import {
  getExtensionFromUrl
} from "./chunk-ILMKZBO5.js";
import {
  CHANNEL_SET_USER_AGENT,
  CommonModule,
  Component,
  DataService,
  ElementRef,
  Input,
  ViewChild,
  ViewEncapsulation,
  __async,
  __commonJS,
  __spreadProps,
  __spreadValues,
  __toESM,
  setClassMetadata,
  ɵsetClassDebugInfo,
  ɵɵNgOnChangesFeature,
  ɵɵdefineComponent,
  ɵɵdirectiveInject,
  ɵɵelement,
  ɵɵelementEnd,
  ɵɵelementStart,
  ɵɵloadQuery,
  ɵɵqueryRefresh,
  ɵɵtext,
  ɵɵviewQuery
} from "./chunk-OHPFONIX.js";

// node_modules/.pnpm/artplayer@5.2.1/node_modules/artplayer/dist/artplayer.js
var require_artplayer = __commonJS({
  "node_modules/.pnpm/artplayer@5.2.1/node_modules/artplayer/dist/artplayer.js"(exports, module) {
    !function(e, t2, r2, a, o) {
      var i = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : "undefined" != typeof window ? window : "undefined" != typeof global ? global : {}, n = "function" == typeof i[a] && i[a], s = n.cache || {}, l = "undefined" != typeof module && "function" == typeof module.require && module.require.bind(module);
      function c(t3, r3) {
        if (!s[t3]) {
          if (!e[t3]) {
            var o2 = "function" == typeof i[a] && i[a];
            if (!r3 && o2) return o2(t3, true);
            if (n) return n(t3, true);
            if (l && "string" == typeof t3) return l(t3);
            var p2 = Error("Cannot find module '" + t3 + "'");
            throw p2.code = "MODULE_NOT_FOUND", p2;
          }
          d2.resolve = function(r4) {
            var a2 = e[t3][1][r4];
            return null != a2 ? a2 : r4;
          }, d2.cache = {};
          var u2 = s[t3] = new c.Module(t3);
          e[t3][0].call(u2.exports, d2, u2, u2.exports, this);
        }
        return s[t3].exports;
        function d2(e2) {
          var t4 = d2.resolve(e2);
          return false === t4 ? {} : c(t4);
        }
      }
      c.isParcelRequire = true, c.Module = function(e2) {
        this.id = e2, this.bundle = c, this.exports = {};
      }, c.modules = e, c.cache = s, c.parent = n, c.register = function(t3, r3) {
        e[t3] = [function(e2, t4) {
          t4.exports = r3;
        }, {}];
      }, Object.defineProperty(c, "root", {
        get: function() {
          return i[a];
        }
      }), i[a] = c;
      for (var p = 0; p < t2.length; p++) c(t2[p]);
      if (r2) {
        var u = c(r2);
        "object" == typeof exports && "undefined" != typeof module ? module.exports = u : "function" == typeof define && define.amd && define(function() {
          return u;
        });
      }
    }({
      "5lTcX": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("bundle-text:./style/index.less"), i = a.interopDefault(o), n = e("option-validator"), s = a.interopDefault(n), l = e("./utils/emitter"), c = a.interopDefault(l), p = e("./utils"), u = e("./scheme"), d2 = a.interopDefault(u), f = e("./config"), h = a.interopDefault(f), m = e("./template"), g = a.interopDefault(m), v = e("./i18n"), y = a.interopDefault(v), b = e("./player"), x = a.interopDefault(b), w = e("./control"), j = a.interopDefault(w), k = e("./contextmenu"), C = a.interopDefault(k), S = e("./info"), I = a.interopDefault(S), T = e("./subtitle"), $2 = a.interopDefault(T), E = e("./events"), M = a.interopDefault(E), F = e("./hotkey"), H = a.interopDefault(F), z = e("./layer"), D = a.interopDefault(z), A = e("./loading"), R = a.interopDefault(A), O = e("./notice"), Y = a.interopDefault(O), L = e("./mask"), P = a.interopDefault(L), V = e("./icons"), q = a.interopDefault(V), _ = e("./setting"), N = a.interopDefault(_), B = e("./storage"), W = a.interopDefault(B), U = e("./plugins"), K = a.interopDefault(U);
        let Z = 0, X = [];
        class G extends c.default {
          constructor(e2, t3) {
            super(), this.id = ++Z;
            let r3 = p.mergeDeep(G.option, e2);
            if (r3.container = e2.container, this.option = (0, s.default)(r3, d2.default), this.isLock = false, this.isReady = false, this.isFocus = false, this.isInput = false, this.isRotate = false, this.isDestroy = false, this.template = new g.default(this), this.events = new M.default(this), this.storage = new W.default(this), this.icons = new q.default(this), this.i18n = new y.default(this), this.notice = new Y.default(this), this.player = new x.default(this), this.layers = new D.default(this), this.controls = new j.default(this), this.contextmenu = new C.default(this), this.subtitle = new $2.default(this), this.info = new I.default(this), this.loading = new R.default(this), this.hotkey = new H.default(this), this.mask = new P.default(this), this.setting = new N.default(this), this.plugins = new K.default(this), "function" == typeof t3 && this.on("ready", () => t3.call(this, this)), G.DEBUG) {
              let e3 = (e4) => console.log(`[ART.${this.id}] -> ${e4}`);
              e3("Version@" + G.version), e3("Env@" + G.env), e3("Build@" + G.build);
              for (let t4 = 0; t4 < h.default.events.length; t4++) this.on("video:" + h.default.events[t4], (t5) => e3("Event@" + t5.type));
            }
            X.push(this);
          }
          static get instances() {
            return X;
          }
          static get version() {
            return "5.2.1";
          }
          static get env() {
            return "production";
          }
          static get build() {
            return "2024-10-26 15:26:30";
          }
          static get config() {
            return h.default;
          }
          static get utils() {
            return p;
          }
          static get scheme() {
            return d2.default;
          }
          static get Emitter() {
            return c.default;
          }
          static get validator() {
            return s.default;
          }
          static get kindOf() {
            return s.default.kindOf;
          }
          static get html() {
            return g.default.html;
          }
          static get option() {
            return {
              id: "",
              container: "#artplayer",
              url: "",
              poster: "",
              type: "",
              theme: "#f00",
              volume: 0.7,
              isLive: false,
              muted: false,
              autoplay: false,
              autoSize: false,
              autoMini: false,
              loop: false,
              flip: false,
              playbackRate: false,
              aspectRatio: false,
              screenshot: false,
              setting: false,
              hotkey: true,
              pip: false,
              mutex: true,
              backdrop: true,
              fullscreen: false,
              fullscreenWeb: false,
              subtitleOffset: false,
              miniProgressBar: false,
              useSSR: false,
              playsInline: true,
              lock: false,
              fastForward: false,
              autoPlayback: false,
              autoOrientation: false,
              airplay: false,
              proxy: void 0,
              layers: [],
              contextmenu: [],
              controls: [],
              settings: [],
              quality: [],
              highlight: [],
              plugins: [],
              thumbnails: {
                url: "",
                number: 60,
                column: 10,
                width: 0,
                height: 0,
                scale: 1
              },
              subtitle: {
                url: "",
                type: "",
                style: {},
                name: "",
                escape: true,
                encoding: "utf-8",
                onVttLoad: (e2) => e2
              },
              moreVideoAttr: {
                controls: false,
                preload: p.isSafari ? "auto" : "metadata"
              },
              i18n: {},
              icons: {},
              cssVar: {},
              customType: {},
              lang: navigator.language.toLowerCase()
            };
          }
          get proxy() {
            return this.events.proxy;
          }
          get query() {
            return this.template.query;
          }
          get video() {
            return this.template.$video;
          }
          destroy(e2 = true) {
            this.events.destroy(), this.template.destroy(e2), X.splice(X.indexOf(this), 1), this.isDestroy = true, this.emit("destroy");
          }
        }
        r2.default = G, G.STYLE = i.default, G.DEBUG = false, G.CONTEXTMENU = true, G.NOTICE_TIME = 2e3, G.SETTING_WIDTH = 250, G.SETTING_ITEM_WIDTH = 200, G.SETTING_ITEM_HEIGHT = 35, G.RESIZE_TIME = 200, G.SCROLL_TIME = 200, G.SCROLL_GAP = 50, G.AUTO_PLAYBACK_MAX = 10, G.AUTO_PLAYBACK_MIN = 5, G.AUTO_PLAYBACK_TIMEOUT = 3e3, G.RECONNECT_TIME_MAX = 5, G.RECONNECT_SLEEP_TIME = 1e3, G.CONTROL_HIDE_TIME = 3e3, G.DBCLICK_TIME = 300, G.DBCLICK_FULLSCREEN = true, G.MOBILE_DBCLICK_PLAY = true, G.MOBILE_CLICK_PLAY = false, G.AUTO_ORIENTATION_TIME = 200, G.INFO_LOOP_TIME = 1e3, G.FAST_FORWARD_VALUE = 3, G.FAST_FORWARD_TIME = 1e3, G.TOUCH_MOVE_RATIO = 0.5, G.VOLUME_STEP = 0.1, G.SEEK_STEP = 5, G.PLAYBACK_RATE = [0.5, 0.75, 1, 1.25, 1.5, 2], G.ASPECT_RATIO = ["default", "4:3", "16:9"], G.FLIP = ["normal", "horizontal", "vertical"], G.FULLSCREEN_WEB_IN_BODY = false, G.LOG_VERSION = true, G.USE_RAF = false, p.isBrowser && (window.Artplayer = G, p.setStyleText("artplayer-style", i.default), setTimeout(() => {
          G.LOG_VERSION && console.log(`%c ArtPlayer %c ${G.version} %c https://artplayer.org`, "color: #fff; background: #5f5f5f", "color: #fff; background: #4bc729", "");
        }, 100));
      }, {
        "bundle-text:./style/index.less": "0016T",
        "option-validator": "bAWi2",
        "./utils/emitter": "66mFZ",
        "./utils": "71aH7",
        "./scheme": "AKEiO",
        "./config": "lyjeQ",
        "./template": "X13Zf",
        "./i18n": "3jKkj",
        "./player": "a90nx",
        "./control": "8Z0Uf",
        "./contextmenu": "2KYsr",
        "./info": "02ajl",
        "./subtitle": "eSWto",
        "./events": "jo4S1",
        "./hotkey": "6NoFy",
        "./layer": "6G6hZ",
        "./loading": "3dsEe",
        "./notice": "dWGTw",
        "./mask": "5POkG",
        "./icons": "6OeNg",
        "./setting": "3eYNH",
        "./storage": "2aaJe",
        "./plugins": "8MTUM",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "0016T": [function(e, t2, r2) {
        t2.exports = '.art-video-player{--art-theme:red;--art-font-color:#fff;--art-background-color:#000;--art-text-shadow-color:#00000080;--art-transition-duration:.2s;--art-padding:10px;--art-border-radius:3px;--art-progress-height:6px;--art-progress-color:#ffffff40;--art-hover-color:#ffffff40;--art-loaded-color:#ffffff40;--art-state-size:80px;--art-state-opacity:.8;--art-bottom-height:100px;--art-bottom-offset:20px;--art-bottom-gap:5px;--art-highlight-width:8px;--art-highlight-color:#ffffff80;--art-control-height:46px;--art-control-opacity:.75;--art-control-icon-size:36px;--art-control-icon-scale:1.1;--art-volume-height:120px;--art-volume-handle-size:14px;--art-lock-size:36px;--art-indicator-scale:0;--art-indicator-size:16px;--art-fullscreen-web-index:9999;--art-settings-icon-size:24px;--art-settings-max-height:300px;--art-selector-max-height:300px;--art-contextmenus-min-width:250px;--art-subtitle-font-size:20px;--art-subtitle-gap:5px;--art-subtitle-bottom:15px;--art-subtitle-border:#000;--art-widget-background:#000000d9;--art-tip-background:#000000b3;--art-scrollbar-size:4px;--art-scrollbar-background:#ffffff40;--art-scrollbar-background-hover:#ffffff80;--art-mini-progress-height:2px}.art-bg-cover{background-position:50%;background-repeat:no-repeat;background-size:cover}.art-bottom-gradient{background-image:linear-gradient(#0000,#0006,#000);background-position:bottom;background-repeat:repeat-x}.art-backdrop-filter{backdrop-filter:saturate(180%)blur(20px);background-color:#000000bf!important}.art-truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.art-video-player{zoom:1;text-align:left;user-select:none;box-sizing:border-box;color:var(--art-font-color);background-color:var(--art-background-color);text-shadow:0 0 2px var(--art-text-shadow-color);-webkit-tap-highlight-color:#0000;-ms-touch-action:manipulation;touch-action:manipulation;-ms-high-contrast-adjust:none;direction:ltr;outline:0;width:100%;height:100%;margin:0 auto;padding:0;font-family:PingFang SC,Helvetica Neue,Microsoft YaHei,Roboto,Arial,sans-serif;font-size:14px;line-height:1.3;position:relative}.art-video-player *,.art-video-player :before,.art-video-player :after{box-sizing:border-box}.art-video-player ::-webkit-scrollbar{width:var(--art-scrollbar-size);height:var(--art-scrollbar-size)}.art-video-player ::-webkit-scrollbar-thumb{background-color:var(--art-scrollbar-background)}.art-video-player ::-webkit-scrollbar-thumb:hover{background-color:var(--art-scrollbar-background-hover)}.art-video-player img{vertical-align:top;max-width:100%}.art-video-player svg{fill:var(--art-font-color)}.art-video-player a{color:var(--art-font-color);text-decoration:none}.art-icon{justify-content:center;align-items:center;line-height:1;display:flex}.art-video-player.art-backdrop .art-contextmenus,.art-video-player.art-backdrop .art-info,.art-video-player.art-backdrop .art-settings,.art-video-player.art-backdrop .art-layer-auto-playback,.art-video-player.art-backdrop .art-selector-list,.art-video-player.art-backdrop .art-volume-inner{backdrop-filter:saturate(180%)blur(20px);background-color:#000000bf!important}.art-video{z-index:10;cursor:pointer;width:100%;height:100%;position:absolute;inset:0}.art-poster{z-index:11;pointer-events:none;background-position:50%;background-repeat:no-repeat;background-size:cover;width:100%;height:100%;position:absolute;inset:0}.art-video-player .art-subtitle{z-index:20;text-align:center;pointer-events:none;justify-content:center;align-items:center;gap:var(--art-subtitle-gap);bottom:var(--art-subtitle-bottom);font-size:var(--art-subtitle-font-size);transition:bottom var(--art-transition-duration)ease;text-shadow:var(--art-subtitle-border)1px 0 1px,var(--art-subtitle-border)0 1px 1px,var(--art-subtitle-border)-1px 0 1px,var(--art-subtitle-border)0 -1px 1px,var(--art-subtitle-border)1px 1px 1px,var(--art-subtitle-border)-1px -1px 1px,var(--art-subtitle-border)1px -1px 1px,var(--art-subtitle-border)-1px 1px 1px;flex-direction:column;width:100%;padding:0 5%;display:none;position:absolute}.art-video-player.art-subtitle-show .art-subtitle{display:flex}.art-video-player.art-control-show .art-subtitle{bottom:calc(var(--art-control-height) + var(--art-subtitle-bottom))}.art-danmuku{z-index:30;pointer-events:none;width:100%;height:100%;position:absolute;inset:0;overflow:hidden}.art-video-player .art-layers{z-index:40;pointer-events:none;width:100%;height:100%;display:none;position:absolute;inset:0}.art-video-player .art-layers .art-layer{pointer-events:auto}.art-video-player.art-layer-show .art-layers{display:flex}.art-video-player .art-mask{z-index:50;pointer-events:none;justify-content:center;align-items:center;width:100%;height:100%;display:flex;position:absolute;inset:0}.art-video-player .art-mask .art-state{opacity:0;width:var(--art-state-size);height:var(--art-state-size);transition:all var(--art-transition-duration)ease;justify-content:center;align-items:center;display:flex;transform:scale(2)}.art-video-player.art-mask-show .art-state{cursor:pointer;pointer-events:auto;opacity:var(--art-state-opacity);transform:scale(1)}.art-video-player.art-loading-show .art-state{display:none}.art-video-player .art-loading{z-index:70;pointer-events:none;justify-content:center;align-items:center;width:100%;height:100%;display:none;position:absolute;inset:0}.art-video-player.art-loading-show .art-loading{display:flex}.art-video-player .art-bottom{z-index:60;opacity:0;pointer-events:none;padding:0 var(--art-padding);transition:all var(--art-transition-duration)ease;background-size:100% var(--art-bottom-height);background-image:linear-gradient(#0000,#0006,#000);background-position:bottom;background-repeat:repeat-x;flex-direction:column;justify-content:flex-end;width:100%;height:100%;display:flex;position:absolute;inset:0;overflow:hidden}.art-video-player .art-bottom .art-controls,.art-video-player .art-bottom .art-progress{transform:translateY(var(--art-bottom-offset));transition:transform var(--art-transition-duration)ease}.art-video-player.art-control-show .art-bottom,.art-video-player.art-hover .art-bottom{opacity:1}.art-video-player.art-control-show .art-bottom .art-controls,.art-video-player.art-hover .art-bottom .art-controls,.art-video-player.art-control-show .art-bottom .art-progress,.art-video-player.art-hover .art-bottom .art-progress{transform:translateY(0)}.art-bottom .art-progress{z-index:0;pointer-events:auto;padding-bottom:var(--art-bottom-gap);position:relative}.art-bottom .art-progress .art-control-progress{cursor:pointer;height:var(--art-progress-height);justify-content:center;align-items:center;display:flex;position:relative}.art-bottom .art-progress .art-control-progress .art-control-progress-inner{transition:height var(--art-transition-duration)ease;background-color:var(--art-progress-color);align-items:center;width:100%;height:50%;display:flex;position:relative}.art-bottom .art-progress .art-control-progress .art-control-progress-inner .art-progress-hover{z-index:0;background-color:var(--art-hover-color);width:0%;height:100%;position:absolute;inset:0}.art-bottom .art-progress .art-control-progress .art-control-progress-inner .art-progress-loaded{z-index:10;background-color:var(--art-loaded-color);width:0%;height:100%;position:absolute;inset:0}.art-bottom .art-progress .art-control-progress .art-control-progress-inner .art-progress-played{z-index:20;background-color:var(--art-theme);width:0%;height:100%;position:absolute;inset:0}.art-bottom .art-progress .art-control-progress .art-control-progress-inner .art-progress-highlight{z-index:30;pointer-events:none;width:100%;height:100%;position:absolute;inset:0}.art-bottom .art-progress .art-control-progress .art-control-progress-inner .art-progress-highlight span{z-index:0;pointer-events:auto;transform:translateX(calc(var(--art-highlight-width)/-2));background-color:var(--art-highlight-color);width:100%;height:100%;position:absolute;inset:0 auto 0 0;width:var(--art-highlight-width)!important}.art-bottom .art-progress .art-control-progress .art-control-progress-inner .art-progress-indicator{z-index:40;width:var(--art-indicator-size);height:var(--art-indicator-size);transform:scale(var(--art-indicator-scale));margin-left:calc(var(--art-indicator-size)/-2);transition:transform var(--art-transition-duration)ease;border-radius:50%;justify-content:center;align-items:center;display:flex;position:absolute;left:0}.art-bottom .art-progress .art-control-progress .art-control-progress-inner .art-progress-indicator .art-icon{pointer-events:none;width:100%;height:100%}.art-bottom .art-progress .art-control-progress .art-control-progress-inner .art-progress-indicator:hover{transform:scale(1.2)!important}.art-bottom .art-progress .art-control-progress .art-control-progress-inner .art-progress-indicator:active{transform:scale(1)!important}.art-bottom .art-progress .art-control-progress .art-control-progress-inner .art-progress-tip{z-index:50;border-radius:var(--art-border-radius);white-space:nowrap;background-color:var(--art-tip-background);padding:3px 5px;font-size:12px;line-height:1;display:none;position:absolute;top:-25px;left:0}.art-bottom .art-progress .art-control-progress:hover .art-control-progress-inner{height:100%}.art-bottom .art-progress .art-control-thumbnails{bottom:calc(var(--art-bottom-gap) + 10px);border-radius:var(--art-border-radius);pointer-events:none;background-color:var(--art-widget-background);display:none;position:absolute;left:0;box-shadow:0 1px 3px #0003,0 1px 2px -1px #0003}.art-bottom:hover .art-progress .art-control-progress .art-control-progress-inner .art-progress-indicator{transform:scale(1)}.art-controls{z-index:10;pointer-events:auto;height:var(--art-control-height);justify-content:space-between;align-items:center;display:flex;position:relative}.art-controls .art-controls-left,.art-controls .art-controls-right{height:100%;display:flex}.art-controls .art-controls-center{flex:1;justify-content:center;align-items:center;height:100%;padding:0 10px;display:none}.art-controls .art-controls-right{justify-content:flex-end}.art-controls .art-control{cursor:pointer;white-space:nowrap;opacity:var(--art-control-opacity);min-height:var(--art-control-height);min-width:var(--art-control-height);transition:opacity var(--art-transition-duration)ease;flex-shrink:0;justify-content:center;align-items:center;display:flex}.art-controls .art-control .art-icon{height:var(--art-control-icon-size);width:var(--art-control-icon-size);transform:scale(var(--art-control-icon-scale));transition:transform var(--art-transition-duration)ease}.art-controls .art-control .art-icon:active{transform:scale(calc(var(--art-control-icon-scale)*.8))}.art-controls .art-control:hover{opacity:1}.art-control-volume{position:relative}.art-control-volume .art-volume-panel{text-align:center;cursor:default;opacity:0;pointer-events:none;left:0;right:0;bottom:var(--art-control-height);width:var(--art-control-height);height:var(--art-volume-height);transition:all var(--art-transition-duration)ease;justify-content:center;align-items:center;padding:0 5px;font-size:12px;display:flex;position:absolute;transform:translateY(10px)}.art-control-volume .art-volume-panel .art-volume-inner{border-radius:var(--art-border-radius);background-color:var(--art-widget-background);flex-direction:column;align-items:center;gap:10px;width:100%;height:100%;padding:10px 0 12px;display:flex}.art-control-volume .art-volume-panel .art-volume-inner .art-volume-slider{cursor:pointer;flex:1;justify-content:center;width:100%;display:flex;position:relative}.art-control-volume .art-volume-panel .art-volume-inner .art-volume-slider .art-volume-handle{border-radius:var(--art-border-radius);background-color:#ffffff40;justify-content:center;width:2px;display:flex;position:relative;overflow:hidden}.art-control-volume .art-volume-panel .art-volume-inner .art-volume-slider .art-volume-handle .art-volume-loaded{z-index:0;background-color:var(--art-theme);width:100%;height:100%;position:absolute;inset:0}.art-control-volume .art-volume-panel .art-volume-inner .art-volume-slider .art-volume-indicator{width:var(--art-volume-handle-size);height:var(--art-volume-handle-size);margin-top:calc(var(--art-volume-handle-size)/-2);background-color:var(--art-theme);transition:transform var(--art-transition-duration)ease;border-radius:100%;flex-shrink:0;position:absolute;transform:scale(1)}.art-control-volume .art-volume-panel .art-volume-inner .art-volume-slider:active .art-volume-indicator{transform:scale(.9)}.art-control-volume:hover .art-volume-panel{opacity:1;pointer-events:auto;transform:translateY(0)}.art-video-player .art-notice{z-index:80;padding:var(--art-padding);pointer-events:none;width:100%;height:auto;display:none;position:absolute;inset:0 0 auto}.art-video-player .art-notice .art-notice-inner{border-radius:var(--art-border-radius);background-color:var(--art-tip-background);padding:5px;line-height:1;display:inline-flex}.art-video-player.art-notice-show .art-notice{display:flex}.art-video-player .art-contextmenus{z-index:120;border-radius:var(--art-border-radius);background-color:var(--art-widget-background);min-width:var(--art-contextmenus-min-width);flex-direction:column;padding:5px 0;font-size:12px;display:none;position:absolute}.art-video-player .art-contextmenus .art-contextmenu{cursor:pointer;border-bottom:1px solid #ffffff1a;padding:10px 15px;display:flex}.art-video-player .art-contextmenus .art-contextmenu span{padding:0 8px}.art-video-player .art-contextmenus .art-contextmenu span:hover,.art-video-player .art-contextmenus .art-contextmenu span.art-current{color:var(--art-theme)}.art-video-player .art-contextmenus .art-contextmenu:hover{background-color:#ffffff1a}.art-video-player .art-contextmenus .art-contextmenu:last-child{border-bottom:none}.art-video-player.art-contextmenu-show .art-contextmenus{display:flex}.art-video-player .art-settings{z-index:90;border-radius:var(--art-border-radius);max-height:var(--art-settings-max-height);left:auto;right:var(--art-padding);bottom:var(--art-control-height);transition:all var(--art-transition-duration)ease;background-color:var(--art-widget-background);flex-direction:column;display:none;position:absolute;overflow:hidden auto}.art-video-player .art-settings .art-setting-panel{flex-direction:column;display:none}.art-video-player .art-settings .art-setting-panel.art-current{display:flex}.art-video-player .art-settings .art-setting-panel .art-setting-item{cursor:pointer;transition:background-color var(--art-transition-duration)ease;justify-content:space-between;align-items:center;padding:0 5px;display:flex;overflow:hidden}.art-video-player .art-settings .art-setting-panel .art-setting-item:hover{background-color:#ffffff1a}.art-video-player .art-settings .art-setting-panel .art-setting-item.art-current{color:var(--art-theme)}.art-video-player .art-settings .art-setting-panel .art-setting-item .art-icon-check{visibility:hidden;height:15px}.art-video-player .art-settings .art-setting-panel .art-setting-item.art-current .art-icon-check{visibility:visible}.art-video-player .art-settings .art-setting-panel .art-setting-item .art-setting-item-left{flex-shrink:0;justify-content:center;align-items:center;gap:5px;display:flex}.art-video-player .art-settings .art-setting-panel .art-setting-item .art-setting-item-left .art-setting-item-left-icon{height:var(--art-settings-icon-size);width:var(--art-settings-icon-size);justify-content:center;align-items:center;display:flex}.art-video-player .art-settings .art-setting-panel .art-setting-item .art-setting-item-right{justify-content:center;align-items:center;gap:5px;font-size:12px;display:flex}.art-video-player .art-settings .art-setting-panel .art-setting-item .art-setting-item-right .art-setting-item-right-tooltip{white-space:nowrap;color:#ffffff80}.art-video-player .art-settings .art-setting-panel .art-setting-item .art-setting-item-right .art-setting-item-right-icon{justify-content:center;align-items:center;min-width:32px;height:24px;display:flex}.art-video-player .art-settings .art-setting-panel .art-setting-item .art-setting-item-right .art-setting-range{appearance:none;background-color:#fff3;outline:none;width:80px;height:3px}.art-video-player .art-settings .art-setting-panel .art-setting-item-back{border-bottom:1px solid #ffffff1a}.art-video-player.art-setting-show .art-settings{display:flex}.art-video-player .art-info{left:var(--art-padding);top:var(--art-padding);z-index:100;border-radius:var(--art-border-radius);background-color:var(--art-widget-background);padding:10px;font-size:12px;display:none;position:absolute}.art-video-player .art-info .art-info-panel{flex-direction:column;gap:5px;display:flex}.art-video-player .art-info .art-info-panel .art-info-item{align-items:center;gap:5px;display:flex}.art-video-player .art-info .art-info-panel .art-info-item .art-info-title{text-align:right;width:100px}.art-video-player .art-info .art-info-panel .art-info-item .art-info-content{text-overflow:ellipsis;white-space:nowrap;user-select:all;width:250px;overflow:hidden}.art-video-player .art-info .art-info-close{cursor:pointer;position:absolute;top:5px;right:5px}.art-video-player.art-info-show .art-info{display:flex}.art-hide-cursor *{cursor:none!important}.art-video-player[data-aspect-ratio]{overflow:hidden}.art-video-player[data-aspect-ratio] .art-video{object-fit:fill;box-sizing:content-box}.art-fullscreen{--art-progress-height:8px;--art-indicator-size:20px;--art-control-height:60px;--art-control-icon-scale:1.3}.art-fullscreen-web{--art-progress-height:8px;--art-indicator-size:20px;--art-control-height:60px;--art-control-icon-scale:1.3;z-index:var(--art-fullscreen-web-index);width:100%;height:100%;position:fixed;inset:0}.art-mini-popup{z-index:9999;border-radius:var(--art-border-radius);cursor:move;user-select:none;background:#000;width:320px;height:180px;transition:opacity .2s;position:fixed;overflow:hidden;box-shadow:0 0 5px #00000080}.art-mini-popup svg{fill:#fff}.art-mini-popup .art-video{pointer-events:none}.art-mini-popup .art-mini-close{z-index:20;cursor:pointer;opacity:0;transition:opacity .2s;position:absolute;top:10px;right:10px}.art-mini-popup .art-mini-state{z-index:30;pointer-events:none;opacity:0;background-color:#00000040;justify-content:center;align-items:center;width:100%;height:100%;transition:opacity .2s;display:flex;position:absolute;inset:0}.art-mini-popup .art-mini-state .art-icon{opacity:.75;cursor:pointer;pointer-events:auto;transition:transform .2s;transform:scale(3)}.art-mini-popup .art-mini-state .art-icon:active{transform:scale(2.5)}.art-mini-popup.art-mini-droging{opacity:.9}.art-mini-popup:hover .art-mini-close,.art-mini-popup:hover .art-mini-state{opacity:1}.art-video-player[data-flip=horizontal] .art-video{transform:scaleX(-1)}.art-video-player[data-flip=vertical] .art-video{transform:scaleY(-1)}.art-video-player .art-layer-lock{height:var(--art-lock-size);width:var(--art-lock-size);top:50%;left:var(--art-padding);background-color:var(--art-tip-background);border-radius:50%;justify-content:center;align-items:center;display:none;position:absolute;transform:translateY(-50%)}.art-video-player .art-layer-auto-playback{border-radius:var(--art-border-radius);left:var(--art-padding);bottom:calc(var(--art-control-height) + var(--art-bottom-gap) + 10px);background-color:var(--art-widget-background);align-items:center;gap:10px;padding:10px;line-height:1;display:none;position:absolute}.art-video-player .art-layer-auto-playback .art-auto-playback-close{cursor:pointer;justify-content:center;align-items:center;display:flex}.art-video-player .art-layer-auto-playback .art-auto-playback-close svg{fill:var(--art-theme);width:15px;height:15px}.art-video-player .art-layer-auto-playback .art-auto-playback-jump{color:var(--art-theme);cursor:pointer}.art-video-player.art-lock .art-subtitle{bottom:var(--art-subtitle-bottom)!important}.art-video-player.art-mini-progress-bar .art-bottom,.art-video-player.art-lock .art-bottom{opacity:1;background-image:none;padding:0}.art-video-player.art-mini-progress-bar .art-bottom .art-controls,.art-video-player.art-lock .art-bottom .art-controls,.art-video-player.art-mini-progress-bar .art-bottom .art-progress,.art-video-player.art-lock .art-bottom .art-progress{transform:translateY(calc(var(--art-control-height) + var(--art-bottom-gap) + var(--art-progress-height)/4))}.art-video-player.art-mini-progress-bar .art-bottom .art-progress-indicator,.art-video-player.art-lock .art-bottom .art-progress-indicator{display:none!important}.art-video-player.art-control-show .art-layer-lock{display:flex}.art-control-selector{justify-content:center;display:flex;position:relative}.art-control-selector .art-selector-list{text-align:center;border-radius:var(--art-border-radius);opacity:0;pointer-events:none;bottom:var(--art-control-height);max-height:var(--art-selector-max-height);background-color:var(--art-widget-background);transition:all var(--art-transition-duration)ease;flex-direction:column;align-items:center;display:flex;position:absolute;overflow:hidden auto;transform:translateY(10px)}.art-control-selector .art-selector-list .art-selector-item{flex-shrink:0;justify-content:center;align-items:center;width:100%;padding:10px 15px;line-height:1;display:flex}.art-control-selector .art-selector-list .art-selector-item:hover{background-color:#ffffff1a}.art-control-selector .art-selector-list .art-selector-item:hover,.art-control-selector .art-selector-list .art-selector-item.art-current{color:var(--art-theme)}.art-control-selector:hover .art-selector-list{opacity:1;pointer-events:auto;transform:translateY(0)}[class*=hint--]{font-style:normal;display:inline-block;position:relative}[class*=hint--]:before,[class*=hint--]:after{visibility:hidden;opacity:0;z-index:1000000;pointer-events:none;transition:all .3s;position:absolute;transform:translate(0,0)}[class*=hint--]:hover:before,[class*=hint--]:hover:after{visibility:visible;opacity:1;transition-delay:.1s}[class*=hint--]:before{content:"";z-index:1000001;background:0 0;border:6px solid #0000;position:absolute}[class*=hint--]:after{color:#fff;white-space:nowrap;background:#000;padding:8px 10px;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:12px;line-height:12px}[class*=hint--][aria-label]:after{content:attr(aria-label)}[class*=hint--][data-hint]:after{content:attr(data-hint)}[aria-label=""]:before,[aria-label=""]:after,[data-hint=""]:before,[data-hint=""]:after{display:none!important}.hint--top-left:before,.hint--top-right:before,.hint--top:before{border-top-color:#000}.hint--bottom-left:before,.hint--bottom-right:before,.hint--bottom:before{border-bottom-color:#000}.hint--left:before{border-left-color:#000}.hint--right:before{border-right-color:#000}.hint--top:before{margin-bottom:-11px}.hint--top:before,.hint--top:after{bottom:100%;left:50%}.hint--top:before{left:calc(50% - 6px)}.hint--top:after{transform:translate(-50%)}.hint--top:hover:before{transform:translateY(-8px)}.hint--top:hover:after{transform:translate(-50%)translateY(-8px)}.hint--bottom:before{margin-top:-11px}.hint--bottom:before,.hint--bottom:after{top:100%;left:50%}.hint--bottom:before{left:calc(50% - 6px)}.hint--bottom:after{transform:translate(-50%)}.hint--bottom:hover:before{transform:translateY(8px)}.hint--bottom:hover:after{transform:translate(-50%)translateY(8px)}.hint--right:before{margin-bottom:-6px;margin-left:-11px}.hint--right:after{margin-bottom:-14px}.hint--right:before,.hint--right:after{bottom:50%;left:100%}.hint--right:hover:before,.hint--right:hover:after{transform:translate(8px)}.hint--left:before{margin-bottom:-6px;margin-right:-11px}.hint--left:after{margin-bottom:-14px}.hint--left:before,.hint--left:after{bottom:50%;right:100%}.hint--left:hover:before,.hint--left:hover:after{transform:translate(-8px)}.hint--top-left:before{margin-bottom:-11px}.hint--top-left:before,.hint--top-left:after{bottom:100%;left:50%}.hint--top-left:before{left:calc(50% - 6px)}.hint--top-left:after{margin-left:12px;transform:translate(-100%)}.hint--top-left:hover:before{transform:translateY(-8px)}.hint--top-left:hover:after{transform:translate(-100%)translateY(-8px)}.hint--top-right:before{margin-bottom:-11px}.hint--top-right:before,.hint--top-right:after{bottom:100%;left:50%}.hint--top-right:before{left:calc(50% - 6px)}.hint--top-right:after{margin-left:-12px;transform:translate(0)}.hint--top-right:hover:before,.hint--top-right:hover:after{transform:translateY(-8px)}.hint--bottom-left:before{margin-top:-11px}.hint--bottom-left:before,.hint--bottom-left:after{top:100%;left:50%}.hint--bottom-left:before{left:calc(50% - 6px)}.hint--bottom-left:after{margin-left:12px;transform:translate(-100%)}.hint--bottom-left:hover:before{transform:translateY(8px)}.hint--bottom-left:hover:after{transform:translate(-100%)translateY(8px)}.hint--bottom-right:before{margin-top:-11px}.hint--bottom-right:before,.hint--bottom-right:after{top:100%;left:50%}.hint--bottom-right:before{left:calc(50% - 6px)}.hint--bottom-right:after{margin-left:-12px;transform:translate(0)}.hint--bottom-right:hover:before,.hint--bottom-right:hover:after{transform:translateY(8px)}.hint--small:after,.hint--medium:after,.hint--large:after{white-space:normal;word-wrap:break-word;line-height:1.4em}.hint--small:after{width:80px}.hint--medium:after{width:150px}.hint--large:after{width:300px}[class*=hint--]:after{text-shadow:0 -1px #000;box-shadow:4px 4px 8px #0000004d}.hint--error:after{text-shadow:0 -1px #592726;background-color:#b34e4d}.hint--error.hint--top-left:before,.hint--error.hint--top-right:before,.hint--error.hint--top:before{border-top-color:#b34e4d}.hint--error.hint--bottom-left:before,.hint--error.hint--bottom-right:before,.hint--error.hint--bottom:before{border-bottom-color:#b34e4d}.hint--error.hint--left:before{border-left-color:#b34e4d}.hint--error.hint--right:before{border-right-color:#b34e4d}.hint--warning:after{text-shadow:0 -1px #6c5328;background-color:#c09854}.hint--warning.hint--top-left:before,.hint--warning.hint--top-right:before,.hint--warning.hint--top:before{border-top-color:#c09854}.hint--warning.hint--bottom-left:before,.hint--warning.hint--bottom-right:before,.hint--warning.hint--bottom:before{border-bottom-color:#c09854}.hint--warning.hint--left:before{border-left-color:#c09854}.hint--warning.hint--right:before{border-right-color:#c09854}.hint--info:after{text-shadow:0 -1px #1a3c4d;background-color:#3986ac}.hint--info.hint--top-left:before,.hint--info.hint--top-right:before,.hint--info.hint--top:before{border-top-color:#3986ac}.hint--info.hint--bottom-left:before,.hint--info.hint--bottom-right:before,.hint--info.hint--bottom:before{border-bottom-color:#3986ac}.hint--info.hint--left:before{border-left-color:#3986ac}.hint--info.hint--right:before{border-right-color:#3986ac}.hint--success:after{text-shadow:0 -1px #1a321a;background-color:#458746}.hint--success.hint--top-left:before,.hint--success.hint--top-right:before,.hint--success.hint--top:before{border-top-color:#458746}.hint--success.hint--bottom-left:before,.hint--success.hint--bottom-right:before,.hint--success.hint--bottom:before{border-bottom-color:#458746}.hint--success.hint--left:before{border-left-color:#458746}.hint--success.hint--right:before{border-right-color:#458746}.hint--always:after,.hint--always:before{opacity:1;visibility:visible}.hint--always.hint--top:before{transform:translateY(-8px)}.hint--always.hint--top:after{transform:translate(-50%)translateY(-8px)}.hint--always.hint--top-left:before{transform:translateY(-8px)}.hint--always.hint--top-left:after{transform:translate(-100%)translateY(-8px)}.hint--always.hint--top-right:before,.hint--always.hint--top-right:after{transform:translateY(-8px)}.hint--always.hint--bottom:before{transform:translateY(8px)}.hint--always.hint--bottom:after{transform:translate(-50%)translateY(8px)}.hint--always.hint--bottom-left:before{transform:translateY(8px)}.hint--always.hint--bottom-left:after{transform:translate(-100%)translateY(8px)}.hint--always.hint--bottom-right:before,.hint--always.hint--bottom-right:after{transform:translateY(8px)}.hint--always.hint--left:before,.hint--always.hint--left:after{transform:translate(-8px)}.hint--always.hint--right:before,.hint--always.hint--right:after{transform:translate(8px)}.hint--rounded:after{border-radius:4px}.hint--no-animate:before,.hint--no-animate:after{transition-duration:0s}.hint--bounce:before,.hint--bounce:after{-webkit-transition:opacity .3s,visibility .3s,-webkit-transform .3s cubic-bezier(.71,1.7,.77,1.24);-moz-transition:opacity .3s,visibility .3s,-moz-transform .3s cubic-bezier(.71,1.7,.77,1.24);transition:opacity .3s,visibility .3s,transform .3s cubic-bezier(.71,1.7,.77,1.24)}.hint--no-shadow:before,.hint--no-shadow:after{text-shadow:initial;box-shadow:initial}.hint--no-arrow:before{display:none}.art-video-player.art-mobile{--art-bottom-gap:10px;--art-control-height:38px;--art-control-icon-scale:1;--art-state-size:60px;--art-settings-max-height:180px;--art-selector-max-height:180px;--art-indicator-scale:1;--art-control-opacity:1}.art-video-player.art-mobile .art-controls-left{margin-left:calc(var(--art-padding)/-1)}.art-video-player.art-mobile .art-controls-right{margin-right:calc(var(--art-padding)/-1)}';
      }, {}],
      bAWi2: [function(e, t2, r2) {
        var a;
        a = function() {
          function e2(t4) {
            return (e2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(e3) {
              return typeof e3;
            } : function(e3) {
              return e3 && "function" == typeof Symbol && e3.constructor === Symbol && e3 !== Symbol.prototype ? "symbol" : typeof e3;
            })(t4);
          }
          var t3 = Object.prototype.toString, r3 = function(r4) {
            if (void 0 === r4) return "undefined";
            if (null === r4) return "null";
            var o2 = e2(r4);
            if ("boolean" === o2) return "boolean";
            if ("string" === o2) return "string";
            if ("number" === o2) return "number";
            if ("symbol" === o2) return "symbol";
            if ("function" === o2) return "GeneratorFunction" === a2(r4) ? "generatorfunction" : "function";
            if (Array.isArray ? Array.isArray(r4) : r4 instanceof Array) return "array";
            if (r4.constructor && "function" == typeof r4.constructor.isBuffer && r4.constructor.isBuffer(r4)) return "buffer";
            if (function(e3) {
              try {
                if ("number" == typeof e3.length && "function" == typeof e3.callee) return true;
              } catch (e4) {
                if (-1 !== e4.message.indexOf("callee")) return true;
              }
              return false;
            }(r4)) return "arguments";
            if (r4 instanceof Date || "function" == typeof r4.toDateString && "function" == typeof r4.getDate && "function" == typeof r4.setDate) return "date";
            if (r4 instanceof Error || "string" == typeof r4.message && r4.constructor && "number" == typeof r4.constructor.stackTraceLimit) return "error";
            if (r4 instanceof RegExp || "string" == typeof r4.flags && "boolean" == typeof r4.ignoreCase && "boolean" == typeof r4.multiline && "boolean" == typeof r4.global) return "regexp";
            switch (a2(r4)) {
              case "Symbol":
                return "symbol";
              case "Promise":
                return "promise";
              case "WeakMap":
                return "weakmap";
              case "WeakSet":
                return "weakset";
              case "Map":
                return "map";
              case "Set":
                return "set";
              case "Int8Array":
                return "int8array";
              case "Uint8Array":
                return "uint8array";
              case "Uint8ClampedArray":
                return "uint8clampedarray";
              case "Int16Array":
                return "int16array";
              case "Uint16Array":
                return "uint16array";
              case "Int32Array":
                return "int32array";
              case "Uint32Array":
                return "uint32array";
              case "Float32Array":
                return "float32array";
              case "Float64Array":
                return "float64array";
            }
            if ("function" == typeof r4.throw && "function" == typeof r4.return && "function" == typeof r4.next) return "generator";
            switch (o2 = t3.call(r4)) {
              case "[object Object]":
                return "object";
              case "[object Map Iterator]":
                return "mapiterator";
              case "[object Set Iterator]":
                return "setiterator";
              case "[object String Iterator]":
                return "stringiterator";
              case "[object Array Iterator]":
                return "arrayiterator";
            }
            return o2.slice(8, -1).toLowerCase().replace(/\s/g, "");
          };
          function a2(e3) {
            return e3.constructor ? e3.constructor.name : null;
          }
          function o(e3, t4) {
            var a3 = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : ["option"];
            return i(e3, t4, a3), n(e3, t4, a3), function(e4, t5, a4) {
              var s = r3(t5), l = r3(e4);
              if ("object" === s) {
                if ("object" !== l) throw Error("[Type Error]: '".concat(a4.join("."), "' require 'object' type, but got '").concat(l, "'"));
                Object.keys(t5).forEach(function(r4) {
                  var s2 = e4[r4], l2 = t5[r4], c = a4.slice();
                  c.push(r4), i(s2, l2, c), n(s2, l2, c), o(s2, l2, c);
                });
              }
              if ("array" === s) {
                if ("array" !== l) throw Error("[Type Error]: '".concat(a4.join("."), "' require 'array' type, but got '").concat(l, "'"));
                e4.forEach(function(r4, s2) {
                  var l2 = e4[s2], c = t5[s2] || t5[0], p = a4.slice();
                  p.push(s2), i(l2, c, p), n(l2, c, p), o(l2, c, p);
                });
              }
            }(e3, t4, a3), e3;
          }
          function i(e3, t4, a3) {
            if ("string" === r3(t4)) {
              var o2 = r3(e3);
              if ("?" === t4[0] && (t4 = t4.slice(1) + "|undefined"), !(-1 < t4.indexOf("|") ? t4.split("|").map(function(e4) {
                return e4.toLowerCase().trim();
              }).filter(Boolean).some(function(e4) {
                return o2 === e4;
              }) : t4.toLowerCase().trim() === o2)) throw Error("[Type Error]: '".concat(a3.join("."), "' require '").concat(t4, "' type, but got '").concat(o2, "'"));
            }
          }
          function n(e3, t4, a3) {
            if ("function" === r3(t4)) {
              var o2 = t4(e3, r3(e3), a3);
              if (true !== o2) {
                var i2 = r3(o2);
                throw "string" === i2 ? Error(o2) : "error" === i2 ? o2 : Error("[Validator Error]: The scheme for '".concat(a3.join("."), "' validator require return true, but got '").concat(o2, "'"));
              }
            }
          }
          return o.kindOf = r3, o;
        }, t2.exports = a();
      }, {}],
      "66mFZ": [function(e, t2, r2) {
        e("@parcel/transformer-js/src/esmodule-helpers.js").defineInteropFlag(r2), r2.default = class {
          on(e2, t3, r3) {
            let a = this.e || (this.e = {});
            return (a[e2] || (a[e2] = [])).push({
              fn: t3,
              ctx: r3
            }), this;
          }
          once(e2, t3, r3) {
            let a = this;
            function o(...i) {
              a.off(e2, o), t3.apply(r3, i);
            }
            return o._ = t3, this.on(e2, o, r3);
          }
          emit(e2, ...t3) {
            let r3 = ((this.e || (this.e = {}))[e2] || []).slice();
            for (let e3 = 0; e3 < r3.length; e3 += 1) r3[e3].fn.apply(r3[e3].ctx, t3);
            return this;
          }
          off(e2, t3) {
            let r3 = this.e || (this.e = {}), a = r3[e2], o = [];
            if (a && t3) for (let e3 = 0, r4 = a.length; e3 < r4; e3 += 1) a[e3].fn !== t3 && a[e3].fn._ !== t3 && o.push(a[e3]);
            return o.length ? r3[e2] = o : delete r3[e2], this;
          }
        };
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "9pCYc": [function(e, t2, r2) {
        r2.interopDefault = function(e2) {
          return e2 && e2.__esModule ? e2 : {
            default: e2
          };
        }, r2.defineInteropFlag = function(e2) {
          Object.defineProperty(e2, "__esModule", {
            value: true
          });
        }, r2.exportAll = function(e2, t3) {
          return Object.keys(e2).forEach(function(r3) {
            "default" === r3 || "__esModule" === r3 || Object.prototype.hasOwnProperty.call(t3, r3) || Object.defineProperty(t3, r3, {
              enumerable: true,
              get: function() {
                return e2[r3];
              }
            });
          }), t3;
        }, r2.export = function(e2, t3, r3) {
          Object.defineProperty(e2, t3, {
            enumerable: true,
            get: r3
          });
        };
      }, {}],
      "71aH7": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("./dom");
        a.exportAll(o, r2);
        var i = e("./error");
        a.exportAll(i, r2);
        var n = e("./subtitle");
        a.exportAll(n, r2);
        var s = e("./file");
        a.exportAll(s, r2);
        var l = e("./property");
        a.exportAll(l, r2);
        var c = e("./time");
        a.exportAll(c, r2);
        var p = e("./format");
        a.exportAll(p, r2);
        var u = e("./compatibility");
        a.exportAll(u, r2);
      }, {
        "./dom": "bSNiV",
        "./error": "hwmZz",
        "./subtitle": "inzwq",
        "./file": "6b7Ip",
        "./property": "5NSdr",
        "./time": "epmNy",
        "./format": "gapRl",
        "./compatibility": "6ZTr6",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      bSNiV: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "query", () => i), a.export(r2, "queryAll", () => n), a.export(r2, "addClass", () => s), a.export(r2, "removeClass", () => l), a.export(r2, "hasClass", () => c), a.export(r2, "append", () => p), a.export(r2, "remove", () => u), a.export(r2, "setStyle", () => d2), a.export(r2, "setStyles", () => f), a.export(r2, "getStyle", () => h), a.export(r2, "sublings", () => m), a.export(r2, "inverseClass", () => g), a.export(r2, "tooltip", () => v), a.export(r2, "isInViewport", () => y), a.export(r2, "includeFromEvent", () => b), a.export(r2, "replaceElement", () => x), a.export(r2, "createElement", () => w), a.export(r2, "getIcon", () => j), a.export(r2, "setStyleText", () => k), a.export(r2, "supportsFlex", () => C), a.export(r2, "getRect", () => S), a.export(r2, "loadImg", () => I);
        var o = e("./compatibility");
        function i(e2, t3 = document) {
          return t3.querySelector(e2);
        }
        function n(e2, t3 = document) {
          return Array.from(t3.querySelectorAll(e2));
        }
        function s(e2, t3) {
          return e2.classList.add(t3);
        }
        function l(e2, t3) {
          return e2.classList.remove(t3);
        }
        function c(e2, t3) {
          return e2.classList.contains(t3);
        }
        function p(e2, t3) {
          return t3 instanceof Element ? e2.appendChild(t3) : e2.insertAdjacentHTML("beforeend", String(t3)), e2.lastElementChild || e2.lastChild;
        }
        function u(e2) {
          return e2.parentNode.removeChild(e2);
        }
        function d2(e2, t3, r3) {
          return e2.style[t3] = r3, e2;
        }
        function f(e2, t3) {
          for (let r3 in t3) d2(e2, r3, t3[r3]);
          return e2;
        }
        function h(e2, t3, r3 = true) {
          let a2 = window.getComputedStyle(e2, null).getPropertyValue(t3);
          return r3 ? parseFloat(a2) : a2;
        }
        function m(e2) {
          return Array.from(e2.parentElement.children).filter((t3) => t3 !== e2);
        }
        function g(e2, t3) {
          m(e2).forEach((e3) => l(e3, t3)), s(e2, t3);
        }
        function v(e2, t3, r3 = "top") {
          o.isMobile || (e2.setAttribute("aria-label", t3), s(e2, "hint--rounded"), s(e2, `hint--${r3}`));
        }
        function y(e2, t3 = 0) {
          let r3 = e2.getBoundingClientRect(), a2 = window.innerHeight || document.documentElement.clientHeight, o2 = window.innerWidth || document.documentElement.clientWidth, i2 = r3.top - t3 <= a2 && r3.top + r3.height + t3 >= 0, n2 = r3.left - t3 <= o2 + t3 && r3.left + r3.width + t3 >= 0;
          return i2 && n2;
        }
        function b(e2, t3) {
          return e2.composedPath && e2.composedPath().indexOf(t3) > -1;
        }
        function x(e2, t3) {
          return t3.parentNode.replaceChild(e2, t3), e2;
        }
        function w(e2) {
          return document.createElement(e2);
        }
        function j(e2 = "", t3 = "") {
          let r3 = w("i");
          return s(r3, "art-icon"), s(r3, `art-icon-${e2}`), p(r3, t3), r3;
        }
        function k(e2, t3) {
          let r3 = document.getElementById(e2);
          if (r3) r3.textContent = t3;
          else {
            let r4 = w("style");
            r4.id = e2, r4.textContent = t3, document.head.appendChild(r4);
          }
        }
        function C() {
          let e2 = document.createElement("div");
          return e2.style.display = "flex", "flex" === e2.style.display;
        }
        function S(e2) {
          return e2.getBoundingClientRect();
        }
        function I(e2, t3) {
          return new Promise((r3, a2) => {
            let o2 = new Image();
            o2.crossOrigin = "Anonymous", o2.onload = function() {
              if (t3 && 1 !== t3) {
                let i2 = document.createElement("canvas"), n2 = i2.getContext("2d");
                i2.width = o2.width * t3, i2.height = o2.height * t3, n2.drawImage(o2, 0, 0, i2.width, i2.height), i2.toBlob((t4) => {
                  let o3 = URL.createObjectURL(t4), i3 = new Image();
                  i3.onload = function() {
                    r3(i3);
                  }, i3.onerror = function() {
                    URL.revokeObjectURL(o3), a2(Error(`Image load failed: ${e2}`));
                  }, i3.src = o3;
                });
              } else r3(o2);
            }, o2.onerror = function() {
              a2(Error(`Image load failed: ${e2}`));
            }, o2.src = e2;
          });
        }
      }, {
        "./compatibility": "6ZTr6",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "6ZTr6": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "userAgent", () => o), a.export(r2, "isSafari", () => i), a.export(r2, "isWechat", () => n), a.export(r2, "isIE", () => s), a.export(r2, "isAndroid", () => l), a.export(r2, "isIOS", () => c), a.export(r2, "isIOS13", () => p), a.export(r2, "isMobile", () => u), a.export(r2, "isBrowser", () => d2);
        let o = "undefined" != typeof navigator ? navigator.userAgent : "", i = /^((?!chrome|android).)*safari/i.test(o), n = /MicroMessenger/i.test(o), s = /MSIE|Trident/i.test(o), l = /android/i.test(o), c = /iPad|iPhone|iPod/i.test(o) && !window.MSStream, p = c || o.includes("Macintosh") && navigator.maxTouchPoints >= 1, u = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(o) || p, d2 = "undefined" != typeof window;
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      hwmZz: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "ArtPlayerError", () => o), a.export(r2, "errorHandle", () => i);
        class o extends Error {
          constructor(e2, t3) {
            super(e2), "function" == typeof Error.captureStackTrace && Error.captureStackTrace(this, t3 || this.constructor), this.name = "ArtPlayerError";
          }
        }
        function i(e2, t3) {
          if (!e2) throw new o(t3);
          return e2;
        }
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      inzwq: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2) {
          return "WEBVTT \r\n\r\n".concat(e2.replace(/(\d\d:\d\d:\d\d)[,.](\d+)/g, (e3, t3, r3) => {
            let a2 = r3.slice(0, 3);
            return 1 === r3.length && (a2 = r3 + "00"), 2 === r3.length && (a2 = r3 + "0"), `${t3},${a2}`;
          }).replace(/\{\\([ibu])\}/g, "</$1>").replace(/\{\\([ibu])1\}/g, "<$1>").replace(/\{([ibu])\}/g, "<$1>").replace(/\{\/([ibu])\}/g, "</$1>").replace(/(\d\d:\d\d:\d\d),(\d\d\d)/g, "$1.$2").replace(/{[\s\S]*?}/g, "").concat("\r\n\r\n"));
        }
        function i(e2) {
          return URL.createObjectURL(new Blob([e2], {
            type: "text/vtt"
          }));
        }
        function n(e2) {
          let t3 = RegExp("Dialogue:\\s\\d,(\\d+:\\d\\d:\\d\\d.\\d\\d),(\\d+:\\d\\d:\\d\\d.\\d\\d),([^,]*),([^,]*),(?:[^,]*,){4}([\\s\\S]*)$", "i");
          function r3(e3 = "") {
            return e3.split(/[:.]/).map((e4, t4, r4) => {
              if (t4 === r4.length - 1) {
                if (1 === e4.length) return `.${e4}00`;
                if (2 === e4.length) return `.${e4}0`;
              } else if (1 === e4.length) return (0 === t4 ? "0" : ":0") + e4;
              return 0 === t4 ? e4 : t4 === r4.length - 1 ? `.${e4}` : `:${e4}`;
            }).join("");
          }
          return "WEBVTT\n\n" + e2.split(/\r?\n/).map((e3) => {
            let a2 = e3.match(t3);
            return a2 ? {
              start: r3(a2[1].trim()),
              end: r3(a2[2].trim()),
              text: a2[5].replace(/{[\s\S]*?}/g, "").replace(/(\\N)/g, "\n").trim().split(/\r?\n/).map((e4) => e4.trim()).join("\n")
            } : null;
          }).filter((e3) => e3).map((e3, t4) => e3 ? t4 + 1 + `
${e3.start} --> ${e3.end}
${e3.text}` : "").filter((e3) => e3.trim()).join("\n\n");
        }
        a.defineInteropFlag(r2), a.export(r2, "srtToVtt", () => o), a.export(r2, "vttToBlob", () => i), a.export(r2, "assToVtt", () => n);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "6b7Ip": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2, t3) {
          let r3 = document.createElement("a");
          r3.style.display = "none", r3.href = e2, r3.download = t3, document.body.appendChild(r3), r3.click(), document.body.removeChild(r3);
        }
        a.defineInteropFlag(r2), a.export(r2, "getExt", () => function e2(t3) {
          return t3.includes("?") ? e2(t3.split("?")[0]) : t3.includes("#") ? e2(t3.split("#")[0]) : t3.trim().toLowerCase().split(".").pop();
        }), a.export(r2, "download", () => o);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "5NSdr": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "def", () => o), a.export(r2, "has", () => n), a.export(r2, "get", () => s), a.export(r2, "mergeDeep", () => function e2(...t3) {
          let r3 = (e3) => e3 && "object" == typeof e3 && !Array.isArray(e3);
          return t3.reduce((t4, a2) => (Object.keys(a2).forEach((o2) => {
            let i2 = t4[o2], n2 = a2[o2];
            Array.isArray(i2) && Array.isArray(n2) ? t4[o2] = i2.concat(...n2) : r3(i2) && r3(n2) ? t4[o2] = e2(i2, n2) : t4[o2] = n2;
          }), t4), {});
        });
        let o = Object.defineProperty, {
          hasOwnProperty: i
        } = Object.prototype;
        function n(e2, t3) {
          return i.call(e2, t3);
        }
        function s(e2, t3) {
          return Object.getOwnPropertyDescriptor(e2, t3);
        }
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      epmNy: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2 = 0) {
          return new Promise((t3) => setTimeout(t3, e2));
        }
        function i(e2, t3) {
          let r3;
          return function(...a2) {
            clearTimeout(r3), r3 = setTimeout(() => (r3 = null, e2.apply(this, a2)), t3);
          };
        }
        function n(e2, t3) {
          let r3 = false;
          return function(...a2) {
            r3 || (e2.apply(this, a2), r3 = true, setTimeout(function() {
              r3 = false;
            }, t3));
          };
        }
        a.defineInteropFlag(r2), a.export(r2, "sleep", () => o), a.export(r2, "debounce", () => i), a.export(r2, "throttle", () => n);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      gapRl: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2, t3, r3) {
          return Math.max(Math.min(e2, Math.max(t3, r3)), Math.min(t3, r3));
        }
        function i(e2) {
          return e2.charAt(0).toUpperCase() + e2.slice(1);
        }
        function n(e2) {
          if (!e2) return "00:00";
          let t3 = Math.floor(e2 / 3600), r3 = Math.floor((e2 - 3600 * t3) / 60), a2 = Math.floor(e2 - 3600 * t3 - 60 * r3);
          return (t3 > 0 ? [t3, r3, a2] : [r3, a2]).map((e3) => e3 < 10 ? `0${e3}` : String(e3)).join(":");
        }
        function s(e2) {
          return e2.replace(/[&<>'"]/g, (e3) => ({
            "&": "&amp;",
            "<": "&lt;",
            ">": "&gt;",
            "'": "&#39;",
            '"': "&quot;"
          })[e3] || e3);
        }
        function l(e2) {
          let t3 = {
            "&amp;": "&",
            "&lt;": "<",
            "&gt;": ">",
            "&#39;": "'",
            "&quot;": '"'
          }, r3 = RegExp(`(${Object.keys(t3).join("|")})`, "g");
          return e2.replace(r3, (e3) => t3[e3] || e3);
        }
        a.defineInteropFlag(r2), a.export(r2, "clamp", () => o), a.export(r2, "capitalize", () => i), a.export(r2, "secondToTime", () => n), a.export(r2, "escape", () => s), a.export(r2, "unescape", () => l);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      AKEiO: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "ComponentOption", () => d2);
        var o = e("../utils");
        let i = "array", n = "boolean", s = "string", l = "number", c = "object", p = "function";
        function u(e2, t3, r3) {
          return (0, o.errorHandle)(t3 === s || t3 === l || e2 instanceof Element, `${r3.join(".")} require '${s}' or 'Element' type`);
        }
        let d2 = {
          html: u,
          disable: `?${n}`,
          name: `?${s}`,
          index: `?${l}`,
          style: `?${c}`,
          click: `?${p}`,
          mounted: `?${p}`,
          tooltip: `?${s}|${l}`,
          width: `?${l}`,
          selector: `?${i}`,
          onSelect: `?${p}`,
          switch: `?${n}`,
          onSwitch: `?${p}`,
          range: `?${i}`,
          onRange: `?${p}`,
          onChange: `?${p}`
        };
        r2.default = {
          id: s,
          container: u,
          url: s,
          poster: s,
          type: s,
          theme: s,
          lang: s,
          volume: l,
          isLive: n,
          muted: n,
          autoplay: n,
          autoSize: n,
          autoMini: n,
          loop: n,
          flip: n,
          playbackRate: n,
          aspectRatio: n,
          screenshot: n,
          setting: n,
          hotkey: n,
          pip: n,
          mutex: n,
          backdrop: n,
          fullscreen: n,
          fullscreenWeb: n,
          subtitleOffset: n,
          miniProgressBar: n,
          useSSR: n,
          playsInline: n,
          lock: n,
          fastForward: n,
          autoPlayback: n,
          autoOrientation: n,
          airplay: n,
          proxy: `?${p}`,
          plugins: [p],
          layers: [d2],
          contextmenu: [d2],
          settings: [d2],
          controls: [__spreadProps(__spreadValues({}, d2), {
            position: (e2, t3, r3) => {
              let a2 = ["top", "left", "right"];
              return (0, o.errorHandle)(a2.includes(e2), `${r3.join(".")} only accept ${a2.toString()} as parameters`);
            }
          })],
          quality: [{
            default: `?${n}`,
            html: s,
            url: s
          }],
          highlight: [{
            time: l,
            text: s
          }],
          thumbnails: {
            url: s,
            number: l,
            column: l,
            width: l,
            height: l,
            scale: l
          },
          subtitle: {
            url: s,
            name: s,
            type: s,
            style: c,
            escape: n,
            encoding: s,
            onVttLoad: p
          },
          moreVideoAttr: c,
          i18n: c,
          icons: c,
          cssVar: c,
          customType: c
        };
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      lyjeQ: [function(e, t2, r2) {
        e("@parcel/transformer-js/src/esmodule-helpers.js").defineInteropFlag(r2), r2.default = {
          propertys: ["audioTracks", "autoplay", "buffered", "controller", "controls", "crossOrigin", "currentSrc", "currentTime", "defaultMuted", "defaultPlaybackRate", "duration", "ended", "error", "loop", "mediaGroup", "muted", "networkState", "paused", "playbackRate", "played", "preload", "readyState", "seekable", "seeking", "src", "startDate", "textTracks", "videoTracks", "volume"],
          methods: ["addTextTrack", "canPlayType", "load", "play", "pause"],
          events: ["abort", "canplay", "canplaythrough", "durationchange", "emptied", "ended", "error", "loadeddata", "loadedmetadata", "loadstart", "pause", "play", "playing", "progress", "ratechange", "seeked", "seeking", "stalled", "suspend", "timeupdate", "volumechange", "waiting"],
          prototypes: ["width", "height", "videoWidth", "videoHeight", "poster", "webkitDecodedFrameCount", "webkitDroppedFrameCount", "playsInline", "webkitSupportsFullscreen", "webkitDisplayingFullscreen", "onenterpictureinpicture", "onleavepictureinpicture", "disablePictureInPicture", "cancelVideoFrameCallback", "requestVideoFrameCallback", "getVideoPlaybackQuality", "requestPictureInPicture", "webkitEnterFullScreen", "webkitEnterFullscreen", "webkitExitFullScreen", "webkitExitFullscreen"]
        };
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      X13Zf: [function(e, t2, r2) {
        e("@parcel/transformer-js/src/esmodule-helpers.js").defineInteropFlag(r2);
        var a = e("./utils");
        class o {
          constructor(e2) {
            this.art = e2;
            let {
              option: t3,
              constructor: r3
            } = e2;
            t3.container instanceof Element ? this.$container = t3.container : (this.$container = (0, a.query)(t3.container), (0, a.errorHandle)(this.$container, `No container element found by ${t3.container}`)), (0, a.errorHandle)((0, a.supportsFlex)(), "The current browser does not support flex layout");
            let o2 = this.$container.tagName.toLowerCase();
            (0, a.errorHandle)("div" === o2, `Unsupported container element type, only support 'div' but got '${o2}'`), (0, a.errorHandle)(r3.instances.every((e3) => e3.template.$container !== this.$container), "Cannot mount multiple instances on the same dom element"), this.query = this.query.bind(this), this.$container.dataset.artId = e2.id, this.init();
          }
          static get html() {
            return `<div class="art-video-player art-subtitle-show art-layer-show art-control-show art-mask-show"><video class="art-video"><track default kind="metadata" src=""></track></video><div class="art-poster"></div><div class="art-subtitle"></div><div class="art-danmuku"></div><div class="art-layers"></div><div class="art-mask"><div class="art-state"></div></div><div class="art-bottom"><div class="art-progress"></div><div class="art-controls"><div class="art-controls-left"></div><div class="art-controls-center"></div><div class="art-controls-right"></div></div></div><div class="art-loading"></div><div class="art-notice"><div class="art-notice-inner"></div></div><div class="art-settings"></div><div class="art-info"><div class="art-info-panel"><div class="art-info-item"><div class="art-info-title">Player version:</div><div class="art-info-content">5.2.1</div></div><div class="art-info-item"><div class="art-info-title">Video url:</div><div class="art-info-content" data-video="src"></div></div><div class="art-info-item"><div class="art-info-title">Video volume:</div><div class="art-info-content" data-video="volume"></div></div><div class="art-info-item"><div class="art-info-title">Video time:</div><div class="art-info-content" data-video="currentTime"></div></div><div class="art-info-item"><div class="art-info-title">Video duration:</div><div class="art-info-content" data-video="duration"></div></div><div class="art-info-item"><div class="art-info-title">Video resolution:</div><div class="art-info-content"><span data-video="videoWidth"></span>x<span data-video="videoHeight"></span></div></div></div><div class="art-info-close">[x]</div></div><div class="art-contextmenus"></div></div>`;
          }
          query(e2) {
            return (0, a.query)(e2, this.$container);
          }
          init() {
            let {
              option: e2
            } = this.art;
            if (e2.useSSR || (this.$container.innerHTML = o.html), this.$player = this.query(".art-video-player"), this.$video = this.query(".art-video"), this.$track = this.query("track"), this.$poster = this.query(".art-poster"), this.$subtitle = this.query(".art-subtitle"), this.$danmuku = this.query(".art-danmuku"), this.$bottom = this.query(".art-bottom"), this.$progress = this.query(".art-progress"), this.$controls = this.query(".art-controls"), this.$controlsLeft = this.query(".art-controls-left"), this.$controlsCenter = this.query(".art-controls-center"), this.$controlsRight = this.query(".art-controls-right"), this.$layer = this.query(".art-layers"), this.$loading = this.query(".art-loading"), this.$notice = this.query(".art-notice"), this.$noticeInner = this.query(".art-notice-inner"), this.$mask = this.query(".art-mask"), this.$state = this.query(".art-state"), this.$setting = this.query(".art-settings"), this.$info = this.query(".art-info"), this.$infoPanel = this.query(".art-info-panel"), this.$infoClose = this.query(".art-info-close"), this.$contextmenu = this.query(".art-contextmenus"), e2.proxy) {
              let t3 = e2.proxy.call(this.art, this.art);
              (0, a.errorHandle)(t3 instanceof HTMLVideoElement || t3 instanceof HTMLCanvasElement, "Function 'option.proxy' needs to return 'HTMLVideoElement' or 'HTMLCanvasElement'"), (0, a.replaceElement)(t3, this.$video), t3.className = "art-video", this.$video = t3;
            }
            e2.backdrop && (0, a.addClass)(this.$player, "art-backdrop"), a.isMobile && (0, a.addClass)(this.$player, "art-mobile");
          }
          destroy(e2) {
            e2 ? this.$container.innerHTML = "" : (0, a.addClass)(this.$player, "art-destroy");
          }
        }
        r2.default = o;
      }, {
        "./utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "3jKkj": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("../utils"), i = e("./zh-cn"), n = a.interopDefault(i);
        r2.default = class {
          constructor(e2) {
            this.art = e2, this.languages = {
              "zh-cn": n.default
            }, this.language = {}, this.update(e2.option.i18n);
          }
          init() {
            let e2 = this.art.option.lang.toLowerCase();
            this.language = this.languages[e2] || {};
          }
          get(e2) {
            return this.language[e2] || e2;
          }
          update(e2) {
            this.languages = (0, o.mergeDeep)(this.languages, e2), this.init();
          }
        };
      }, {
        "../utils": "71aH7",
        "./zh-cn": "5Y91w",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "5Y91w": [function(e, t2, r2) {
        e("@parcel/transformer-js/src/esmodule-helpers.js").defineInteropFlag(r2);
        let a = {
          "Video Info": "\u7EDF\u8BA1\u4FE1\u606F",
          Close: "\u5173\u95ED",
          "Video Load Failed": "\u52A0\u8F7D\u5931\u8D25",
          Volume: "\u97F3\u91CF",
          Play: "\u64AD\u653E",
          Pause: "\u6682\u505C",
          Rate: "\u901F\u5EA6",
          Mute: "\u9759\u97F3",
          "Video Flip": "\u753B\u9762\u7FFB\u8F6C",
          Horizontal: "\u6C34\u5E73",
          Vertical: "\u5782\u76F4",
          Reconnect: "\u91CD\u65B0\u8FDE\u63A5",
          "Show Setting": "\u663E\u793A\u8BBE\u7F6E",
          "Hide Setting": "\u9690\u85CF\u8BBE\u7F6E",
          Screenshot: "\u622A\u56FE",
          "Play Speed": "\u64AD\u653E\u901F\u5EA6",
          "Aspect Ratio": "\u753B\u9762\u6BD4\u4F8B",
          Default: "\u9ED8\u8BA4",
          Normal: "\u6B63\u5E38",
          Open: "\u6253\u5F00",
          "Switch Video": "\u5207\u6362",
          "Switch Subtitle": "\u5207\u6362\u5B57\u5E55",
          Fullscreen: "\u5168\u5C4F",
          "Exit Fullscreen": "\u9000\u51FA\u5168\u5C4F",
          "Web Fullscreen": "\u7F51\u9875\u5168\u5C4F",
          "Exit Web Fullscreen": "\u9000\u51FA\u7F51\u9875\u5168\u5C4F",
          "Mini Player": "\u8FF7\u4F60\u64AD\u653E\u5668",
          "PIP Mode": "\u5F00\u542F\u753B\u4E2D\u753B",
          "Exit PIP Mode": "\u9000\u51FA\u753B\u4E2D\u753B",
          "PIP Not Supported": "\u4E0D\u652F\u6301\u753B\u4E2D\u753B",
          "Fullscreen Not Supported": "\u4E0D\u652F\u6301\u5168\u5C4F",
          "Subtitle Offset": "\u5B57\u5E55\u504F\u79FB",
          "Last Seen": "\u4E0A\u6B21\u770B\u5230",
          "Jump Play": "\u8DF3\u8F6C\u64AD\u653E",
          AirPlay: "\u9694\u7A7A\u64AD\u653E",
          "AirPlay Not Available": "\u9694\u7A7A\u64AD\u653E\u4E0D\u53EF\u7528"
        };
        r2.default = a, "undefined" != typeof window && (window["artplayer-i18n-zh-cn"] = a);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      a90nx: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("./urlMix"), i = a.interopDefault(o), n = e("./attrMix"), s = a.interopDefault(n), l = e("./playMix"), c = a.interopDefault(l), p = e("./pauseMix"), u = a.interopDefault(p), d2 = e("./toggleMix"), f = a.interopDefault(d2), h = e("./seekMix"), m = a.interopDefault(h), g = e("./volumeMix"), v = a.interopDefault(g), y = e("./currentTimeMix"), b = a.interopDefault(y), x = e("./durationMix"), w = a.interopDefault(x), j = e("./switchMix"), k = a.interopDefault(j), C = e("./playbackRateMix"), S = a.interopDefault(C), I = e("./aspectRatioMix"), T = a.interopDefault(I), $2 = e("./screenshotMix"), E = a.interopDefault($2), M = e("./fullscreenMix"), F = a.interopDefault(M), H = e("./fullscreenWebMix"), z = a.interopDefault(H), D = e("./pipMix"), A = a.interopDefault(D), R = e("./loadedMix"), O = a.interopDefault(R), Y = e("./playedMix"), L = a.interopDefault(Y), P = e("./playingMix"), V = a.interopDefault(P), q = e("./autoSizeMix"), _ = a.interopDefault(q), N = e("./rectMix"), B = a.interopDefault(N), W = e("./flipMix"), U = a.interopDefault(W), K = e("./miniMix"), Z = a.interopDefault(K), X = e("./posterMix"), G = a.interopDefault(X), Q = e("./autoHeightMix"), J = a.interopDefault(Q), ee = e("./cssVarMix"), et = a.interopDefault(ee), er = e("./themeMix"), ea = a.interopDefault(er), eo = e("./typeMix"), ei = a.interopDefault(eo), en = e("./stateMix"), es = a.interopDefault(en), el = e("./subtitleOffsetMix"), ec = a.interopDefault(el), ep = e("./airplayMix"), eu = a.interopDefault(ep), ed = e("./qualityMix"), ef = a.interopDefault(ed), eh = e("./thumbnailsMix"), em = a.interopDefault(eh), eg = e("./optionInit"), ev = a.interopDefault(eg), ey = e("./eventInit"), eb = a.interopDefault(ey);
        r2.default = class {
          constructor(e2) {
            (0, i.default)(e2), (0, s.default)(e2), (0, c.default)(e2), (0, u.default)(e2), (0, f.default)(e2), (0, m.default)(e2), (0, v.default)(e2), (0, b.default)(e2), (0, w.default)(e2), (0, k.default)(e2), (0, S.default)(e2), (0, T.default)(e2), (0, E.default)(e2), (0, F.default)(e2), (0, z.default)(e2), (0, A.default)(e2), (0, O.default)(e2), (0, L.default)(e2), (0, V.default)(e2), (0, _.default)(e2), (0, B.default)(e2), (0, U.default)(e2), (0, Z.default)(e2), (0, G.default)(e2), (0, J.default)(e2), (0, et.default)(e2), (0, ea.default)(e2), (0, ei.default)(e2), (0, es.default)(e2), (0, ec.default)(e2), (0, eu.default)(e2), (0, ef.default)(e2), (0, em.default)(e2), (0, eb.default)(e2), (0, ev.default)(e2);
          }
        };
      }, {
        "./urlMix": "kQoac",
        "./attrMix": "deCma",
        "./playMix": "fOJuP",
        "./pauseMix": "fzHAy",
        "./toggleMix": "cBHxQ",
        "./seekMix": "koAPr",
        "./volumeMix": "6eyuR",
        "./currentTimeMix": "faaWv",
        "./durationMix": "5y91K",
        "./switchMix": "iceD8",
        "./playbackRateMix": "keKwh",
        "./aspectRatioMix": "jihET",
        "./screenshotMix": "36kPY",
        "./fullscreenMix": "2GYOJ",
        "./fullscreenWebMix": "5aYAP",
        "./pipMix": "7EnIB",
        "./loadedMix": "3N9mP",
        "./playedMix": "et96R",
        "./playingMix": "9DzzM",
        "./autoSizeMix": "i1LDY",
        "./rectMix": "IqARI",
        "./flipMix": "7E7Vs",
        "./miniMix": "gpugx",
        "./posterMix": "1SuFS",
        "./autoHeightMix": "8x4te",
        "./cssVarMix": "1CaTA",
        "./themeMix": "2FqhO",
        "./typeMix": "1fQQs",
        "./stateMix": "iBOQW",
        "./subtitleOffsetMix": "6vlBV",
        "./airplayMix": "eftqT",
        "./qualityMix": "5SdyX",
        "./thumbnailsMix": "4HcqV",
        "./optionInit": "fCWZK",
        "./eventInit": "f8Lv3",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      kQoac: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            option: t3,
            template: {
              $video: r3
            }
          } = e2;
          (0, o.def)(e2, "url", {
            get: () => r3.src,
            set(a2) {
              return __async(this, null, function* () {
                if (a2) {
                  let i2 = e2.url, n = t3.type || (0, o.getExt)(a2), s = t3.customType[n];
                  n && s ? (yield (0, o.sleep)(), e2.loading.show = true, s.call(e2, r3, a2, e2)) : (URL.revokeObjectURL(i2), r3.src = a2), i2 !== e2.url && (e2.option.url = a2, e2.isReady && i2 && e2.once("video:canplay", () => {
                    e2.emit("restart", a2);
                  }));
                } else yield (0, o.sleep)(), e2.loading.show = true;
              });
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      deCma: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            template: {
              $video: t3
            }
          } = e2;
          (0, o.def)(e2, "attr", {
            value(e3, r3) {
              if (void 0 === r3) return t3[e3];
              t3[e3] = r3;
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      fOJuP: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            i18n: t3,
            notice: r3,
            option: a2,
            constructor: {
              instances: i2
            },
            template: {
              $video: n
            }
          } = e2;
          (0, o.def)(e2, "play", {
            value: function() {
              return __async(this, null, function* () {
                let o2 = yield n.play();
                if (r3.show = t3.get("Play"), e2.emit("play"), a2.mutex) for (let t4 = 0; t4 < i2.length; t4++) {
                  let r4 = i2[t4];
                  r4 !== e2 && r4.pause();
                }
                return o2;
              });
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      fzHAy: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            template: {
              $video: t3
            },
            i18n: r3,
            notice: a2
          } = e2;
          (0, o.def)(e2, "pause", {
            value() {
              let o2 = t3.pause();
              return a2.show = r3.get("Pause"), e2.emit("pause"), o2;
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      cBHxQ: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          (0, o.def)(e2, "toggle", {
            value: () => e2.playing ? e2.pause() : e2.play()
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      koAPr: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            notice: t3
          } = e2;
          (0, o.def)(e2, "seek", {
            set(r3) {
              e2.currentTime = r3, e2.emit("seek", e2.currentTime), e2.duration && (t3.show = `${(0, o.secondToTime)(e2.currentTime)} / ${(0, o.secondToTime)(e2.duration)}`);
            }
          }), (0, o.def)(e2, "forward", {
            set(t4) {
              e2.seek = e2.currentTime + t4;
            }
          }), (0, o.def)(e2, "backward", {
            set(t4) {
              e2.seek = e2.currentTime - t4;
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "6eyuR": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            template: {
              $video: t3
            },
            i18n: r3,
            notice: a2,
            storage: i2
          } = e2;
          (0, o.def)(e2, "volume", {
            get: () => t3.volume || 0,
            set: (e3) => {
              t3.volume = (0, o.clamp)(e3, 0, 1), a2.show = `${r3.get("Volume")}: ${parseInt(100 * t3.volume, 10)}`, 0 !== t3.volume && i2.set("volume", t3.volume);
            }
          }), (0, o.def)(e2, "muted", {
            get: () => t3.muted,
            set: (r4) => {
              t3.muted = r4, e2.emit("muted", r4);
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      faaWv: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            $video: t3
          } = e2.template;
          (0, o.def)(e2, "currentTime", {
            get: () => t3.currentTime || 0,
            set: (r3) => {
              Number.isNaN(r3 = parseFloat(r3)) || (t3.currentTime = (0, o.clamp)(r3, 0, e2.duration));
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "5y91K": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          (0, o.def)(e2, "duration", {
            get: () => {
              let {
                duration: t3
              } = e2.template.$video;
              return t3 === 1 / 0 ? 0 : t3 || 0;
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      iceD8: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          function t3(t4, r3) {
            return new Promise((a2, o2) => {
              if (t4 === e2.url) return;
              let {
                playing: i2,
                aspectRatio: n,
                playbackRate: s
              } = e2;
              e2.pause(), e2.url = t4, e2.notice.show = "", e2.once("video:error", o2), e2.once("video:loadedmetadata", () => {
                e2.currentTime = r3;
              }), e2.once("video:canplay", () => __async(null, null, function* () {
                e2.playbackRate = s, e2.aspectRatio = n, i2 && (yield e2.play()), e2.notice.show = "", a2();
              }));
            });
          }
          (0, o.def)(e2, "switchQuality", {
            value: (r3) => t3(r3, e2.currentTime)
          }), (0, o.def)(e2, "switchUrl", {
            value: (e3) => t3(e3, 0)
          }), (0, o.def)(e2, "switch", {
            set: e2.switchUrl
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      keKwh: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            template: {
              $video: t3
            },
            i18n: r3,
            notice: a2
          } = e2;
          (0, o.def)(e2, "playbackRate", {
            get: () => t3.playbackRate,
            set(o2) {
              o2 ? o2 !== t3.playbackRate && (t3.playbackRate = o2, a2.show = `${r3.get("Rate")}: ${1 === o2 ? r3.get("Normal") : `${o2}x`}`) : e2.playbackRate = 1;
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      jihET: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            i18n: t3,
            notice: r3,
            template: {
              $video: a2,
              $player: i2
            }
          } = e2;
          (0, o.def)(e2, "aspectRatio", {
            get: () => i2.dataset.aspectRatio || "default",
            set(n) {
              if (n || (n = "default"), "default" === n) (0, o.setStyle)(a2, "width", null), (0, o.setStyle)(a2, "height", null), (0, o.setStyle)(a2, "margin", null), delete i2.dataset.aspectRatio;
              else {
                let e3 = n.split(":").map(Number), {
                  clientWidth: t4,
                  clientHeight: r4
                } = i2, s = e3[0] / e3[1];
                t4 / r4 > s ? ((0, o.setStyle)(a2, "width", `${s * r4}px`), (0, o.setStyle)(a2, "height", "100%"), (0, o.setStyle)(a2, "margin", "0 auto")) : ((0, o.setStyle)(a2, "width", "100%"), (0, o.setStyle)(a2, "height", `${t4 / s}px`), (0, o.setStyle)(a2, "margin", "auto 0")), i2.dataset.aspectRatio = n;
              }
              r3.show = `${t3.get("Aspect Ratio")}: ${"default" === n ? t3.get("Default") : n}`, e2.emit("aspectRatio", n);
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "36kPY": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            notice: t3,
            template: {
              $video: r3
            }
          } = e2, a2 = (0, o.createElement)("canvas");
          (0, o.def)(e2, "getDataURL", {
            value: () => new Promise((e3, o2) => {
              try {
                a2.width = r3.videoWidth, a2.height = r3.videoHeight, a2.getContext("2d").drawImage(r3, 0, 0), e3(a2.toDataURL("image/png"));
              } catch (e4) {
                t3.show = e4, o2(e4);
              }
            })
          }), (0, o.def)(e2, "getBlobUrl", {
            value: () => new Promise((e3, o2) => {
              try {
                a2.width = r3.videoWidth, a2.height = r3.videoHeight, a2.getContext("2d").drawImage(r3, 0, 0), a2.toBlob((t4) => {
                  e3(URL.createObjectURL(t4));
                });
              } catch (e4) {
                t3.show = e4, o2(e4);
              }
            })
          }), (0, o.def)(e2, "screenshot", {
            value: (t4) => __async(null, null, function* () {
              let a3 = yield e2.getDataURL(), i2 = t4 || `artplayer_${(0, o.secondToTime)(r3.currentTime)}`;
              return (0, o.download)(a3, `${i2}.png`), e2.emit("screenshot", a3), a3;
            })
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "2GYOJ": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => s);
        var o = e("../libs/screenfull"), i = a.interopDefault(o), n = e("../utils");
        function s(e2) {
          let {
            i18n: t3,
            notice: r3,
            template: {
              $video: a2,
              $player: o2
            }
          } = e2, s2 = (e3) => {
            (0, i.default).on("change", () => {
              e3.emit("fullscreen", i.default.isFullscreen);
            }), (0, i.default).on("error", (t4) => {
              e3.emit("fullscreenError", t4);
            }), (0, n.def)(e3, "fullscreen", {
              get: () => i.default.isFullscreen,
              set(t4) {
                return __async(this, null, function* () {
                  t4 ? (e3.state = "fullscreen", yield (0, i.default).request(o2), (0, n.addClass)(o2, "art-fullscreen")) : (yield (0, i.default).exit(), (0, n.removeClass)(o2, "art-fullscreen")), e3.emit("resize");
                });
              }
            });
          }, l = (e3) => {
            e3.proxy(document, "webkitfullscreenchange", () => {
              e3.emit("fullscreen", e3.fullscreen), e3.emit("resize");
            }), (0, n.def)(e3, "fullscreen", {
              get: () => document.fullscreenElement === a2,
              set(t4) {
                t4 ? (e3.state = "fullscreen", a2.webkitEnterFullscreen()) : a2.webkitExitFullscreen();
              }
            });
          };
          e2.once("video:loadedmetadata", () => {
            i.default.isEnabled ? s2(e2) : a2.webkitSupportsFullscreen ? l(e2) : (0, n.def)(e2, "fullscreen", {
              get: () => false,
              set() {
                r3.show = t3.get("Fullscreen Not Supported");
              }
            }), (0, n.def)(e2, "fullscreen", (0, n.get)(e2, "fullscreen"));
          });
        }
      }, {
        "../libs/screenfull": "8v40z",
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "8v40z": [function(e, t2, r2) {
        e("@parcel/transformer-js/src/esmodule-helpers.js").defineInteropFlag(r2);
        let a = [["requestFullscreen", "exitFullscreen", "fullscreenElement", "fullscreenEnabled", "fullscreenchange", "fullscreenerror"], ["webkitRequestFullscreen", "webkitExitFullscreen", "webkitFullscreenElement", "webkitFullscreenEnabled", "webkitfullscreenchange", "webkitfullscreenerror"], ["webkitRequestFullScreen", "webkitCancelFullScreen", "webkitCurrentFullScreenElement", "webkitCancelFullScreen", "webkitfullscreenchange", "webkitfullscreenerror"], ["mozRequestFullScreen", "mozCancelFullScreen", "mozFullScreenElement", "mozFullScreenEnabled", "mozfullscreenchange", "mozfullscreenerror"], ["msRequestFullscreen", "msExitFullscreen", "msFullscreenElement", "msFullscreenEnabled", "MSFullscreenChange", "MSFullscreenError"]], o = (() => {
          if ("undefined" == typeof document) return false;
          let e2 = a[0], t3 = {};
          for (let r3 of a) if (r3[1] in document) {
            for (let [a2, o2] of r3.entries()) t3[e2[a2]] = o2;
            return t3;
          }
          return false;
        })(), i = {
          change: o.fullscreenchange,
          error: o.fullscreenerror
        }, n = {
          request: (e2 = document.documentElement, t3) => new Promise((r3, a2) => {
            let i2 = () => {
              n.off("change", i2), r3();
            };
            n.on("change", i2);
            let s = e2[o.requestFullscreen](t3);
            s instanceof Promise && s.then(i2).catch(a2);
          }),
          exit: () => new Promise((e2, t3) => {
            if (!n.isFullscreen) {
              e2();
              return;
            }
            let r3 = () => {
              n.off("change", r3), e2();
            };
            n.on("change", r3);
            let a2 = document[o.exitFullscreen]();
            a2 instanceof Promise && a2.then(r3).catch(t3);
          }),
          toggle: (e2, t3) => n.isFullscreen ? n.exit() : n.request(e2, t3),
          onchange(e2) {
            n.on("change", e2);
          },
          onerror(e2) {
            n.on("error", e2);
          },
          on(e2, t3) {
            let r3 = i[e2];
            r3 && document.addEventListener(r3, t3, false);
          },
          off(e2, t3) {
            let r3 = i[e2];
            r3 && document.removeEventListener(r3, t3, false);
          },
          raw: o
        };
        Object.defineProperties(n, {
          isFullscreen: {
            get: () => !!document[o.fullscreenElement]
          },
          element: {
            enumerable: true,
            get: () => document[o.fullscreenElement]
          },
          isEnabled: {
            enumerable: true,
            get: () => !!document[o.fullscreenEnabled]
          }
        }), o || (n = {
          isEnabled: false
        }), r2.default = n;
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "5aYAP": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            constructor: t3,
            template: {
              $container: r3,
              $player: a2
            }
          } = e2, i2 = "";
          (0, o.def)(e2, "fullscreenWeb", {
            get: () => (0, o.hasClass)(a2, "art-fullscreen-web"),
            set(n) {
              n ? (i2 = a2.style.cssText, t3.FULLSCREEN_WEB_IN_BODY && (0, o.append)(document.body, a2), e2.state = "fullscreenWeb", (0, o.setStyle)(a2, "width", "100%"), (0, o.setStyle)(a2, "height", "100%"), (0, o.addClass)(a2, "art-fullscreen-web"), e2.emit("fullscreenWeb", true)) : (t3.FULLSCREEN_WEB_IN_BODY && (0, o.append)(r3, a2), i2 && (a2.style.cssText = i2, i2 = ""), (0, o.removeClass)(a2, "art-fullscreen-web"), e2.emit("fullscreenWeb", false)), e2.emit("resize");
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "7EnIB": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            i18n: t3,
            notice: r3,
            template: {
              $video: a2
            }
          } = e2;
          document.pictureInPictureEnabled ? function(e3) {
            let {
              template: {
                $video: t4
              },
              proxy: r4,
              notice: a3
            } = e3;
            t4.disablePictureInPicture = false, (0, o.def)(e3, "pip", {
              get: () => document.pictureInPictureElement,
              set(r5) {
                r5 ? (e3.state = "pip", t4.requestPictureInPicture().catch((e4) => {
                  throw a3.show = e4, e4;
                })) : document.exitPictureInPicture().catch((e4) => {
                  throw a3.show = e4, e4;
                });
              }
            }), r4(t4, "enterpictureinpicture", () => {
              e3.emit("pip", true);
            }), r4(t4, "leavepictureinpicture", () => {
              e3.emit("pip", false);
            });
          }(e2) : a2.webkitSupportsPresentationMode ? function(e3) {
            let {
              $video: t4
            } = e3.template;
            t4.webkitSetPresentationMode("inline"), (0, o.def)(e3, "pip", {
              get: () => "picture-in-picture" === t4.webkitPresentationMode,
              set(r4) {
                r4 ? (e3.state = "pip", t4.webkitSetPresentationMode("picture-in-picture"), e3.emit("pip", true)) : (t4.webkitSetPresentationMode("inline"), e3.emit("pip", false));
              }
            });
          }(e2) : (0, o.def)(e2, "pip", {
            get: () => false,
            set() {
              r3.show = t3.get("PIP Not Supported");
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "3N9mP": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            $video: t3
          } = e2.template;
          (0, o.def)(e2, "loaded", {
            get: () => e2.loadedTime / t3.duration
          }), (0, o.def)(e2, "loadedTime", {
            get: () => t3.buffered.length ? t3.buffered.end(t3.buffered.length - 1) : 0
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      et96R: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          (0, o.def)(e2, "played", {
            get: () => e2.currentTime / e2.duration
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "9DzzM": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            $video: t3
          } = e2.template;
          (0, o.def)(e2, "playing", {
            get: () => "boolean" == typeof t3.playing ? t3.playing : !!(t3.currentTime > 0 && !t3.paused && !t3.ended && t3.readyState > 2)
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      i1LDY: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            $container: t3,
            $player: r3,
            $video: a2
          } = e2.template;
          (0, o.def)(e2, "autoSize", {
            value() {
              let {
                videoWidth: i2,
                videoHeight: n
              } = a2, {
                width: s,
                height: l
              } = (0, o.getRect)(t3), c = i2 / n;
              s / l > c ? ((0, o.setStyle)(r3, "width", `${l * c / s * 100}%`), (0, o.setStyle)(r3, "height", "100%")) : ((0, o.setStyle)(r3, "width", "100%"), (0, o.setStyle)(r3, "height", `${s / c / l * 100}%`)), e2.emit("autoSize", {
                width: e2.width,
                height: e2.height
              });
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      IqARI: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          (0, o.def)(e2, "rect", {
            get: () => (0, o.getRect)(e2.template.$player)
          });
          let t3 = ["bottom", "height", "left", "right", "top", "width"];
          for (let r3 = 0; r3 < t3.length; r3++) {
            let a2 = t3[r3];
            (0, o.def)(e2, a2, {
              get: () => e2.rect[a2]
            });
          }
          (0, o.def)(e2, "x", {
            get: () => e2.left + window.pageXOffset
          }), (0, o.def)(e2, "y", {
            get: () => e2.top + window.pageYOffset
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "7E7Vs": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            template: {
              $player: t3
            },
            i18n: r3,
            notice: a2
          } = e2;
          (0, o.def)(e2, "flip", {
            get: () => t3.dataset.flip || "normal",
            set(i2) {
              i2 || (i2 = "normal"), "normal" === i2 ? delete t3.dataset.flip : t3.dataset.flip = i2, a2.show = `${r3.get("Video Flip")}: ${r3.get((0, o.capitalize)(i2))}`, e2.emit("flip", i2);
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      gpugx: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            icons: t3,
            proxy: r3,
            storage: a2,
            template: {
              $player: i2,
              $video: n
            }
          } = e2, s = false, l = 0, c = 0;
          function p() {
            let {
              $mini: t4
            } = e2.template;
            t4 && ((0, o.removeClass)(i2, "art-mini"), (0, o.setStyle)(t4, "display", "none"), i2.prepend(n), e2.emit("mini", false));
          }
          function u(t4, r4) {
            e2.playing ? ((0, o.setStyle)(t4, "display", "none"), (0, o.setStyle)(r4, "display", "flex")) : ((0, o.setStyle)(t4, "display", "flex"), (0, o.setStyle)(r4, "display", "none"));
          }
          function d2() {
            let {
              $mini: t4
            } = e2.template, r4 = (0, o.getRect)(t4), i3 = window.innerHeight - r4.height - 50, n2 = window.innerWidth - r4.width - 50;
            a2.set("top", i3), a2.set("left", n2), (0, o.setStyle)(t4, "top", `${i3}px`), (0, o.setStyle)(t4, "left", `${n2}px`);
          }
          (0, o.def)(e2, "mini", {
            get: () => (0, o.hasClass)(i2, "art-mini"),
            set(f) {
              if (f) {
                e2.state = "mini", (0, o.addClass)(i2, "art-mini");
                let f2 = function() {
                  let {
                    $mini: i3
                  } = e2.template;
                  if (i3) return (0, o.append)(i3, n), (0, o.setStyle)(i3, "display", "flex");
                  {
                    let i4 = (0, o.createElement)("div");
                    (0, o.addClass)(i4, "art-mini-popup"), (0, o.append)(document.body, i4), e2.template.$mini = i4, (0, o.append)(i4, n);
                    let d3 = (0, o.append)(i4, '<div class="art-mini-close"></div>');
                    (0, o.append)(d3, t3.close), r3(d3, "click", p);
                    let f3 = (0, o.append)(i4, '<div class="art-mini-state"></div>'), h2 = (0, o.append)(f3, t3.play), m2 = (0, o.append)(f3, t3.pause);
                    return r3(h2, "click", () => e2.play()), r3(m2, "click", () => e2.pause()), u(h2, m2), e2.on("video:playing", () => u(h2, m2)), e2.on("video:pause", () => u(h2, m2)), e2.on("video:timeupdate", () => u(h2, m2)), r3(i4, "mousedown", (e3) => {
                      s = 0 === e3.button, l = e3.pageX, c = e3.pageY;
                    }), e2.on("document:mousemove", (e3) => {
                      if (s) {
                        (0, o.addClass)(i4, "art-mini-droging");
                        let t4 = e3.pageX - l, r4 = e3.pageY - c;
                        (0, o.setStyle)(i4, "transform", `translate(${t4}px, ${r4}px)`);
                      }
                    }), e2.on("document:mouseup", () => {
                      if (s) {
                        s = false, (0, o.removeClass)(i4, "art-mini-droging");
                        let e3 = (0, o.getRect)(i4);
                        a2.set("left", e3.left), a2.set("top", e3.top), (0, o.setStyle)(i4, "left", `${e3.left}px`), (0, o.setStyle)(i4, "top", `${e3.top}px`), (0, o.setStyle)(i4, "transform", null);
                      }
                    }), i4;
                  }
                }(), h = a2.get("top"), m = a2.get("left");
                h && m ? ((0, o.setStyle)(f2, "top", `${h}px`), (0, o.setStyle)(f2, "left", `${m}px`), (0, o.isInViewport)(f2) || d2()) : d2(), e2.emit("mini", true);
              } else p();
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "1SuFS": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            template: {
              $poster: t3
            }
          } = e2;
          (0, o.def)(e2, "poster", {
            get: () => {
              try {
                return t3.style.backgroundImage.match(/"(.*)"/)[1];
              } catch (e3) {
                return "";
              }
            },
            set(e3) {
              (0, o.setStyle)(t3, "backgroundImage", `url(${e3})`);
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "8x4te": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            template: {
              $container: t3,
              $video: r3
            }
          } = e2;
          (0, o.def)(e2, "autoHeight", {
            value() {
              let {
                clientWidth: a2
              } = t3, {
                videoHeight: i2,
                videoWidth: n
              } = r3, s = a2 / n * i2;
              (0, o.setStyle)(t3, "height", s + "px"), e2.emit("autoHeight", s);
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "1CaTA": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            $player: t3
          } = e2.template;
          (0, o.def)(e2, "cssVar", {
            value: (e3, r3) => r3 ? t3.style.setProperty(e3, r3) : getComputedStyle(t3).getPropertyValue(e3)
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "2FqhO": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          (0, o.def)(e2, "theme", {
            get: () => e2.cssVar("--art-theme"),
            set(t3) {
              e2.cssVar("--art-theme", t3);
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "1fQQs": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          (0, o.def)(e2, "type", {
            get: () => e2.option.type,
            set(t3) {
              e2.option.type = t3;
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      iBOQW: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let t3 = ["mini", "pip", "fullscreen", "fullscreenWeb"];
          (0, o.def)(e2, "state", {
            get: () => t3.find((t4) => e2[t4]) || "standard",
            set(r3) {
              for (let a2 = 0; a2 < t3.length; a2++) {
                let o2 = t3[a2];
                o2 !== r3 && e2[o2] && (e2[o2] = false);
              }
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "6vlBV": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            notice: t3,
            i18n: r3,
            template: a2
          } = e2;
          (0, o.def)(e2, "subtitleOffset", {
            get: () => a2.$track?.offset || 0,
            set(i2) {
              let {
                cues: n
              } = e2.subtitle;
              if (!a2.$track || 0 === n.length) return;
              let s = (0, o.clamp)(i2, -10, 10);
              a2.$track.offset = s;
              for (let t4 = 0; t4 < n.length; t4++) {
                let r4 = n[t4];
                r4.originalStartTime = r4.originalStartTime ?? r4.startTime, r4.originalEndTime = r4.originalEndTime ?? r4.endTime, r4.startTime = (0, o.clamp)(r4.originalStartTime + s, 0, e2.duration), r4.endTime = (0, o.clamp)(r4.originalEndTime + s, 0, e2.duration);
              }
              e2.subtitle.update(), t3.show = `${r3.get("Subtitle Offset")}: ${i2}s`, e2.emit("subtitleOffset", i2);
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      eftqT: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            i18n: t3,
            notice: r3,
            proxy: a2,
            template: {
              $video: i2
            }
          } = e2, n = true;
          window.WebKitPlaybackTargetAvailabilityEvent && i2.webkitShowPlaybackTargetPicker ? a2(i2, "webkitplaybacktargetavailabilitychanged", (e3) => {
            switch (e3.availability) {
              case "available":
                n = true;
                break;
              case "not-available":
                n = false;
            }
          }) : n = false, (0, o.def)(e2, "airplay", {
            value() {
              n ? (i2.webkitShowPlaybackTargetPicker(), e2.emit("airplay")) : r3.show = t3.get("AirPlay Not Available");
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "5SdyX": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          (0, o.def)(e2, "quality", {
            set(t3) {
              let {
                controls: r3,
                notice: a2,
                i18n: o2
              } = e2, i2 = t3.find((e3) => e3.default) || t3[0];
              r3.update({
                name: "quality",
                position: "right",
                index: 10,
                style: {
                  marginRight: "10px"
                },
                html: i2?.html || "",
                selector: t3,
                onSelect: (t4) => __async(null, null, function* () {
                  return yield e2.switchQuality(t4.url), a2.show = `${o2.get("Switch Video")}: ${t4.html}`, t4.html;
                })
              });
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "4HcqV": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            events: t3,
            option: r3,
            template: {
              $progress: a2,
              $video: i2
            }
          } = e2, n = null, s = null, l = false, c = false, p = false;
          t3.hover(a2, () => {
            p = true;
          }, () => {
            p = false;
          }), e2.on("setBar", (t4, u, d2) => __async(null, null, function* () {
            let f = e2.controls?.thumbnails, {
              url: h,
              scale: m
            } = r3.thumbnails;
            if (!f || !h) return;
            let g = "played" === t4 && d2 && o.isMobile;
            if ("hover" === t4 || g) {
              if (l || (l = true, s = yield (0, o.loadImg)(h, m), c = true), !c || !p) return;
              let t5 = a2.clientWidth * u;
              (0, o.setStyle)(f, "display", "flex"), t5 > 0 && t5 < a2.clientWidth ? function(t6) {
                let n2 = e2.controls?.thumbnails;
                if (!n2) return;
                let {
                  number: l2,
                  column: c2,
                  width: p2,
                  height: u2,
                  scale: d3
                } = r3.thumbnails, f2 = p2 * d3 || s.naturalWidth / c2, h2 = u2 * d3 || f2 / (i2.videoWidth / i2.videoHeight), m2 = Math.floor(t6 / (a2.clientWidth / l2)), g2 = Math.ceil(m2 / c2) - 1;
                (0, o.setStyle)(n2, "backgroundImage", `url(${s.src})`), (0, o.setStyle)(n2, "height", `${h2}px`), (0, o.setStyle)(n2, "width", `${f2}px`), (0, o.setStyle)(n2, "backgroundPosition", `-${(m2 % c2 || c2 - 1) * f2}px -${g2 * h2}px`), t6 <= f2 / 2 ? (0, o.setStyle)(n2, "left", 0) : t6 > a2.clientWidth - f2 / 2 ? (0, o.setStyle)(n2, "left", `${a2.clientWidth - f2}px`) : (0, o.setStyle)(n2, "left", `${t6 - f2 / 2}px`);
              }(t5) : o.isMobile || (0, o.setStyle)(f, "display", "none"), g && (clearTimeout(n), n = setTimeout(() => {
                (0, o.setStyle)(f, "display", "none");
              }, 500));
            }
          })), (0, o.def)(e2, "thumbnails", {
            get: () => e2.option.thumbnails,
            set(t4) {
              t4.url && !e2.option.isLive && (e2.option.thumbnails = t4, clearTimeout(n), n = null, s = null, l = false, c = false);
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      fCWZK: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            option: t3,
            storage: r3,
            template: {
              $video: a2,
              $poster: i2
            }
          } = e2;
          for (let r4 in t3.moreVideoAttr) e2.attr(r4, t3.moreVideoAttr[r4]);
          t3.muted && (e2.muted = t3.muted), t3.volume && (a2.volume = (0, o.clamp)(t3.volume, 0, 1));
          let n = r3.get("volume");
          for (let r4 in "number" == typeof n && (a2.volume = (0, o.clamp)(n, 0, 1)), t3.poster && (0, o.setStyle)(i2, "backgroundImage", `url(${t3.poster})`), t3.autoplay && (a2.autoplay = t3.autoplay), t3.playsInline && (a2.playsInline = true, a2["webkit-playsinline"] = true), t3.theme && (t3.cssVar["--art-theme"] = t3.theme), t3.cssVar) e2.cssVar(r4, t3.cssVar[r4]);
          e2.url = t3.url;
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      f8Lv3: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => s);
        var o = e("../config"), i = a.interopDefault(o), n = e("../utils");
        function s(e2) {
          let {
            i18n: t3,
            notice: r3,
            option: a2,
            constructor: o2,
            proxy: s2,
            template: {
              $player: l,
              $video: c,
              $poster: p
            }
          } = e2, u = 0;
          for (let t4 = 0; t4 < i.default.events.length; t4++) s2(c, i.default.events[t4], (t5) => {
            e2.emit(`video:${t5.type}`, t5);
          });
          e2.on("video:canplay", () => {
            u = 0, e2.loading.show = false;
          }), e2.once("video:canplay", () => {
            e2.loading.show = false, e2.controls.show = true, e2.mask.show = true, e2.isReady = true, e2.emit("ready");
          }), e2.on("video:ended", () => {
            a2.loop ? (e2.seek = 0, e2.play(), e2.controls.show = false, e2.mask.show = false) : (e2.controls.show = true, e2.mask.show = true);
          }), e2.on("video:error", (i2) => __async(null, null, function* () {
            u < o2.RECONNECT_TIME_MAX ? (yield (0, n.sleep)(o2.RECONNECT_SLEEP_TIME), u += 1, e2.url = a2.url, r3.show = `${t3.get("Reconnect")}: ${u}`, e2.emit("error", i2, u)) : (e2.mask.show = true, e2.loading.show = false, e2.controls.show = true, (0, n.addClass)(l, "art-error"), yield (0, n.sleep)(o2.RECONNECT_SLEEP_TIME), r3.show = t3.get("Video Load Failed"));
          })), e2.on("video:loadedmetadata", () => {
            e2.emit("resize"), n.isMobile && (e2.loading.show = false, e2.controls.show = true, e2.mask.show = true);
          }), e2.on("video:loadstart", () => {
            e2.loading.show = true, e2.mask.show = false, e2.controls.show = true;
          }), e2.on("video:pause", () => {
            e2.controls.show = true, e2.mask.show = true;
          }), e2.on("video:play", () => {
            e2.mask.show = false, (0, n.setStyle)(p, "display", "none");
          }), e2.on("video:playing", () => {
            e2.mask.show = false;
          }), e2.on("video:progress", () => {
            e2.playing && (e2.loading.show = false);
          }), e2.on("video:seeked", () => {
            e2.loading.show = false, e2.mask.show = true;
          }), e2.on("video:seeking", () => {
            e2.loading.show = true, e2.mask.show = false;
          }), e2.on("video:timeupdate", () => {
            e2.mask.show = false;
          }), e2.on("video:waiting", () => {
            e2.loading.show = true, e2.mask.show = false;
          });
        }
      }, {
        "../config": "lyjeQ",
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "8Z0Uf": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("../utils/component"), i = a.interopDefault(o), n = e("./fullscreen"), s = a.interopDefault(n), l = e("./fullscreenWeb"), c = a.interopDefault(l), p = e("./pip"), u = a.interopDefault(p), d2 = e("./playAndPause"), f = a.interopDefault(d2), h = e("./progress"), m = a.interopDefault(h), g = e("./time"), v = a.interopDefault(g), y = e("./volume"), b = a.interopDefault(y), x = e("./setting"), w = a.interopDefault(x), j = e("./screenshot"), k = a.interopDefault(j), C = e("./airplay"), S = a.interopDefault(C), I = e("../utils");
        class T extends i.default {
          constructor(e2) {
            super(e2), this.isHover = false, this.name = "control", this.timer = Date.now();
            let {
              constructor: t3
            } = e2, {
              $player: r3,
              $bottom: a2
            } = this.art.template;
            e2.on("mousemove", () => {
              I.isMobile || (this.show = true);
            }), e2.on("click", () => {
              I.isMobile ? this.toggle() : this.show = true;
            }), e2.on("document:mousemove", (e3) => {
              this.isHover = (0, I.includeFromEvent)(e3, a2);
            }), e2.on("video:timeupdate", () => {
              !e2.setting.show && !this.isHover && !e2.isInput && e2.playing && this.show && Date.now() - this.timer >= t3.CONTROL_HIDE_TIME && (this.show = false);
            }), e2.on("control", (e3) => {
              e3 ? ((0, I.removeClass)(r3, "art-hide-cursor"), (0, I.addClass)(r3, "art-hover"), this.timer = Date.now()) : ((0, I.addClass)(r3, "art-hide-cursor"), (0, I.removeClass)(r3, "art-hover"));
            }), this.init();
          }
          init() {
            let {
              option: e2
            } = this.art;
            e2.isLive || this.add((0, m.default)({
              name: "progress",
              position: "top",
              index: 10
            })), this.add({
              name: "thumbnails",
              position: "top",
              index: 20
            }), this.add((0, f.default)({
              name: "playAndPause",
              position: "left",
              index: 10
            })), this.add((0, b.default)({
              name: "volume",
              position: "left",
              index: 20
            })), e2.isLive || this.add((0, v.default)({
              name: "time",
              position: "left",
              index: 30
            })), e2.quality.length && (0, I.sleep)().then(() => {
              this.art.quality = e2.quality;
            }), e2.screenshot && !I.isMobile && this.add((0, k.default)({
              name: "screenshot",
              position: "right",
              index: 20
            })), e2.setting && this.add((0, w.default)({
              name: "setting",
              position: "right",
              index: 30
            })), e2.pip && this.add((0, u.default)({
              name: "pip",
              position: "right",
              index: 40
            })), e2.airplay && window.WebKitPlaybackTargetAvailabilityEvent && this.add((0, S.default)({
              name: "airplay",
              position: "right",
              index: 50
            })), e2.fullscreenWeb && this.add((0, c.default)({
              name: "fullscreenWeb",
              position: "right",
              index: 60
            })), e2.fullscreen && this.add((0, s.default)({
              name: "fullscreen",
              position: "right",
              index: 70
            }));
            for (let t3 = 0; t3 < e2.controls.length; t3++) this.add(e2.controls[t3]);
          }
          add(e2) {
            let t3 = "function" == typeof e2 ? e2(this.art) : e2, {
              $progress: r3,
              $controlsLeft: a2,
              $controlsRight: o2
            } = this.art.template;
            switch (t3.position) {
              case "top":
                this.$parent = r3;
                break;
              case "left":
                this.$parent = a2;
                break;
              case "right":
                this.$parent = o2;
                break;
              default:
                (0, I.errorHandle)(false, "Control option.position must one of 'top', 'left', 'right'");
            }
            super.add(t3);
          }
          check(e2) {
            e2.$control_value.innerHTML = e2.html;
            for (let t3 = 0; t3 < e2.$control_option.length; t3++) {
              let r3 = e2.$control_option[t3];
              r3.default = r3 === e2, r3.default && (0, I.inverseClass)(r3.$control_item, "art-current");
            }
          }
          selector(e2, t3, r3) {
            let {
              proxy: a2
            } = this.art.events;
            (0, I.addClass)(t3, "art-control-selector");
            let o2 = (0, I.createElement)("div");
            (0, I.addClass)(o2, "art-selector-value"), (0, I.append)(o2, e2.html), t3.innerText = "", (0, I.append)(t3, o2);
            let i2 = (0, I.createElement)("div");
            (0, I.addClass)(i2, "art-selector-list"), (0, I.append)(t3, i2);
            for (let t4 = 0; t4 < e2.selector.length; t4++) {
              let r4 = e2.selector[t4], a3 = (0, I.createElement)("div");
              (0, I.addClass)(a3, "art-selector-item"), r4.default && (0, I.addClass)(a3, "art-current"), a3.dataset.index = t4, a3.dataset.value = r4.value, a3.innerHTML = r4.html, (0, I.append)(i2, a3), (0, I.def)(r4, "$control_option", {
                get: () => e2.selector
              }), (0, I.def)(r4, "$control_item", {
                get: () => a3
              }), (0, I.def)(r4, "$control_value", {
                get: () => o2
              });
            }
            let n2 = a2(i2, "click", (t4) => __async(this, null, function* () {
              let r4 = t4.composedPath() || [], a3 = e2.selector.find((e3) => e3.$control_item === r4.find((t5) => e3.$control_item === t5));
              this.check(a3), e2.onSelect && (o2.innerHTML = yield e2.onSelect.call(this.art, a3, a3.$control_item, t4));
            }));
            r3.push(n2);
          }
        }
        r2.default = T;
      }, {
        "../utils/component": "18nVI",
        "./fullscreen": "c61Lj",
        "./fullscreenWeb": "03jeB",
        "./pip": "u8l8e",
        "./playAndPause": "ebXtb",
        "./progress": "bgoVP",
        "./time": "ikc2j",
        "./volume": "b8NFx",
        "./setting": "03o9l",
        "./screenshot": "4KCF5",
        "./airplay": "4IS2d",
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "18nVI": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("./dom"), i = e("./error"), n = e("option-validator"), s = a.interopDefault(n), l = e("../scheme");
        r2.default = class {
          constructor(e2) {
            this.id = 0, this.art = e2, this.cache = /* @__PURE__ */ new Map(), this.add = this.add.bind(this), this.remove = this.remove.bind(this), this.update = this.update.bind(this);
          }
          get show() {
            return (0, o.hasClass)(this.art.template.$player, `art-${this.name}-show`);
          }
          set show(e2) {
            let {
              $player: t3
            } = this.art.template, r3 = `art-${this.name}-show`;
            e2 ? (0, o.addClass)(t3, r3) : (0, o.removeClass)(t3, r3), this.art.emit(this.name, e2);
          }
          toggle() {
            this.show = !this.show;
          }
          add(e2) {
            let t3 = "function" == typeof e2 ? e2(this.art) : e2;
            if (t3.html = t3.html || "", (0, s.default)(t3, l.ComponentOption), !this.$parent || !this.name || t3.disable) return;
            let r3 = t3.name || `${this.name}${this.id}`, a2 = this.cache.get(r3);
            (0, i.errorHandle)(!a2, `Can't add an existing [${r3}] to the [${this.name}]`), this.id += 1;
            let n2 = (0, o.createElement)("div");
            (0, o.addClass)(n2, `art-${this.name}`), (0, o.addClass)(n2, `art-${this.name}-${r3}`);
            let c = Array.from(this.$parent.children);
            n2.dataset.index = t3.index || this.id;
            let p = c.find((e3) => Number(e3.dataset.index) >= Number(n2.dataset.index));
            p ? p.insertAdjacentElement("beforebegin", n2) : (0, o.append)(this.$parent, n2), t3.html && (0, o.append)(n2, t3.html), t3.style && (0, o.setStyles)(n2, t3.style), t3.tooltip && (0, o.tooltip)(n2, t3.tooltip);
            let u = [];
            if (t3.click) {
              let e3 = this.art.events.proxy(n2, "click", (e4) => {
                e4.preventDefault(), t3.click.call(this.art, this, e4);
              });
              u.push(e3);
            }
            return t3.selector && ["left", "right"].includes(t3.position) && this.selector(t3, n2, u), this[r3] = n2, this.cache.set(r3, {
              $ref: n2,
              events: u,
              option: t3
            }), t3.mounted && t3.mounted.call(this.art, n2), n2;
          }
          remove(e2) {
            let t3 = this.cache.get(e2);
            (0, i.errorHandle)(t3, `Can't find [${e2}] from the [${this.name}]`), t3.option.beforeUnmount && t3.option.beforeUnmount.call(this.art, t3.$ref);
            for (let e3 = 0; e3 < t3.events.length; e3++) this.art.events.remove(t3.events[e3]);
            this.cache.delete(e2), delete this[e2], (0, o.remove)(t3.$ref);
          }
          update(e2) {
            let t3 = this.cache.get(e2.name);
            return t3 && (e2 = Object.assign(t3.option, e2), this.remove(e2.name)), this.add(e2);
          }
        };
      }, {
        "./dom": "bSNiV",
        "./error": "hwmZz",
        "option-validator": "bAWi2",
        "../scheme": "AKEiO",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      c61Lj: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => __spreadProps(__spreadValues({}, e2), {
            tooltip: t3.i18n.get("Fullscreen"),
            mounted: (e3) => {
              let {
                proxy: r3,
                icons: a2,
                i18n: i2
              } = t3, n = (0, o.append)(e3, a2.fullscreenOn), s = (0, o.append)(e3, a2.fullscreenOff);
              (0, o.setStyle)(s, "display", "none"), r3(e3, "click", () => {
                t3.fullscreen = !t3.fullscreen;
              }), t3.on("fullscreen", (t4) => {
                t4 ? ((0, o.tooltip)(e3, i2.get("Exit Fullscreen")), (0, o.setStyle)(n, "display", "none"), (0, o.setStyle)(s, "display", "inline-flex")) : ((0, o.tooltip)(e3, i2.get("Fullscreen")), (0, o.setStyle)(n, "display", "inline-flex"), (0, o.setStyle)(s, "display", "none"));
              });
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "03jeB": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => __spreadProps(__spreadValues({}, e2), {
            tooltip: t3.i18n.get("Web Fullscreen"),
            mounted: (e3) => {
              let {
                proxy: r3,
                icons: a2,
                i18n: i2
              } = t3, n = (0, o.append)(e3, a2.fullscreenWebOn), s = (0, o.append)(e3, a2.fullscreenWebOff);
              (0, o.setStyle)(s, "display", "none"), r3(e3, "click", () => {
                t3.fullscreenWeb = !t3.fullscreenWeb;
              }), t3.on("fullscreenWeb", (t4) => {
                t4 ? ((0, o.tooltip)(e3, i2.get("Exit Web Fullscreen")), (0, o.setStyle)(n, "display", "none"), (0, o.setStyle)(s, "display", "inline-flex")) : ((0, o.tooltip)(e3, i2.get("Web Fullscreen")), (0, o.setStyle)(n, "display", "inline-flex"), (0, o.setStyle)(s, "display", "none"));
              });
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      u8l8e: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => __spreadProps(__spreadValues({}, e2), {
            tooltip: t3.i18n.get("PIP Mode"),
            mounted: (e3) => {
              let {
                proxy: r3,
                icons: a2,
                i18n: i2
              } = t3;
              (0, o.append)(e3, a2.pip), r3(e3, "click", () => {
                t3.pip = !t3.pip;
              }), t3.on("pip", (t4) => {
                (0, o.tooltip)(e3, i2.get(t4 ? "Exit PIP Mode" : "PIP Mode"));
              });
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      ebXtb: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => __spreadProps(__spreadValues({}, e2), {
            mounted: (e3) => {
              let {
                proxy: r3,
                icons: a2,
                i18n: i2
              } = t3, n = (0, o.append)(e3, a2.play), s = (0, o.append)(e3, a2.pause);
              function l() {
                (0, o.setStyle)(n, "display", "flex"), (0, o.setStyle)(s, "display", "none");
              }
              function c() {
                (0, o.setStyle)(n, "display", "none"), (0, o.setStyle)(s, "display", "flex");
              }
              (0, o.tooltip)(n, i2.get("Play")), (0, o.tooltip)(s, i2.get("Pause")), r3(n, "click", () => {
                t3.play();
              }), r3(s, "click", () => {
                t3.pause();
              }), t3.playing ? c() : l(), t3.on("video:playing", () => {
                c();
              }), t3.on("video:pause", () => {
                l();
              });
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      bgoVP: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "getPosFromEvent", () => i), a.export(r2, "setCurrentTime", () => n), a.export(r2, "default", () => s);
        var o = e("../utils");
        function i(e2, t3) {
          let {
            $progress: r3
          } = e2.template, {
            left: a2
          } = (0, o.getRect)(r3), i2 = o.isMobile ? t3.touches[0].clientX : t3.clientX, n2 = (0, o.clamp)(i2 - a2, 0, r3.clientWidth), s2 = n2 / r3.clientWidth * e2.duration, l = (0, o.secondToTime)(s2), c = (0, o.clamp)(n2 / r3.clientWidth, 0, 1);
          return {
            second: s2,
            time: l,
            width: n2,
            percentage: c
          };
        }
        function n(e2, t3) {
          if (e2.isRotate) {
            let r3 = t3.touches[0].clientY / e2.height, a2 = r3 * e2.duration;
            e2.emit("setBar", "played", r3, t3), e2.seek = a2;
          } else {
            let {
              second: r3,
              percentage: a2
            } = i(e2, t3);
            e2.emit("setBar", "played", a2, t3), e2.seek = r3;
          }
        }
        function s(e2) {
          return (t3) => {
            let {
              icons: r3,
              option: a2,
              proxy: s2
            } = t3;
            return __spreadProps(__spreadValues({}, e2), {
              html: `<div class="art-control-progress-inner"><div class="art-progress-hover"></div><div class="art-progress-loaded"></div><div class="art-progress-played"></div><div class="art-progress-highlight"></div><div class="art-progress-indicator"></div><div class="art-progress-tip"></div></div>`,
              mounted: (e3) => {
                let l = null, c = false, p = (0, o.query)(".art-progress-hover", e3), u = (0, o.query)(".art-progress-loaded", e3), d2 = (0, o.query)(".art-progress-played", e3), f = (0, o.query)(".art-progress-highlight", e3), h = (0, o.query)(".art-progress-indicator", e3), m = (0, o.query)(".art-progress-tip", e3);
                function g(r4, a3) {
                  let {
                    width: n2,
                    time: s3
                  } = a3 || i(t3, r4);
                  m.innerText = s3;
                  let l2 = m.clientWidth;
                  n2 <= l2 / 2 ? (0, o.setStyle)(m, "left", 0) : n2 > e3.clientWidth - l2 / 2 ? (0, o.setStyle)(m, "left", `${e3.clientWidth - l2}px`) : (0, o.setStyle)(m, "left", `${n2 - l2 / 2}px`);
                }
                r3.indicator ? (0, o.append)(h, r3.indicator) : (0, o.setStyle)(h, "backgroundColor", "var(--art-theme)"), t3.on("setBar", function(r4, a3, i2) {
                  let n2 = "played" === r4 && i2 && o.isMobile;
                  "loaded" === r4 && (0, o.setStyle)(u, "width", `${100 * a3}%`), "hover" === r4 && (0, o.setStyle)(p, "width", `${100 * a3}%`), "played" === r4 && ((0, o.setStyle)(d2, "width", `${100 * a3}%`), (0, o.setStyle)(h, "left", `${100 * a3}%`)), n2 && ((0, o.setStyle)(m, "display", "flex"), g(i2, {
                    width: e3.clientWidth * a3,
                    time: (0, o.secondToTime)(a3 * t3.duration)
                  }), clearTimeout(l), l = setTimeout(() => {
                    (0, o.setStyle)(m, "display", "none");
                  }, 500));
                }), t3.on("video:loadedmetadata", function() {
                  f.innerText = "";
                  for (let e4 = 0; e4 < a2.highlight.length; e4++) {
                    let r4 = a2.highlight[e4], i2 = (0, o.clamp)(r4.time, 0, t3.duration) / t3.duration * 100, n2 = `<span data-text="${r4.text}" data-time="${r4.time}" style="left: ${i2}%"></span>`;
                    (0, o.append)(f, n2);
                  }
                }), t3.on("video:progress", () => {
                  t3.emit("setBar", "loaded", t3.loaded);
                }), t3.constructor.USE_RAF ? t3.on("raf", () => {
                  t3.emit("setBar", "played", t3.played);
                }) : t3.on("video:timeupdate", () => {
                  t3.emit("setBar", "played", t3.played);
                }), t3.on("video:ended", () => {
                  t3.emit("setBar", "played", 1);
                }), t3.emit("setBar", "loaded", t3.loaded || 0), o.isMobile || (s2(e3, "click", (e4) => {
                  e4.target !== h && n(t3, e4);
                }), s2(e3, "mousemove", (r4) => {
                  let {
                    percentage: a3
                  } = i(t3, r4);
                  t3.emit("setBar", "hover", a3, r4), (0, o.setStyle)(m, "display", "flex"), (0, o.includeFromEvent)(r4, f) ? function(r5) {
                    let {
                      width: a4
                    } = i(t3, r5), {
                      text: n2
                    } = r5.target.dataset;
                    m.innerText = n2;
                    let s3 = m.clientWidth;
                    a4 <= s3 / 2 ? (0, o.setStyle)(m, "left", 0) : a4 > e3.clientWidth - s3 / 2 ? (0, o.setStyle)(m, "left", `${e3.clientWidth - s3}px`) : (0, o.setStyle)(m, "left", `${a4 - s3 / 2}px`);
                  }(r4) : g(r4);
                }), s2(e3, "mouseleave", (e4) => {
                  (0, o.setStyle)(m, "display", "none"), t3.emit("setBar", "hover", 0, e4);
                }), s2(e3, "mousedown", (e4) => {
                  c = 0 === e4.button;
                }), t3.on("document:mousemove", (e4) => {
                  if (c) {
                    let {
                      second: r4,
                      percentage: a3
                    } = i(t3, e4);
                    t3.emit("setBar", "played", a3, e4), t3.seek = r4;
                  }
                }), t3.on("document:mouseup", () => {
                  c && (c = false);
                }));
              }
            });
          };
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      ikc2j: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => __spreadProps(__spreadValues({}, e2), {
            style: o.isMobile ? {
              fontSize: "12px",
              padding: "0 5px"
            } : {
              cursor: "auto",
              padding: "0 10px"
            },
            mounted: (e3) => {
              function r3() {
                let r4 = `${(0, o.secondToTime)(t3.currentTime)} / ${(0, o.secondToTime)(t3.duration)}`;
                r4 !== e3.innerText && (e3.innerText = r4);
              }
              r3();
              let a2 = ["video:loadedmetadata", "video:timeupdate", "video:progress"];
              for (let e4 = 0; e4 < a2.length; e4++) t3.on(a2[e4], r3);
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      b8NFx: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => __spreadProps(__spreadValues({}, e2), {
            mounted: (e3) => {
              let {
                proxy: r3,
                icons: a2
              } = t3, i2 = (0, o.append)(e3, a2.volume), n = (0, o.append)(e3, a2.volumeClose), s = (0, o.append)(e3, '<div class="art-volume-panel"></div>'), l = (0, o.append)(s, '<div class="art-volume-inner"></div>'), c = (0, o.append)(l, '<div class="art-volume-val"></div>'), p = (0, o.append)(l, '<div class="art-volume-slider"></div>'), u = (0, o.append)(p, '<div class="art-volume-handle"></div>'), d2 = (0, o.append)(u, '<div class="art-volume-loaded"></div>'), f = (0, o.append)(p, '<div class="art-volume-indicator"></div>');
              function h(e4) {
                let {
                  top: t4,
                  height: r4
                } = (0, o.getRect)(p);
                return 1 - (e4.clientY - t4) / r4;
              }
              function m() {
                if (t3.muted || 0 === t3.volume) (0, o.setStyle)(i2, "display", "none"), (0, o.setStyle)(n, "display", "flex"), (0, o.setStyle)(f, "top", "100%"), (0, o.setStyle)(d2, "top", "100%"), c.innerText = 0;
                else {
                  let e4 = 100 * t3.volume;
                  (0, o.setStyle)(i2, "display", "flex"), (0, o.setStyle)(n, "display", "none"), (0, o.setStyle)(f, "top", `${100 - e4}%`), (0, o.setStyle)(d2, "top", `${100 - e4}%`), c.innerText = Math.floor(e4);
                }
              }
              if (m(), t3.on("video:volumechange", m), r3(i2, "click", () => {
                t3.muted = true;
              }), r3(n, "click", () => {
                t3.muted = false;
              }), o.isMobile) (0, o.setStyle)(s, "display", "none");
              else {
                let e4 = false;
                r3(p, "mousedown", (r4) => {
                  e4 = 0 === r4.button, t3.volume = h(r4);
                }), t3.on("document:mousemove", (r4) => {
                  e4 && (t3.muted = false, t3.volume = h(r4));
                }), t3.on("document:mouseup", () => {
                  e4 && (e4 = false);
                });
              }
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "03o9l": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => __spreadProps(__spreadValues({}, e2), {
            tooltip: t3.i18n.get("Show Setting"),
            mounted: (e3) => {
              let {
                proxy: r3,
                icons: a2,
                i18n: i2
              } = t3;
              (0, o.append)(e3, a2.setting), r3(e3, "click", () => {
                t3.setting.toggle(), t3.setting.resize();
              }), t3.on("setting", (t4) => {
                (0, o.tooltip)(e3, i2.get(t4 ? "Hide Setting" : "Show Setting"));
              });
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "4KCF5": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => __spreadProps(__spreadValues({}, e2), {
            tooltip: t3.i18n.get("Screenshot"),
            mounted: (e3) => {
              let {
                proxy: r3,
                icons: a2
              } = t3;
              (0, o.append)(e3, a2.screenshot), r3(e3, "click", () => {
                t3.screenshot();
              });
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "4IS2d": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => __spreadProps(__spreadValues({}, e2), {
            tooltip: t3.i18n.get("AirPlay"),
            mounted: (e3) => {
              let {
                proxy: r3,
                icons: a2
              } = t3;
              (0, o.append)(e3, a2.airplay), r3(e3, "click", () => t3.airplay());
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "2KYsr": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("../utils"), i = e("../utils/component"), n = a.interopDefault(i), s = e("./playbackRate"), l = a.interopDefault(s), c = e("./aspectRatio"), p = a.interopDefault(c), u = e("./flip"), d2 = a.interopDefault(u), f = e("./info"), h = a.interopDefault(f), m = e("./version"), g = a.interopDefault(m), v = e("./close"), y = a.interopDefault(v);
        class b extends n.default {
          constructor(e2) {
            super(e2), this.name = "contextmenu", this.$parent = e2.template.$contextmenu, o.isMobile || this.init();
          }
          init() {
            let {
              option: e2,
              proxy: t3,
              template: {
                $player: r3,
                $contextmenu: a2
              }
            } = this.art;
            e2.playbackRate && this.add((0, l.default)({
              name: "playbackRate",
              index: 10
            })), e2.aspectRatio && this.add((0, p.default)({
              name: "aspectRatio",
              index: 20
            })), e2.flip && this.add((0, d2.default)({
              name: "flip",
              index: 30
            })), this.add((0, h.default)({
              name: "info",
              index: 40
            })), this.add((0, g.default)({
              name: "version",
              index: 50
            })), this.add((0, y.default)({
              name: "close",
              index: 60
            }));
            for (let t4 = 0; t4 < e2.contextmenu.length; t4++) this.add(e2.contextmenu[t4]);
            t3(r3, "contextmenu", (e3) => {
              if (!this.art.constructor.CONTEXTMENU) return;
              e3.preventDefault(), this.show = true;
              let t4 = e3.clientX, i2 = e3.clientY, {
                height: n2,
                width: s2,
                left: l2,
                top: c2
              } = (0, o.getRect)(r3), {
                height: p2,
                width: u2
              } = (0, o.getRect)(a2), d3 = t4 - l2, f2 = i2 - c2;
              t4 + u2 > l2 + s2 && (d3 = s2 - u2), i2 + p2 > c2 + n2 && (f2 = n2 - p2), (0, o.setStyles)(a2, {
                top: `${f2}px`,
                left: `${d3}px`
              });
            }), t3(r3, "click", (e3) => {
              (0, o.includeFromEvent)(e3, a2) || (this.show = false);
            }), this.art.on("blur", () => {
              this.show = false;
            });
          }
        }
        r2.default = b;
      }, {
        "../utils": "71aH7",
        "../utils/component": "18nVI",
        "./playbackRate": "69eLi",
        "./aspectRatio": "lUefg",
        "./flip": "kysiM",
        "./info": "gqIgJ",
        "./version": "kRU7C",
        "./close": "jQ8Pm",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "69eLi": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => {
            let {
              i18n: r3,
              constructor: {
                PLAYBACK_RATE: a2
              }
            } = t3, i2 = a2.map((e3) => `<span data-value="${e3}">${1 === e3 ? r3.get("Normal") : e3.toFixed(1)}</span>`).join("");
            return __spreadProps(__spreadValues({}, e2), {
              html: `${r3.get("Play Speed")}: ${i2}`,
              click: (e3, r4) => {
                let {
                  value: a3
                } = r4.target.dataset;
                a3 && (t3.playbackRate = Number(a3), e3.show = false);
              },
              mounted: (e3) => {
                let r4 = (0, o.query)('[data-value="1"]', e3);
                r4 && (0, o.inverseClass)(r4, "art-current"), t3.on("video:ratechange", () => {
                  let r5 = (0, o.queryAll)("span", e3).find((e4) => Number(e4.dataset.value) === t3.playbackRate);
                  r5 && (0, o.inverseClass)(r5, "art-current");
                });
              }
            });
          };
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      lUefg: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => {
            let {
              i18n: r3,
              constructor: {
                ASPECT_RATIO: a2
              }
            } = t3, i2 = a2.map((e3) => `<span data-value="${e3}">${"default" === e3 ? r3.get("Default") : e3}</span>`).join("");
            return __spreadProps(__spreadValues({}, e2), {
              html: `${r3.get("Aspect Ratio")}: ${i2}`,
              click: (e3, r4) => {
                let {
                  value: a3
                } = r4.target.dataset;
                a3 && (t3.aspectRatio = a3, e3.show = false);
              },
              mounted: (e3) => {
                let r4 = (0, o.query)('[data-value="default"]', e3);
                r4 && (0, o.inverseClass)(r4, "art-current"), t3.on("aspectRatio", (t4) => {
                  let r5 = (0, o.queryAll)("span", e3).find((e4) => e4.dataset.value === t4);
                  r5 && (0, o.inverseClass)(r5, "art-current");
                });
              }
            });
          };
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      kysiM: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return (t3) => {
            let {
              i18n: r3,
              constructor: {
                FLIP: a2
              }
            } = t3, i2 = a2.map((e3) => `<span data-value="${e3}">${r3.get((0, o.capitalize)(e3))}</span>`).join("");
            return __spreadProps(__spreadValues({}, e2), {
              html: `${r3.get("Video Flip")}: ${i2}`,
              click: (e3, r4) => {
                let {
                  value: a3
                } = r4.target.dataset;
                a3 && (t3.flip = a3.toLowerCase(), e3.show = false);
              },
              mounted: (e3) => {
                let r4 = (0, o.query)('[data-value="normal"]', e3);
                r4 && (0, o.inverseClass)(r4, "art-current"), t3.on("flip", (t4) => {
                  let r5 = (0, o.queryAll)("span", e3).find((e4) => e4.dataset.value === t4);
                  r5 && (0, o.inverseClass)(r5, "art-current");
                });
              }
            });
          };
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      gqIgJ: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2) {
          return (t3) => __spreadProps(__spreadValues({}, e2), {
            html: t3.i18n.get("Video Info"),
            click: (e3) => {
              t3.info.show = true, e3.show = false;
            }
          });
        }
        a.defineInteropFlag(r2), a.export(r2, "default", () => o);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      kRU7C: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2) {
          return __spreadProps(__spreadValues({}, e2), {
            html: '<a href="https://artplayer.org" target="_blank">ArtPlayer 5.2.1</a>'
          });
        }
        a.defineInteropFlag(r2), a.export(r2, "default", () => o);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      jQ8Pm: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2) {
          return (t3) => __spreadProps(__spreadValues({}, e2), {
            html: t3.i18n.get("Close"),
            click: (e3) => {
              e3.show = false;
            }
          });
        }
        a.defineInteropFlag(r2), a.export(r2, "default", () => o);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "02ajl": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("./utils"), i = e("./utils/component"), n = a.interopDefault(i);
        class s extends n.default {
          constructor(e2) {
            super(e2), this.name = "info", o.isMobile || this.init();
          }
          init() {
            let {
              proxy: e2,
              constructor: t3,
              template: {
                $infoPanel: r3,
                $infoClose: a2,
                $video: i2
              }
            } = this.art;
            e2(a2, "click", () => {
              this.show = false;
            });
            let n2 = null, s2 = (0, o.queryAll)("[data-video]", r3) || [];
            this.art.on("destroy", () => clearTimeout(n2)), function e3() {
              for (let e4 = 0; e4 < s2.length; e4++) {
                let t4 = s2[e4], r4 = i2[t4.dataset.video], a3 = "number" == typeof r4 ? r4.toFixed(2) : r4;
                t4.innerText !== a3 && (t4.innerText = a3);
              }
              n2 = setTimeout(e3, t3.INFO_LOOP_TIME);
            }();
          }
        }
        r2.default = s;
      }, {
        "./utils": "71aH7",
        "./utils/component": "18nVI",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      eSWto: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("./utils"), i = e("./utils/component"), n = a.interopDefault(i), s = e("option-validator"), l = a.interopDefault(s), c = e("./scheme"), p = a.interopDefault(c);
        class u extends n.default {
          constructor(e2) {
            super(e2), this.name = "subtitle", this.option = null, this.destroyEvent = () => null, this.init(e2.option.subtitle);
            let t3 = false;
            e2.on("video:timeupdate", () => {
              if (!this.url) return;
              let e3 = this.art.template.$video.webkitDisplayingFullscreen;
              "boolean" == typeof e3 && e3 !== t3 && (t3 = e3, this.createTrack(e3 ? "subtitles" : "metadata", this.url));
            });
          }
          get url() {
            return this.art.template.$track.src;
          }
          set url(e2) {
            this.switch(e2);
          }
          get textTrack() {
            return this.art.template.$video?.textTracks?.[0];
          }
          get activeCues() {
            return this.textTrack ? Array.from(this.textTrack.activeCues) : [];
          }
          get cues() {
            return this.textTrack ? Array.from(this.textTrack.cues) : [];
          }
          style(e2, t3) {
            let {
              $subtitle: r3
            } = this.art.template;
            return "object" == typeof e2 ? (0, o.setStyles)(r3, e2) : (0, o.setStyle)(r3, e2, t3);
          }
          update() {
            let {
              option: {
                subtitle: e2
              },
              template: {
                $subtitle: t3
              }
            } = this.art;
            t3.innerHTML = "", this.activeCues.length && (this.art.emit("subtitleBeforeUpdate", this.activeCues), t3.innerHTML = this.activeCues.map((t4, r3) => t4.text.split(/\r?\n/).filter((e3) => e3.trim()).map((t5) => `<div class="art-subtitle-line" data-group="${r3}">${e2.escape ? (0, o.escape)(t5) : t5}</div>`).join("")).join(""), this.art.emit("subtitleAfterUpdate", this.activeCues));
          }
          switch(_0) {
            return __async(this, arguments, function* (e2, t3 = {}) {
              let {
                i18n: r3,
                notice: a2,
                option: o2
              } = this.art, i2 = __spreadProps(__spreadValues(__spreadValues({}, o2.subtitle), t3), {
                url: e2
              }), n2 = yield this.init(i2);
              return t3.name && (a2.show = `${r3.get("Switch Subtitle")}: ${t3.name}`), n2;
            });
          }
          createTrack(e2, t3) {
            let {
              template: r3,
              proxy: a2,
              option: i2
            } = this.art, {
              $video: n2,
              $track: s2
            } = r3, l2 = (0, o.createElement)("track");
            l2.default = true, l2.kind = e2, l2.src = t3, l2.label = i2.subtitle.name || "Artplayer", l2.track.mode = "hidden", l2.onload = () => {
              this.art.emit("subtitleLoad", this.cues, this.option);
            }, this.art.events.remove(this.destroyEvent), s2.onload = null, (0, o.remove)(s2), (0, o.append)(n2, l2), r3.$track = l2, this.destroyEvent = a2(this.textTrack, "cuechange", () => this.update());
          }
          init(e2) {
            return __async(this, null, function* () {
              let {
                notice: t3,
                template: {
                  $subtitle: r3
                }
              } = this.art;
              return this.textTrack ? ((0, l.default)(e2, p.default.subtitle), e2.url) ? (this.option = e2, this.style(e2.style), fetch(e2.url).then((e3) => e3.arrayBuffer()).then((t4) => {
                let r4 = new TextDecoder(e2.encoding).decode(t4);
                switch (e2.type || (0, o.getExt)(e2.url)) {
                  case "srt": {
                    let t5 = (0, o.srtToVtt)(r4), a2 = e2.onVttLoad(t5);
                    return (0, o.vttToBlob)(a2);
                  }
                  case "ass": {
                    let t5 = (0, o.assToVtt)(r4), a2 = e2.onVttLoad(t5);
                    return (0, o.vttToBlob)(a2);
                  }
                  case "vtt": {
                    let t5 = e2.onVttLoad(r4);
                    return (0, o.vttToBlob)(t5);
                  }
                  default:
                    return e2.url;
                }
              }).then((e3) => (r3.innerHTML = "", this.url === e3 || (URL.revokeObjectURL(this.url), this.createTrack("metadata", e3)), e3)).catch((e3) => {
                throw r3.innerHTML = "", t3.show = e3, e3;
              })) : void 0 : null;
            });
          }
        }
        r2.default = u;
      }, {
        "./utils": "71aH7",
        "./utils/component": "18nVI",
        "option-validator": "bAWi2",
        "./scheme": "AKEiO",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      jo4S1: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("./clickInit"), i = a.interopDefault(o), n = e("./hoverInit"), s = a.interopDefault(n), l = e("./moveInit"), c = a.interopDefault(l), p = e("./resizeInit"), u = a.interopDefault(p), d2 = e("./gestureInit"), f = a.interopDefault(d2), h = e("./viewInit"), m = a.interopDefault(h), g = e("./documentInit"), v = a.interopDefault(g), y = e("./updateInit"), b = a.interopDefault(y), x = e("./restoreInit"), w = a.interopDefault(x);
        r2.default = class {
          constructor(e2) {
            this.destroyEvents = [], this.proxy = this.proxy.bind(this), this.hover = this.hover.bind(this), (0, i.default)(e2, this), (0, s.default)(e2, this), (0, c.default)(e2, this), (0, u.default)(e2, this), (0, f.default)(e2, this), (0, m.default)(e2, this), (0, v.default)(e2, this), (0, b.default)(e2, this), (0, w.default)(e2, this);
          }
          proxy(e2, t3, r3, a2 = {}) {
            if (Array.isArray(t3)) return t3.map((t4) => this.proxy(e2, t4, r3, a2));
            e2.addEventListener(t3, r3, a2);
            let o2 = () => e2.removeEventListener(t3, r3, a2);
            return this.destroyEvents.push(o2), o2;
          }
          hover(e2, t3, r3) {
            t3 && this.proxy(e2, "mouseenter", t3), r3 && this.proxy(e2, "mouseleave", r3);
          }
          remove(e2) {
            let t3 = this.destroyEvents.indexOf(e2);
            t3 > -1 && (e2(), this.destroyEvents.splice(t3, 1));
          }
          destroy() {
            for (let e2 = 0; e2 < this.destroyEvents.length; e2++) this.destroyEvents[e2]();
          }
        };
      }, {
        "./clickInit": "6UrCm",
        "./hoverInit": "4jWHi",
        "./moveInit": "eqaUm",
        "./resizeInit": "eDXPO",
        "./gestureInit": "95GtS",
        "./viewInit": "InUBx",
        "./documentInit": "hoLfM",
        "./updateInit": "cl8m3",
        "./restoreInit": "bK8As",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "6UrCm": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2, t3) {
          let {
            constructor: r3,
            template: {
              $player: a2,
              $video: i2
            }
          } = e2;
          t3.proxy(document, ["click", "contextmenu"], (t4) => {
            (0, o.includeFromEvent)(t4, a2) ? (e2.isInput = "INPUT" === t4.target.tagName, e2.isFocus = true, e2.emit("focus", t4)) : (e2.isInput = false, e2.isFocus = false, e2.emit("blur", t4));
          });
          let n = [];
          t3.proxy(i2, "click", (t4) => {
            let a3 = Date.now();
            n.push(a3);
            let {
              MOBILE_CLICK_PLAY: i3,
              DBCLICK_TIME: s,
              MOBILE_DBCLICK_PLAY: l,
              DBCLICK_FULLSCREEN: c
            } = r3, p = n.filter((e3) => a3 - e3 <= s);
            switch (p.length) {
              case 1:
                e2.emit("click", t4), o.isMobile ? !e2.isLock && i3 && e2.toggle() : e2.toggle(), n = p;
                break;
              case 2:
                e2.emit("dblclick", t4), o.isMobile ? !e2.isLock && l && e2.toggle() : c && (e2.fullscreen = !e2.fullscreen), n = [];
                break;
              default:
                n = [];
            }
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "4jWHi": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2, t3) {
          let {
            $player: r3
          } = e2.template;
          t3.hover(r3, (t4) => {
            (0, o.addClass)(r3, "art-hover"), e2.emit("hover", true, t4);
          }, (t4) => {
            (0, o.removeClass)(r3, "art-hover"), e2.emit("hover", false, t4);
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      eqaUm: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2, t3) {
          let {
            $player: r3
          } = e2.template;
          t3.proxy(r3, "mousemove", (t4) => {
            e2.emit("mousemove", t4);
          });
        }
        a.defineInteropFlag(r2), a.export(r2, "default", () => o);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      eDXPO: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2, t3) {
          let {
            option: r3,
            constructor: a2
          } = e2;
          e2.on("resize", () => {
            let {
              aspectRatio: t4,
              notice: a3
            } = e2;
            "standard" === e2.state && r3.autoSize && e2.autoSize(), e2.aspectRatio = t4, a3.show = "";
          });
          let i2 = (0, o.debounce)(() => e2.emit("resize"), a2.RESIZE_TIME);
          t3.proxy(window, ["orientationchange", "resize"], () => i2()), screen && screen.orientation && screen.orientation.onchange && t3.proxy(screen.orientation, "change", () => i2());
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "95GtS": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => n);
        var o = e("../utils"), i = e("../control/progress");
        function n(e2, t3) {
          if (o.isMobile && !e2.option.isLive) {
            let {
              $video: r3,
              $progress: a2
            } = e2.template, n2 = null, s = false, l = 0, c = 0, p = 0, u = (t4) => {
              if (1 === t4.touches.length && !e2.isLock) {
                n2 === a2 && (0, i.setCurrentTime)(e2, t4), s = true;
                let {
                  pageX: r4,
                  pageY: o2
                } = t4.touches[0];
                l = r4, c = o2, p = e2.currentTime;
              }
            }, d2 = (t4) => {
              if (1 === t4.touches.length && s && e2.duration) {
                let {
                  pageX: a3,
                  pageY: i2
                } = t4.touches[0], s2 = function(e3, t5, r4, a4) {
                  var o2 = t5 - a4, i3 = r4 - e3, n3 = 0;
                  if (2 > Math.abs(i3) && 2 > Math.abs(o2)) return n3;
                  var s3 = 180 * Math.atan2(o2, i3) / Math.PI;
                  return s3 >= -45 && s3 < 45 ? n3 = 4 : s3 >= 45 && s3 < 135 ? n3 = 1 : s3 >= -135 && s3 < -45 ? n3 = 2 : (s3 >= 135 && s3 <= 180 || s3 >= -180 && s3 < -135) && (n3 = 3), n3;
                }(l, c, a3, i2), u2 = [3, 4].includes(s2), d3 = [1, 2].includes(s2);
                if (u2 && !e2.isRotate || d3 && e2.isRotate) {
                  let s3 = (0, o.clamp)((a3 - l) / e2.width, -1, 1), u3 = (0, o.clamp)((i2 - c) / e2.height, -1, 1), d4 = e2.isRotate ? u3 : s3, f = n2 === r3 ? e2.constructor.TOUCH_MOVE_RATIO : 1, h = (0, o.clamp)(p + e2.duration * d4 * f, 0, e2.duration);
                  e2.seek = h, e2.emit("setBar", "played", (0, o.clamp)(h / e2.duration, 0, 1), t4), e2.notice.show = `${(0, o.secondToTime)(h)} / ${(0, o.secondToTime)(e2.duration)}`;
                }
              }
            };
            t3.proxy(a2, "touchstart", (e3) => {
              n2 = a2, u(e3);
            }), t3.proxy(r3, "touchstart", (e3) => {
              n2 = r3, u(e3);
            }), t3.proxy(r3, "touchmove", d2), t3.proxy(a2, "touchmove", d2), t3.proxy(document, "touchend", () => {
              s && (l = 0, c = 0, p = 0, s = false, n2 = null);
            });
          }
        }
      }, {
        "../utils": "71aH7",
        "../control/progress": "bgoVP",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      InUBx: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2, t3) {
          let {
            option: r3,
            constructor: a2,
            template: {
              $container: i2
            }
          } = e2, n = (0, o.throttle)(() => {
            e2.emit("view", (0, o.isInViewport)(i2, a2.SCROLL_GAP));
          }, a2.SCROLL_TIME);
          t3.proxy(window, "scroll", () => n()), e2.on("view", (t4) => {
            r3.autoMini && (e2.mini = !t4);
          });
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      hoLfM: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2, t3) {
          t3.proxy(document, "mousemove", (t4) => {
            e2.emit("document:mousemove", t4);
          }), t3.proxy(document, "mouseup", (t4) => {
            e2.emit("document:mouseup", t4);
          });
        }
        a.defineInteropFlag(r2), a.export(r2, "default", () => o);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      cl8m3: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2) {
          if (e2.constructor.USE_RAF) {
            let t3 = null;
            !function r3() {
              e2.playing && e2.emit("raf"), e2.isDestroy || (t3 = requestAnimationFrame(r3));
            }(), e2.on("destroy", () => {
              cancelAnimationFrame(t3);
            });
          }
        }
        a.defineInteropFlag(r2), a.export(r2, "default", () => o);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      bK8As: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2, t3) {
        }
        a.defineInteropFlag(r2), a.export(r2, "default", () => o);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "6NoFy": [function(e, t2, r2) {
        e("@parcel/transformer-js/src/esmodule-helpers.js").defineInteropFlag(r2);
        var a = e("./utils");
        r2.default = class {
          constructor(e2) {
            this.art = e2, this.keys = {}, e2.option.hotkey && !a.isMobile && this.init();
          }
          init() {
            let {
              proxy: e2,
              constructor: t3
            } = this.art;
            this.add("Escape", () => {
              this.art.fullscreenWeb && (this.art.fullscreenWeb = false);
            }), this.add("Space", () => {
              this.art.toggle();
            }), this.add("ArrowLeft", () => {
              this.art.backward = t3.SEEK_STEP;
            }), this.add("ArrowUp", () => {
              this.art.volume += t3.VOLUME_STEP;
            }), this.add("ArrowRight", () => {
              this.art.forward = t3.SEEK_STEP;
            }), this.add("ArrowDown", () => {
              this.art.volume -= t3.VOLUME_STEP;
            }), e2(document, "keydown", (e3) => {
              if (this.art.isFocus) {
                let t4 = document.activeElement.tagName.toUpperCase(), r3 = document.activeElement.getAttribute("contenteditable");
                if ("INPUT" !== t4 && "TEXTAREA" !== t4 && "" !== r3 && "true" !== r3 && !e3.altKey && !e3.ctrlKey && !e3.metaKey && !e3.shiftKey) {
                  let t5 = this.keys[e3.code];
                  if (t5) {
                    e3.preventDefault();
                    for (let r4 = 0; r4 < t5.length; r4++) t5[r4].call(this.art, e3);
                    this.art.emit("hotkey", e3);
                  }
                }
              }
              this.art.emit("keydown", e3);
            });
          }
          add(e2, t3) {
            return this.keys[e2] ? this.keys[e2].push(t3) : this.keys[e2] = [t3], this;
          }
          remove(e2, t3) {
            if (this.keys[e2]) {
              let r3 = this.keys[e2].indexOf(t3);
              -1 !== r3 && this.keys[e2].splice(r3, 1);
            }
            return this;
          }
        };
      }, {
        "./utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "6G6hZ": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("./utils/component"), i = a.interopDefault(o);
        class n extends i.default {
          constructor(e2) {
            super(e2);
            let {
              option: t3,
              template: {
                $layer: r3
              }
            } = e2;
            this.name = "layer", this.$parent = r3;
            for (let e3 = 0; e3 < t3.layers.length; e3++) this.add(t3.layers[e3]);
          }
        }
        r2.default = n;
      }, {
        "./utils/component": "18nVI",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "3dsEe": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("./utils"), i = e("./utils/component"), n = a.interopDefault(i);
        class s extends n.default {
          constructor(e2) {
            super(e2), this.name = "loading", (0, o.append)(e2.template.$loading, e2.icons.loading);
          }
        }
        r2.default = s;
      }, {
        "./utils": "71aH7",
        "./utils/component": "18nVI",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      dWGTw: [function(e, t2, r2) {
        e("@parcel/transformer-js/src/esmodule-helpers.js").defineInteropFlag(r2);
        var a = e("./utils");
        r2.default = class {
          constructor(e2) {
            this.art = e2, this.timer = null;
          }
          set show(e2) {
            let {
              constructor: t3,
              template: {
                $player: r3,
                $noticeInner: o
              }
            } = this.art;
            e2 ? (o.innerText = e2 instanceof Error ? e2.message.trim() : e2, (0, a.addClass)(r3, "art-notice-show"), clearTimeout(this.timer), this.timer = setTimeout(() => {
              o.innerText = "", (0, a.removeClass)(r3, "art-notice-show");
            }, t3.NOTICE_TIME)) : (0, a.removeClass)(r3, "art-notice-show");
          }
        };
      }, {
        "./utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "5POkG": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("./utils"), i = e("./utils/component"), n = a.interopDefault(i);
        class s extends n.default {
          constructor(e2) {
            super(e2), this.name = "mask";
            let {
              template: t3,
              icons: r3,
              events: a2
            } = e2, i2 = (0, o.append)(t3.$state, r3.state), n2 = (0, o.append)(t3.$state, r3.error);
            (0, o.setStyle)(n2, "display", "none"), e2.on("destroy", () => {
              (0, o.setStyle)(i2, "display", "none"), (0, o.setStyle)(n2, "display", null);
            }), a2.proxy(t3.$state, "click", () => e2.play());
          }
        }
        r2.default = s;
      }, {
        "./utils": "71aH7",
        "./utils/component": "18nVI",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "6OeNg": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("../utils"), i = e("bundle-text:./loading.svg"), n = a.interopDefault(i), s = e("bundle-text:./state.svg"), l = a.interopDefault(s), c = e("bundle-text:./check.svg"), p = a.interopDefault(c), u = e("bundle-text:./play.svg"), d2 = a.interopDefault(u), f = e("bundle-text:./pause.svg"), h = a.interopDefault(f), m = e("bundle-text:./volume.svg"), g = a.interopDefault(m), v = e("bundle-text:./volume-close.svg"), y = a.interopDefault(v), b = e("bundle-text:./screenshot.svg"), x = a.interopDefault(b), w = e("bundle-text:./setting.svg"), j = a.interopDefault(w), k = e("bundle-text:./arrow-left.svg"), C = a.interopDefault(k), S = e("bundle-text:./arrow-right.svg"), I = a.interopDefault(S), T = e("bundle-text:./playback-rate.svg"), $2 = a.interopDefault(T), E = e("bundle-text:./aspect-ratio.svg"), M = a.interopDefault(E), F = e("bundle-text:./config.svg"), H = a.interopDefault(F), z = e("bundle-text:./pip.svg"), D = a.interopDefault(z), A = e("bundle-text:./lock.svg"), R = a.interopDefault(A), O = e("bundle-text:./unlock.svg"), Y = a.interopDefault(O), L = e("bundle-text:./fullscreen-off.svg"), P = a.interopDefault(L), V = e("bundle-text:./fullscreen-on.svg"), q = a.interopDefault(V), _ = e("bundle-text:./fullscreen-web-off.svg"), N = a.interopDefault(_), B = e("bundle-text:./fullscreen-web-on.svg"), W = a.interopDefault(B), U = e("bundle-text:./switch-on.svg"), K = a.interopDefault(U), Z = e("bundle-text:./switch-off.svg"), X = a.interopDefault(Z), G = e("bundle-text:./flip.svg"), Q = a.interopDefault(G), J = e("bundle-text:./error.svg"), ee = a.interopDefault(J), et = e("bundle-text:./close.svg"), er = a.interopDefault(et), ea = e("bundle-text:./airplay.svg"), eo = a.interopDefault(ea);
        r2.default = class {
          constructor(e2) {
            let t3 = __spreadValues({
              loading: n.default,
              state: l.default,
              play: d2.default,
              pause: h.default,
              check: p.default,
              volume: g.default,
              volumeClose: y.default,
              screenshot: x.default,
              setting: j.default,
              pip: D.default,
              arrowLeft: C.default,
              arrowRight: I.default,
              playbackRate: $2.default,
              aspectRatio: M.default,
              config: H.default,
              lock: R.default,
              flip: Q.default,
              unlock: Y.default,
              fullscreenOff: P.default,
              fullscreenOn: q.default,
              fullscreenWebOff: N.default,
              fullscreenWebOn: W.default,
              switchOn: K.default,
              switchOff: X.default,
              error: ee.default,
              close: er.default,
              airplay: eo.default
            }, e2.option.icons);
            for (let e3 in t3) (0, o.def)(this, e3, {
              get: () => (0, o.getIcon)(e3, t3[e3])
            });
          }
        };
      }, {
        "../utils": "71aH7",
        "bundle-text:./loading.svg": "7tDub",
        "bundle-text:./state.svg": "1ElZc",
        "bundle-text:./check.svg": "lmgoP",
        "bundle-text:./play.svg": "lVWoQ",
        "bundle-text:./pause.svg": "5Mnax",
        "bundle-text:./volume.svg": "w3eIa",
        "bundle-text:./volume-close.svg": "rHjo1",
        "bundle-text:./screenshot.svg": "2KcqM",
        "bundle-text:./setting.svg": "8rQMV",
        "bundle-text:./arrow-left.svg": "kqGBE",
        "bundle-text:./arrow-right.svg": "aFjpC",
        "bundle-text:./playback-rate.svg": "lx7ZM",
        "bundle-text:./aspect-ratio.svg": "2sEjf",
        "bundle-text:./config.svg": "fQTgE",
        "bundle-text:./pip.svg": "2CaxO",
        "bundle-text:./lock.svg": "aCGnW",
        "bundle-text:./unlock.svg": "bTrAV",
        "bundle-text:./fullscreen-off.svg": "bA3p0",
        "bundle-text:./fullscreen-on.svg": "fTuY8",
        "bundle-text:./fullscreen-web-off.svg": "tvKf4",
        "bundle-text:./fullscreen-web-on.svg": "1F1oB",
        "bundle-text:./switch-on.svg": "7qNHs",
        "bundle-text:./switch-off.svg": "28aV8",
        "bundle-text:./flip.svg": "1uXI6",
        "bundle-text:./error.svg": "9f4dh",
        "bundle-text:./close.svg": "4nTtS",
        "bundle-text:./airplay.svg": "cDPXC",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "7tDub": [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" class="uil-default"><path fill="none" class="bk" d="M0 0h100v100H0z"/><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="translate(0 -30)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-1s" repeatCount="indefinite"/></rect><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="rotate(30 105.98 65)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-0.9166666666666666s" repeatCount="indefinite"/></rect><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="rotate(60 75.98 65)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-0.8333333333333334s" repeatCount="indefinite"/></rect><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="rotate(90 65 65)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-0.75s" repeatCount="indefinite"/></rect><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="rotate(120 58.66 65)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-0.6666666666666666s" repeatCount="indefinite"/></rect><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="rotate(150 54.02 65)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-0.5833333333333334s" repeatCount="indefinite"/></rect><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="rotate(180 50 65)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-0.5s" repeatCount="indefinite"/></rect><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="rotate(-150 45.98 65)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-0.4166666666666667s" repeatCount="indefinite"/></rect><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="rotate(-120 41.34 65)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-0.3333333333333333s" repeatCount="indefinite"/></rect><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="rotate(-90 35 65)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-0.25s" repeatCount="indefinite"/></rect><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="rotate(-60 24.02 65)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-0.16666666666666666s" repeatCount="indefinite"/></rect><rect x="47" y="40" width="6" height="20" rx="5" ry="5" fill="#fff" transform="rotate(-30 -5.98 65)"><animate attributeName="opacity" from="1" to="0" dur="1s" begin="-0.08333333333333333s" repeatCount="indefinite"/></rect></svg>';
      }, {}],
      "1ElZc": [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 24 24"><path fill="#fff" d="M9.5 9.325v5.35q0 .575.525.875t1.025-.05l4.15-2.65q.475-.3.475-.85t-.475-.85L11.05 8.5q-.5-.35-1.025-.05t-.525.875ZM12 22q-2.075 0-3.9-.788t-3.175-2.137q-1.35-1.35-2.137-3.175T2 12q0-2.075.788-3.9t2.137-3.175q1.35-1.35 3.175-2.137T12 2q2.075 0 3.9.788t3.175 2.137q1.35 1.35 2.138 3.175T22 12q0 2.075-.788 3.9t-2.137 3.175q-1.35 1.35-3.175 2.138T12 22Z"/></svg>';
      }, {}],
      lmgoP: [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" style="width:100%;height:100%"><path d="M9 16.2 4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" fill="#fff"/></svg>';
      }, {}],
      lVWoQ: [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" height="22" width="22" viewBox="0 0 22 22"><path d="M17.982 9.275 8.06 3.27A2.013 2.013 0 0 0 5 4.994v12.011a2.017 2.017 0 0 0 3.06 1.725l9.922-6.005a2.017 2.017 0 0 0 0-3.45z"/></svg>';
      }, {}],
      "5Mnax": [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" height="22" width="22" viewBox="0 0 22 22"><path d="M7 3a2 2 0 0 0-2 2v12a2 2 0 1 0 4 0V5a2 2 0 0 0-2-2zm8 0a2 2 0 0 0-2 2v12a2 2 0 1 0 4 0V5a2 2 0 0 0-2-2z"/></svg>';
      }, {}],
      w3eIa: [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" height="22" width="22" viewBox="0 0 22 22"><path d="M10.188 4.65 6 8H5a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h1l4.188 3.35a.5.5 0 0 0 .812-.39V5.04a.498.498 0 0 0-.812-.39zm4.258-.872a1 1 0 0 0-.862 1.804 6.002 6.002 0 0 1-.007 10.838 1 1 0 0 0 .86 1.806A8.001 8.001 0 0 0 19 11a8.001 8.001 0 0 0-4.554-7.222z"/><path d="M15 11a3.998 3.998 0 0 0-2-3.465v6.93A3.998 3.998 0 0 0 15 11z"/></svg>';
      }, {}],
      rHjo1: [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" height="22" width="22" viewBox="0 0 22 22"><path d="M15 11a3.998 3.998 0 0 0-2-3.465v2.636l1.865 1.865A4.02 4.02 0 0 0 15 11z"/><path d="M13.583 5.583A5.998 5.998 0 0 1 17 11a6 6 0 0 1-.585 2.587l1.477 1.477a8.001 8.001 0 0 0-3.446-11.286 1 1 0 0 0-.863 1.805zm5.195 13.195-2.121-2.121-1.414-1.414-1.415-1.415L13 13l-2-2-3.889-3.889-3.889-3.889a.999.999 0 1 0-1.414 1.414L5.172 8H5a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h1l4.188 3.35a.5.5 0 0 0 .812-.39v-3.131l2.587 2.587-.01.005a1 1 0 0 0 .86 1.806c.215-.102.424-.214.627-.333l2.3 2.3a1.001 1.001 0 0 0 1.414-1.416zM11 5.04a.5.5 0 0 0-.813-.39L8.682 5.854 11 8.172V5.04z"/></svg>';
      }, {}],
      "2KcqM": [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" height="22" width="22" viewBox="0 0 50 50"><path d="M19.402 6a5 5 0 0 0-4.902 4.012L14.098 12H9a5 5 0 0 0-5 5v21a5 5 0 0 0 5 5h32a5 5 0 0 0 5-5V17a5 5 0 0 0-5-5h-5.098l-.402-1.988A5 5 0 0 0 30.598 6ZM25 17c5.52 0 10 4.48 10 10s-4.48 10-10 10-10-4.48-10-10 4.48-10 10-10Zm0 2c-4.41 0-8 3.59-8 8s3.59 8 8 8 8-3.59 8-8-3.59-8-8-8Z"/></svg>';
      }, {}],
      "8rQMV": [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" height="22" width="22" viewBox="0 0 22 22"><circle cx="11" cy="11" r="2"/><path d="M19.164 8.861 17.6 8.6a6.978 6.978 0 0 0-1.186-2.099l.574-1.533a1 1 0 0 0-.436-1.217l-1.997-1.153a1.001 1.001 0 0 0-1.272.23l-1.008 1.225a7.04 7.04 0 0 0-2.55.001L8.716 2.829a1 1 0 0 0-1.272-.23L5.447 3.751a1 1 0 0 0-.436 1.217l.574 1.533A6.997 6.997 0 0 0 4.4 8.6l-1.564.261A.999.999 0 0 0 2 9.847v2.306c0 .489.353.906.836.986l1.613.269a7 7 0 0 0 1.228 2.075l-.558 1.487a1 1 0 0 0 .436 1.217l1.997 1.153c.423.244.961.147 1.272-.23l1.04-1.263a7.089 7.089 0 0 0 2.272 0l1.04 1.263a1 1 0 0 0 1.272.23l1.997-1.153a1 1 0 0 0 .436-1.217l-.557-1.487c.521-.61.94-1.31 1.228-2.075l1.613-.269a.999.999 0 0 0 .835-.986V9.847a.999.999 0 0 0-.836-.986zM11 15a4 4 0 1 1 0-8 4 4 0 0 1 0 8z"/></svg>';
      }, {}],
      kqGBE: [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" height="32" width="32" viewBox="0 0 32 32"><path d="m19.41 20.09-4.58-4.59 4.58-4.59L18 9.5l-6 6 6 6z" fill="#fff"/></svg>';
      }, {}],
      aFjpC: [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" height="32" width="32" viewBox="0 0 32 32"><path d="m12.59 20.34 4.58-4.59-4.58-4.59L14 9.75l6 6-6 6z" fill="#fff"/></svg>';
      }, {}],
      lx7ZM: [function(e, t2, r2) {
        t2.exports = '<svg height="24" viewBox="0 0 24 24" width="24"><path d="M10 8v8l6-4-6-4zM6.3 5l-.6-.8C7.2 3 9 2.2 11 2l.1 1c-1.8.2-3.4.9-4.8 2zM5 6.3l-.8-.6C3 7.2 2.2 9 2 11l1 .1c.2-1.8.9-3.4 2-4.8zm0 11.4c-1.1-1.4-1.8-3.1-2-4.8L2 13c.2 2 1 3.8 2.2 5.4l.8-.7zm6.1 3.3c-1.8-.2-3.4-.9-4.8-2l-.6.8C7.2 21 9 21.8 11 22l.1-1zM22 12c0-5.2-3.9-9.4-9-10l-.1 1c4.6.5 8.1 4.3 8.1 9s-3.5 8.5-8.1 9l.1 1c5.2-.5 9-4.8 9-10z" fill="#fff" style="--darkreader-inline-fill:#a8a6a4"/></svg>';
      }, {}],
      "2sEjf": [function(e, t2, r2) {
        t2.exports = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" style="width:100%;height:100%;transform:translate(0,0)"><defs><clipPath id="a"><path d="M0 0h88v88H0z"/></clipPath></defs><g style="display:block" clip-path="url('#a')"><path fill="#FFF" d="m12.438-12.702-2.82 2.82c-.79.79-.79 2.05 0 2.83l7.07 7.07-7.07 7.07c-.79.79-.79 2.05 0 2.83l2.82 2.83c.79.78 2.05.78 2.83 0l11.32-11.31c.78-.78.78-2.05 0-2.83l-11.32-11.31c-.78-.79-2.04-.79-2.83 0zm-24.88 0c-.74-.74-1.92-.78-2.7-.12l-.13.12-11.31 11.31a2 2 0 0 0-.12 2.7l.12.13 11.31 11.31a2 2 0 0 0 2.7.12l.13-.12 2.83-2.83c.74-.74.78-1.91.11-2.7l-.11-.13-7.07-7.07 7.07-7.07c.74-.74.78-1.91.11-2.7l-.11-.13-2.83-2.82zM28-28c4.42 0 8 3.58 8 8v40c0 4.42-3.58 8-8 8h-56c-4.42 0-8-3.58-8-8v-40c0-4.42 3.58-8 8-8h56z" style="--darkreader-inline-fill:#a8a6a4" transform="translate(44 44)"/></g></svg>`;
      }, {}],
      fQTgE: [function(e, t2, r2) {
        t2.exports = '<svg height="24" viewBox="0 0 24 24" width="24"><path d="M15 17h6v1h-6v-1zm-4 0H3v1h8v2h1v-5h-1v2zm3-9h1V3h-1v2H3v1h11v2zm4-3v1h3V5h-3zM6 14h1V9H6v2H3v1h3v2zm4-2h11v-1H10v1z" fill="#fff" style="--darkreader-inline-fill:#a8a6a4"/></svg>';
      }, {}],
      "2CaxO": [function(e, t2, r2) {
        t2.exports = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" height="32" width="32"><path d="M25 17h-8v6h8v-6Zm4 8V10.98C29 9.88 28.1 9 27 9H9c-1.1 0-2 .88-2 1.98V25c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2Zm-2 .02H9V10.97h18v14.05Z"/></svg>';
      }, {}],
      aCGnW: [function(e, t2, r2) {
        t2.exports = '<svg class="icon" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="20" height="20"><path d="M298.667 426.667v-85.334a213.333 213.333 0 1 1 426.666 0v85.334H768A85.333 85.333 0 0 1 853.333 512v256A85.333 85.333 0 0 1 768 853.333H256A85.333 85.333 0 0 1 170.667 768V512A85.333 85.333 0 0 1 256 426.667h42.667zM512 213.333a128 128 0 0 0-128 128v85.334h256v-85.334a128 128 0 0 0-128-128z" fill="#fff"/></svg>';
      }, {}],
      bTrAV: [function(e, t2, r2) {
        t2.exports = '<svg class="icon" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="20" height="20"><path d="m666.752 194.517-49.365 74.112A128 128 0 0 0 384 341.333l.043 85.334h384A85.333 85.333 0 0 1 853.376 512v256a85.333 85.333 0 0 1-85.333 85.333H256A85.333 85.333 0 0 1 170.667 768V512A85.333 85.333 0 0 1 256 426.667h42.667v-85.334a213.333 213.333 0 0 1 368.085-146.816z" fill="#fff"/></svg>';
      }, {}],
      bA3p0: [function(e, t2, r2) {
        t2.exports = '<svg class="icon" width="22" height="22" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="#fff" d="M768 298.667h170.667V384h-256V128H768v170.667zM341.333 384h-256v-85.333H256V128h85.333v256zM768 725.333V896h-85.333V640h256v85.333H768zM341.333 640v256H256V725.333H85.333V640h256z"/></svg>';
      }, {}],
      fTuY8: [function(e, t2, r2) {
        t2.exports = '<svg class="icon" width="22" height="22" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="#fff" d="M625.778 256H768v142.222h113.778v-256h-256V256zM256 398.222V256h142.222V142.222h-256v256H256zm512 227.556V768H625.778v113.778h256v-256H768zM398.222 768H256V625.778H142.222v256h256V768z"/></svg>';
      }, {}],
      tvKf4: [function(e, t2, r2) {
        t2.exports = '<svg class="icon" width="18" height="18" viewBox="0 0 1152 1024" xmlns="http://www.w3.org/2000/svg"><path fill="#fff" d="M1075.2 0H76.8A76.8 76.8 0 0 0 0 76.8v870.4a76.8 76.8 0 0 0 76.8 76.8h998.4a76.8 76.8 0 0 0 76.8-76.8V76.8A76.8 76.8 0 0 0 1075.2 0zM1024 128v768H128V128h896zM896 512a64 64 0 0 1 7.488 127.552L896 640H768v128a64 64 0 0 1-56.512 63.552L704 832a64 64 0 0 1-63.552-56.512L640 768V582.592c0-34.496 25.024-66.112 61.632-70.208l8-.384H896zm-640 0a64 64 0 0 1-7.488-127.552L256 384h128V256a64 64 0 0 1 56.512-63.552L448 192a64 64 0 0 1 63.552 56.512L512 256v185.408c0 34.432-25.024 66.112-61.632 70.144l-8 .448H256z"/></svg>';
      }, {}],
      "1F1oB": [function(e, t2, r2) {
        t2.exports = '<svg class="icon" width="18" height="18" viewBox="0 0 1152 1024" xmlns="http://www.w3.org/2000/svg"><path fill="#fff" d="M1075.2 0H76.8A76.8 76.8 0 0 0 0 76.8v870.4a76.8 76.8 0 0 0 76.8 76.8h998.4a76.8 76.8 0 0 0 76.8-76.8V76.8A76.8 76.8 0 0 0 1075.2 0zM1024 128v768H128V128h896zm-576 64a64 64 0 0 1 7.488 127.552L448 320H320v128a64 64 0 0 1-56.512 63.552L256 512a64 64 0 0 1-63.552-56.512L192 448V262.592c0-34.432 25.024-66.112 61.632-70.144l8-.448H448zm256 640a64 64 0 0 1-7.488-127.552L704 704h128V576a64 64 0 0 1 56.512-63.552L896 512a64 64 0 0 1 63.552 56.512L960 576v185.408c0 34.496-25.024 66.112-61.632 70.208l-8 .384H704z"/></svg>';
      }, {}],
      "7qNHs": [function(e, t2, r2) {
        t2.exports = '<svg class="icon" width="26" height="26" viewBox="0 0 1664 1024" xmlns="http://www.w3.org/2000/svg"><path fill="#648FFC" d="M1152 0H512a512 512 0 0 0 0 1024h640a512 512 0 0 0 0-1024zm0 960a448 448 0 1 1 448-448 448 448 0 0 1-448 448z"/></svg>';
      }, {}],
      "28aV8": [function(e, t2, r2) {
        t2.exports = '<svg class="icon" width="26" height="26" viewBox="0 0 1740 1024" xmlns="http://www.w3.org/2000/svg"><path fill="#fff" d="M511.898 1024h670.515c282.419-.41 511.18-229.478 511.18-511.898 0-282.419-228.761-511.488-511.18-511.897H511.898C229.478.615.717 229.683.717 512.102c0 282.42 228.761 511.488 511.18 511.898zm-.564-975.36A464.589 464.589 0 1 1 48.026 513.024 463.872 463.872 0 0 1 511.334 48.435v.205z"/></svg>';
      }, {}],
      "1uXI6": [function(e, t2, r2) {
        t2.exports = '<svg class="icon" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="24" height="24"><path d="M554.667 810.667V896h-85.334v-85.333h85.334zm-384-632.662a42.667 42.667 0 0 1 34.986 18.219l203.904 291.328a42.667 42.667 0 0 1 0 48.896L205.611 827.776A42.667 42.667 0 0 1 128 803.328V220.672a42.667 42.667 0 0 1 42.667-42.667zm682.666 0a42.667 42.667 0 0 1 42.368 37.718l.299 4.949v582.656a42.667 42.667 0 0 1-74.24 28.63l-3.413-4.182-203.904-291.328a42.667 42.667 0 0 1-3.03-43.861l3.03-5.035 203.946-291.328a42.667 42.667 0 0 1 34.944-18.219zM554.667 640v85.333h-85.334V640h85.334zm-358.4-320.896V716.8L335.957 512 196.31 319.104zm358.4 150.23v85.333h-85.334v-85.334h85.334zm0-170.667V384h-85.334v-85.333h85.334zm0-170.667v85.333h-85.334V128h85.334z" fill="#fff"/></svg>';
      }, {}],
      "9f4dh": [function(e, t2, r2) {
        t2.exports = '<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="50" height="50"><path d="M593.818 168.55 949.82 763.76c26.153 43.746 10.732 99.738-34.447 125.052-14.397 8.069-30.72 12.308-47.37 12.308H155.976c-52.224 0-94.536-40.96-94.536-91.505 0-16.097 4.383-31.928 12.718-45.875l356.004-595.19c26.173-43.724 84.009-58.654 129.208-33.341a93.082 93.082 0 0 1 34.448 33.341zM512 819.2a61.44 61.44 0 1 0 0-122.88 61.44 61.44 0 0 0 0 122.88zm0-512a72.315 72.315 0 0 0-71.762 81.306l25.723 205.721a46.408 46.408 0 0 0 92.078 0l25.723-205.742A72.315 72.315 0 0 0 512 307.2z"/></svg>';
      }, {}],
      "4nTtS": [function(e, t2, r2) {
        t2.exports = '<svg class="icon" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="22" height="22"><path d="m571.733 512 268.8-268.8c17.067-17.067 17.067-42.667 0-59.733-17.066-17.067-42.666-17.067-59.733 0L512 452.267l-268.8-268.8c-17.067-17.067-42.667-17.067-59.733 0-17.067 17.066-17.067 42.666 0 59.733l268.8 268.8-268.8 268.8c-17.067 17.067-17.067 42.667 0 59.733 8.533 8.534 19.2 12.8 29.866 12.8s21.334-4.266 29.867-12.8l268.8-268.8 268.8 268.8c8.533 8.534 19.2 12.8 29.867 12.8s21.333-4.266 29.866-12.8c17.067-17.066 17.067-42.666 0-59.733L571.733 512z"/></svg>';
      }, {}],
      cDPXC: [function(e, t2, r2) {
        t2.exports = '<svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg"><g fill="#fff"><path d="M16 1H2a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3v-2H3V3h12v8h-2v2h3a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1Z"/><path d="M4 17h10l-5-6z"/></g></svg>';
      }, {}],
      "3eYNH": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("./flip"), i = a.interopDefault(o), n = e("./aspectRatio"), s = a.interopDefault(n), l = e("./playbackRate"), c = a.interopDefault(l), p = e("./subtitleOffset"), u = a.interopDefault(p), d2 = e("../utils/component"), f = a.interopDefault(d2), h = e("../utils");
        class m extends f.default {
          constructor(e2) {
            super(e2);
            let {
              option: t3,
              controls: r3,
              template: {
                $setting: a2
              }
            } = e2;
            this.name = "setting", this.$parent = a2, this.id = 0, this.active = null, this.cache = /* @__PURE__ */ new Map(), this.option = [...this.builtin, ...t3.settings], t3.setting && (this.format(), this.render(), e2.on("blur", () => {
              this.show && (this.show = false, this.render());
            }), e2.on("focus", (e3) => {
              let t4 = (0, h.includeFromEvent)(e3, r3.setting), a3 = (0, h.includeFromEvent)(e3, this.$parent);
              !this.show || t4 || a3 || (this.show = false, this.render());
            }), e2.on("resize", () => this.resize()));
          }
          get builtin() {
            let e2 = [], {
              option: t3
            } = this.art;
            return t3.playbackRate && e2.push((0, c.default)(this.art)), t3.aspectRatio && e2.push((0, s.default)(this.art)), t3.flip && e2.push((0, i.default)(this.art)), t3.subtitleOffset && e2.push((0, u.default)(this.art)), e2;
          }
          traverse(e2, t3 = this.option) {
            for (let r3 = 0; r3 < t3.length; r3++) {
              let a2 = t3[r3];
              e2(a2), a2.selector?.length && this.traverse.call(this, e2, a2.selector);
            }
          }
          check(e2) {
            e2.$parent.tooltip = e2.html, this.traverse((t3) => {
              t3.default = t3 === e2, t3.default && t3.$item && (0, h.inverseClass)(t3.$item, "art-current");
            }, e2.$option), this.render(e2.$parents);
          }
          format(e2 = this.option, t3, r3, a2 = []) {
            for (let o2 = 0; o2 < e2.length; o2++) {
              let i2 = e2[o2];
              if (i2?.name ? ((0, h.errorHandle)(!a2.includes(i2.name), `The [${i2.name}] is already exist in [setting]`), a2.push(i2.name)) : i2.name = `setting-${this.id++}`, !i2.$formatted) {
                (0, h.def)(i2, "$parent", {
                  get: () => t3
                }), (0, h.def)(i2, "$parents", {
                  get: () => r3
                }), (0, h.def)(i2, "$option", {
                  get: () => e2
                });
                let a3 = [];
                (0, h.def)(i2, "$events", {
                  get: () => a3
                }), (0, h.def)(i2, "$formatted", {
                  get: () => true
                });
              }
              this.format(i2.selector || [], i2, e2, a2);
            }
            this.option = e2;
          }
          find(e2 = "") {
            let t3 = null;
            return this.traverse((r3) => {
              r3.name === e2 && (t3 = r3);
            }), t3;
          }
          resize() {
            let {
              controls: e2,
              constructor: {
                SETTING_WIDTH: t3,
                SETTING_ITEM_HEIGHT: r3
              },
              template: {
                $player: a2,
                $setting: o2
              }
            } = this.art;
            if (e2.setting && this.show) {
              let i2 = this.active[0]?.$parent?.width || t3, {
                left: n2,
                width: s2
              } = (0, h.getRect)(e2.setting), {
                left: l2,
                width: c2
              } = (0, h.getRect)(a2), p2 = n2 - l2 + s2 / 2 - i2 / 2, u2 = this.active === this.option ? this.active.length * r3 : (this.active.length + 1) * r3;
              (0, h.setStyle)(o2, "height", `${u2}px`), (0, h.setStyle)(o2, "width", `${i2}px`), p2 + i2 > c2 ? ((0, h.setStyle)(o2, "left", null), (0, h.setStyle)(o2, "right", null)) : ((0, h.setStyle)(o2, "left", `${p2}px`), (0, h.setStyle)(o2, "right", "auto"));
            }
          }
          inactivate(e2) {
            for (let t3 = 0; t3 < e2.$events.length; t3++) this.art.events.remove(e2.$events[t3]);
            e2.$events.length = 0;
          }
          remove(e2) {
            let t3 = this.find(e2);
            (0, h.errorHandle)(t3, `Can't find [${e2}] in the [setting]`);
            let r3 = t3.$option.indexOf(t3);
            t3.$option.splice(r3, 1), this.inactivate(t3), t3.$item && (0, h.remove)(t3.$item), this.render();
          }
          update(e2) {
            let t3 = this.find(e2.name);
            return t3 ? (this.inactivate(t3), Object.assign(t3, e2), this.format(), this.creatItem(t3, true), this.render(), t3) : this.add(e2);
          }
          add(e2, t3 = this.option) {
            return t3.push(e2), this.format(), this.creatItem(e2), this.render(), e2;
          }
          creatHeader(e2) {
            if (!this.cache.has(e2.$option)) return;
            let t3 = this.cache.get(e2.$option), {
              proxy: r3,
              icons: {
                arrowLeft: a2
              },
              constructor: {
                SETTING_ITEM_HEIGHT: o2
              }
            } = this.art, i2 = (0, h.createElement)("div");
            (0, h.setStyle)(i2, "height", `${o2}px`), (0, h.addClass)(i2, "art-setting-item"), (0, h.addClass)(i2, "art-setting-item-back");
            let n2 = (0, h.append)(i2, '<div class="art-setting-item-left"></div>'), s2 = (0, h.createElement)("div");
            (0, h.addClass)(s2, "art-setting-item-left-icon"), (0, h.append)(s2, a2), (0, h.append)(n2, s2), (0, h.append)(n2, e2.$parent.html);
            let l2 = r3(i2, "click", () => this.render(e2.$parents));
            e2.$parent.$events.push(l2), (0, h.append)(t3, i2);
          }
          creatItem(e2, t3 = false) {
            if (!this.cache.has(e2.$option)) return;
            let r3 = this.cache.get(e2.$option), a2 = e2.$item, o2 = "selector";
            (0, h.has)(e2, "switch") && (o2 = "switch"), (0, h.has)(e2, "range") && (o2 = "range");
            let {
              icons: i2,
              proxy: n2,
              constructor: s2
            } = this.art, l2 = (0, h.createElement)("div");
            (0, h.addClass)(l2, "art-setting-item"), (0, h.setStyle)(l2, "height", `${s2.SETTING_ITEM_HEIGHT}px`), l2.dataset.name = e2.name || "", l2.dataset.value = e2.value || "";
            let c2 = (0, h.append)(l2, '<div class="art-setting-item-left"></div>'), p2 = (0, h.append)(l2, '<div class="art-setting-item-right"></div>'), u2 = (0, h.createElement)("div");
            switch ((0, h.addClass)(u2, "art-setting-item-left-icon"), o2) {
              case "switch":
              case "range":
                (0, h.append)(u2, e2.icon || i2.config);
                break;
              case "selector":
                e2.selector?.length ? (0, h.append)(u2, e2.icon || i2.config) : (0, h.append)(u2, i2.check);
            }
            (0, h.append)(c2, u2), (0, h.def)(e2, "$icon", {
              configurable: true,
              get: () => u2
            }), (0, h.def)(e2, "icon", {
              configurable: true,
              get: () => u2.innerHTML,
              set(e3) {
                u2.innerHTML = "", (0, h.append)(u2, e3);
              }
            });
            let d3 = (0, h.createElement)("div");
            (0, h.addClass)(d3, "art-setting-item-left-text"), (0, h.append)(d3, e2.html || ""), (0, h.append)(c2, d3), (0, h.def)(e2, "$html", {
              configurable: true,
              get: () => d3
            }), (0, h.def)(e2, "html", {
              configurable: true,
              get: () => d3.innerHTML,
              set(e3) {
                d3.innerHTML = "", (0, h.append)(d3, e3);
              }
            });
            let f2 = (0, h.createElement)("div");
            switch ((0, h.addClass)(f2, "art-setting-item-right-tooltip"), (0, h.append)(f2, e2.tooltip || ""), (0, h.append)(p2, f2), (0, h.def)(e2, "$tooltip", {
              configurable: true,
              get: () => f2
            }), (0, h.def)(e2, "tooltip", {
              configurable: true,
              get: () => f2.innerHTML,
              set(e3) {
                f2.innerHTML = "", (0, h.append)(f2, e3);
              }
            }), o2) {
              case "switch": {
                let t4 = (0, h.createElement)("div");
                (0, h.addClass)(t4, "art-setting-item-right-icon");
                let r4 = (0, h.append)(t4, i2.switchOn), a3 = (0, h.append)(t4, i2.switchOff);
                (0, h.setStyle)(e2.switch ? a3 : r4, "display", "none"), (0, h.append)(p2, t4), (0, h.def)(e2, "$switch", {
                  configurable: true,
                  get: () => t4
                });
                let o3 = e2.switch;
                (0, h.def)(e2, "switch", {
                  configurable: true,
                  get: () => o3,
                  set(e3) {
                    o3 = e3, e3 ? ((0, h.setStyle)(a3, "display", "none"), (0, h.setStyle)(r4, "display", null)) : ((0, h.setStyle)(a3, "display", null), (0, h.setStyle)(r4, "display", "none"));
                  }
                });
                break;
              }
              case "range":
                {
                  let t4 = (0, h.createElement)("div");
                  (0, h.addClass)(t4, "art-setting-item-right-icon");
                  let r4 = (0, h.append)(t4, '<input type="range">');
                  r4.value = e2.range[0], r4.min = e2.range[1], r4.max = e2.range[2], r4.step = e2.range[3], (0, h.addClass)(r4, "art-setting-range"), (0, h.append)(p2, t4), (0, h.def)(e2, "$range", {
                    configurable: true,
                    get: () => r4
                  });
                  let a3 = [...e2.range];
                  (0, h.def)(e2, "range", {
                    configurable: true,
                    get: () => a3,
                    set(e3) {
                      a3 = [...e3], r4.value = e3[0], r4.min = e3[1], r4.max = e3[2], r4.step = e3[3];
                    }
                  });
                }
                break;
              case "selector":
                if (e2.selector?.length) {
                  let e3 = (0, h.createElement)("div");
                  (0, h.addClass)(e3, "art-setting-item-right-icon"), (0, h.append)(e3, i2.arrowRight), (0, h.append)(p2, e3);
                }
            }
            switch (o2) {
              case "switch":
                if (e2.onSwitch) {
                  let t4 = n2(l2, "click", (t5) => __async(this, null, function* () {
                    e2.switch = yield e2.onSwitch.call(this.art, e2, l2, t5);
                  }));
                  e2.$events.push(t4);
                }
                break;
              case "range":
                if (e2.$range) {
                  if (e2.onRange) {
                    let t4 = n2(e2.$range, "change", (t5) => __async(this, null, function* () {
                      e2.range[0] = e2.$range.valueAsNumber, e2.tooltip = yield e2.onRange.call(this.art, e2, l2, t5);
                    }));
                    e2.$events.push(t4);
                  }
                  if (e2.onChange) {
                    let t4 = n2(e2.$range, "input", (t5) => __async(this, null, function* () {
                      e2.range[0] = e2.$range.valueAsNumber, e2.tooltip = yield e2.onChange.call(this.art, e2, l2, t5);
                    }));
                    e2.$events.push(t4);
                  }
                }
                break;
              case "selector": {
                let t4 = n2(l2, "click", (t5) => __async(this, null, function* () {
                  e2.selector?.length ? this.render(e2.selector) : (this.check(e2), e2.$parent.onSelect && (e2.$parent.tooltip = yield e2.$parent.onSelect.call(this.art, e2, l2, t5)));
                }));
                e2.$events.push(t4), e2.default && (0, h.addClass)(l2, "art-current");
              }
            }
            (0, h.def)(e2, "$item", {
              configurable: true,
              get: () => l2
            }), t3 ? (0, h.replaceElement)(l2, a2) : (0, h.append)(r3, l2), e2.mounted && setTimeout(() => e2.mounted.call(this.art, e2.$item, e2), 0);
          }
          render(e2 = this.option) {
            if (this.active = e2, this.cache.has(e2)) {
              let t3 = this.cache.get(e2);
              (0, h.inverseClass)(t3, "art-current");
            } else {
              let t3 = (0, h.createElement)("div");
              this.cache.set(e2, t3), (0, h.addClass)(t3, "art-setting-panel"), (0, h.append)(this.$parent, t3), (0, h.inverseClass)(t3, "art-current"), e2[0]?.$parent && this.creatHeader(e2[0]);
              for (let t4 = 0; t4 < e2.length; t4++) this.creatItem(e2[t4]);
            }
            this.resize();
          }
        }
        r2.default = m;
      }, {
        "./flip": "kONUB",
        "./aspectRatio": "84NBV",
        "./playbackRate": "aetWt",
        "./subtitleOffset": "fIBkO",
        "../utils/component": "18nVI",
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      kONUB: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            i18n: t3,
            icons: r3,
            constructor: {
              SETTING_ITEM_WIDTH: a2,
              FLIP: i2
            }
          } = e2;
          function n(e3) {
            return t3.get((0, o.capitalize)(e3));
          }
          function s() {
            let t4 = e2.setting.find(`flip-${e2.flip}`);
            e2.setting.check(t4);
          }
          return {
            width: a2,
            name: "flip",
            html: t3.get("Video Flip"),
            tooltip: n(e2.flip),
            icon: r3.flip,
            selector: i2.map((t4) => ({
              value: t4,
              name: `flip-${t4}`,
              default: t4 === e2.flip,
              html: n(t4)
            })),
            onSelect: (t4) => (e2.flip = t4.value, t4.html),
            mounted: () => {
              s(), e2.on("flip", () => s());
            }
          };
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "84NBV": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2) {
          let {
            i18n: t3,
            icons: r3,
            constructor: {
              SETTING_ITEM_WIDTH: a2,
              ASPECT_RATIO: o2
            }
          } = e2;
          function i(e3) {
            return "default" === e3 ? t3.get("Default") : e3;
          }
          function n() {
            let t4 = e2.setting.find(`aspect-ratio-${e2.aspectRatio}`);
            e2.setting.check(t4);
          }
          return {
            width: a2,
            name: "aspect-ratio",
            html: t3.get("Aspect Ratio"),
            icon: r3.aspectRatio,
            tooltip: i(e2.aspectRatio),
            selector: o2.map((t4) => ({
              value: t4,
              name: `aspect-ratio-${t4}`,
              default: t4 === e2.aspectRatio,
              html: i(t4)
            })),
            onSelect: (t4) => (e2.aspectRatio = t4.value, t4.html),
            mounted: () => {
              n(), e2.on("aspectRatio", () => n());
            }
          };
        }
        a.defineInteropFlag(r2), a.export(r2, "default", () => o);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      aetWt: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2) {
          let {
            i18n: t3,
            icons: r3,
            constructor: {
              SETTING_ITEM_WIDTH: a2,
              PLAYBACK_RATE: o2
            }
          } = e2;
          function i(e3) {
            return 1 === e3 ? t3.get("Normal") : e3.toFixed(1);
          }
          function n() {
            let t4 = e2.setting.find(`playback-rate-${e2.playbackRate}`);
            e2.setting.check(t4);
          }
          return {
            width: a2,
            name: "playback-rate",
            html: t3.get("Play Speed"),
            tooltip: i(e2.playbackRate),
            icon: r3.playbackRate,
            selector: o2.map((t4) => ({
              value: t4,
              name: `playback-rate-${t4}`,
              default: t4 === e2.playbackRate,
              html: i(t4)
            })),
            onSelect: (t4) => (e2.playbackRate = t4.value, t4.html),
            mounted: () => {
              n(), e2.on("video:ratechange", () => n());
            }
          };
        }
        a.defineInteropFlag(r2), a.export(r2, "default", () => o);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      fIBkO: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        function o(e2) {
          let {
            i18n: t3,
            icons: r3,
            constructor: a2
          } = e2;
          return {
            width: a2.SETTING_ITEM_WIDTH,
            name: "subtitle-offset",
            html: t3.get("Subtitle Offset"),
            icon: r3.subtitle,
            tooltip: "0s",
            range: [0, -10, 10, 0.1],
            onChange: (t4) => (e2.subtitleOffset = t4.range[0], t4.range[0] + "s"),
            mounted: (t4, r4) => {
              e2.on("subtitleOffset", (e3) => {
                r4.$range.value = e3, r4.tooltip = e3 + "s";
              });
            }
          };
        }
        a.defineInteropFlag(r2), a.export(r2, "default", () => o);
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "2aaJe": [function(e, t2, r2) {
        e("@parcel/transformer-js/src/esmodule-helpers.js").defineInteropFlag(r2), r2.default = class {
          constructor() {
            this.name = "artplayer_settings", this.settings = {};
          }
          get(e2) {
            try {
              let t3 = JSON.parse(window.localStorage.getItem(this.name)) || {};
              return e2 ? t3[e2] : t3;
            } catch (t3) {
              return e2 ? this.settings[e2] : this.settings;
            }
          }
          set(e2, t3) {
            try {
              let r3 = Object.assign({}, this.get(), {
                [e2]: t3
              });
              window.localStorage.setItem(this.name, JSON.stringify(r3));
            } catch (r3) {
              this.settings[e2] = t3;
            }
          }
          del(e2) {
            try {
              let t3 = this.get();
              delete t3[e2], window.localStorage.setItem(this.name, JSON.stringify(t3));
            } catch (t3) {
              delete this.settings[e2];
            }
          }
          clear() {
            try {
              window.localStorage.removeItem(this.name);
            } catch (e2) {
              this.settings = {};
            }
          }
        };
      }, {
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "8MTUM": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2);
        var o = e("../utils"), i = e("./miniProgressBar"), n = a.interopDefault(i), s = e("./autoOrientation"), l = a.interopDefault(s), c = e("./autoPlayback"), p = a.interopDefault(c), u = e("./fastForward"), d2 = a.interopDefault(u), f = e("./lock"), h = a.interopDefault(f);
        r2.default = class {
          constructor(e2) {
            this.art = e2, this.id = 0;
            let {
              option: t3
            } = e2;
            t3.miniProgressBar && !t3.isLive && this.add(n.default), t3.lock && o.isMobile && this.add(h.default), t3.autoPlayback && !t3.isLive && this.add(p.default), t3.autoOrientation && o.isMobile && this.add(l.default), t3.fastForward && o.isMobile && !t3.isLive && this.add(d2.default);
            for (let e3 = 0; e3 < t3.plugins.length; e3++) this.add(t3.plugins[e3]);
          }
          add(e2) {
            this.id += 1;
            let t3 = e2.call(this.art, this.art);
            return t3 instanceof Promise ? t3.then((t4) => this.next(e2, t4)) : this.next(e2, t3);
          }
          next(e2, t3) {
            let r3 = t3 && t3.name || e2.name || `plugin${this.id}`;
            return (0, o.errorHandle)(!(0, o.has)(this, r3), `Cannot add a plugin that already has the same name: ${r3}`), (0, o.def)(this, r3, {
              value: t3
            }), this;
          }
        };
      }, {
        "../utils": "71aH7",
        "./miniProgressBar": "87pSL",
        "./autoOrientation": "ePEg5",
        "./autoPlayback": "cVO99",
        "./fastForward": "hFDwt",
        "./lock": "1hsTH",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "87pSL": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          return e2.on("control", (t3) => {
            t3 ? (0, o.removeClass)(e2.template.$player, "art-mini-progress-bar") : (0, o.addClass)(e2.template.$player, "art-mini-progress-bar");
          }), {
            name: "mini-progress-bar"
          };
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      ePEg5: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            constructor: t3,
            template: {
              $player: r3,
              $video: a2
            }
          } = e2;
          return e2.on("fullscreenWeb", (i2) => {
            if (i2) {
              let {
                videoWidth: i3,
                videoHeight: n
              } = a2, {
                clientWidth: s,
                clientHeight: l
              } = document.documentElement;
              (i3 > n && s < l || i3 < n && s > l) && setTimeout(() => {
                (0, o.setStyle)(r3, "width", `${l}px`), (0, o.setStyle)(r3, "height", `${s}px`), (0, o.setStyle)(r3, "transform-origin", "0 0"), (0, o.setStyle)(r3, "transform", `rotate(90deg) translate(0, -${s}px)`), (0, o.addClass)(r3, "art-auto-orientation"), e2.isRotate = true, e2.emit("resize");
              }, t3.AUTO_ORIENTATION_TIME);
            } else (0, o.hasClass)(r3, "art-auto-orientation") && ((0, o.removeClass)(r3, "art-auto-orientation"), e2.isRotate = false, e2.emit("resize"));
          }), e2.on("fullscreen", (e3) => __async(null, null, function* () {
            if (!screen?.orientation?.lock) return;
            let t4 = screen.orientation.type;
            if (e3) {
              let {
                videoWidth: e4,
                videoHeight: i2
              } = a2, {
                clientWidth: n,
                clientHeight: s
              } = document.documentElement;
              if (e4 > i2 && n < s || e4 < i2 && n > s) {
                let e5 = t4.startsWith("portrait") ? "landscape" : "portrait";
                yield screen.orientation.lock(e5), (0, o.addClass)(r3, "art-auto-orientation-fullscreen");
              }
            } else (0, o.hasClass)(r3, "art-auto-orientation-fullscreen") && (yield screen.orientation.lock(t4), (0, o.removeClass)(r3, "art-auto-orientation-fullscreen"));
          })), {
            name: "autoOrientation",
            get state() {
              return (0, o.hasClass)(r3, "art-auto-orientation");
            }
          };
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      cVO99: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            i18n: t3,
            icons: r3,
            storage: a2,
            constructor: i2,
            proxy: n,
            template: {
              $poster: s
            }
          } = e2, l = e2.layers.add({
            name: "auto-playback",
            html: `<div class="art-auto-playback-close"></div><div class="art-auto-playback-last"></div><div class="art-auto-playback-jump"></div>`
          }), c = (0, o.query)(".art-auto-playback-last", l), p = (0, o.query)(".art-auto-playback-jump", l), u = (0, o.query)(".art-auto-playback-close", l);
          (0, o.append)(u, r3.close);
          let d2 = null;
          function f() {
            let r4 = (a2.get("times") || {})[e2.option.id || e2.option.url];
            clearTimeout(d2), (0, o.setStyle)(l, "display", "none"), r4 && r4 >= i2.AUTO_PLAYBACK_MIN && ((0, o.setStyle)(l, "display", "flex"), c.innerText = `${t3.get("Last Seen")} ${(0, o.secondToTime)(r4)}`, p.innerText = t3.get("Jump Play"), n(u, "click", () => {
              (0, o.setStyle)(l, "display", "none");
            }), n(p, "click", () => {
              e2.seek = r4, e2.play(), (0, o.setStyle)(s, "display", "none"), (0, o.setStyle)(l, "display", "none");
            }), e2.once("video:timeupdate", () => {
              d2 = setTimeout(() => {
                (0, o.setStyle)(l, "display", "none");
              }, i2.AUTO_PLAYBACK_TIMEOUT);
            }));
          }
          return e2.on("video:timeupdate", () => {
            if (e2.playing) {
              let t4 = a2.get("times") || {}, r4 = Object.keys(t4);
              r4.length > i2.AUTO_PLAYBACK_MAX && delete t4[r4[0]], t4[e2.option.id || e2.option.url] = e2.currentTime, a2.set("times", t4);
            }
          }), e2.on("ready", f), e2.on("restart", f), {
            name: "auto-playback",
            get times() {
              return a2.get("times") || {};
            },
            clear: () => a2.del("times"),
            delete(e3) {
              let t4 = a2.get("times") || {};
              return delete t4[e3], a2.set("times", t4), t4;
            }
          };
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      hFDwt: [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            constructor: t3,
            proxy: r3,
            template: {
              $player: a2,
              $video: i2
            }
          } = e2, n = null, s = false, l = 1, c = () => {
            clearTimeout(n), s && (s = false, e2.playbackRate = l, (0, o.removeClass)(a2, "art-fast-forward"));
          };
          return r3(i2, "touchstart", (r4) => {
            1 === r4.touches.length && e2.playing && !e2.isLock && (n = setTimeout(() => {
              s = true, l = e2.playbackRate, e2.playbackRate = t3.FAST_FORWARD_VALUE, (0, o.addClass)(a2, "art-fast-forward");
            }, t3.FAST_FORWARD_TIME));
          }), r3(document, "touchmove", c), r3(document, "touchend", c), {
            name: "fastForward",
            get state() {
              return (0, o.hasClass)(a2, "art-fast-forward");
            }
          };
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }],
      "1hsTH": [function(e, t2, r2) {
        var a = e("@parcel/transformer-js/src/esmodule-helpers.js");
        a.defineInteropFlag(r2), a.export(r2, "default", () => i);
        var o = e("../utils");
        function i(e2) {
          let {
            layers: t3,
            icons: r3,
            template: {
              $player: a2
            }
          } = e2;
          function i2() {
            return (0, o.hasClass)(a2, "art-lock");
          }
          function n() {
            (0, o.addClass)(a2, "art-lock"), e2.isLock = true, e2.emit("lock", true);
          }
          function s() {
            (0, o.removeClass)(a2, "art-lock"), e2.isLock = false, e2.emit("lock", false);
          }
          return t3.add({
            name: "lock",
            mounted(t4) {
              let a3 = (0, o.append)(t4, r3.lock), i3 = (0, o.append)(t4, r3.unlock);
              (0, o.setStyle)(a3, "display", "none"), e2.on("lock", (e3) => {
                e3 ? ((0, o.setStyle)(a3, "display", "inline-flex"), (0, o.setStyle)(i3, "display", "none")) : ((0, o.setStyle)(a3, "display", "none"), (0, o.setStyle)(i3, "display", "inline-flex"));
              });
            },
            click() {
              i2() ? s() : n();
            }
          }), {
            name: "lock",
            get state() {
              return i2();
            },
            set state(value) {
              value ? n() : s();
            }
          };
        }
      }, {
        "../utils": "71aH7",
        "@parcel/transformer-js/src/esmodule-helpers.js": "9pCYc"
      }]
    }, ["5lTcX"], "5lTcX", "parcelRequire4dc0");
  }
});

// node_modules/.pnpm/dplayer@1.27.1/node_modules/dplayer/dist/DPlayer.min.js
var require_DPlayer_min = __commonJS({
  "node_modules/.pnpm/dplayer@1.27.1/node_modules/dplayer/dist/DPlayer.min.js"(exports, module) {
    !function(n, e) {
      "object" == typeof exports && "object" == typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define("DPlayer", [], e) : "object" == typeof exports ? exports.DPlayer = e() : n.DPlayer = e();
    }(self, () => (() => {
      var n = {
        916: (n2, e2, t3) => {
          var a2 = t3(471);
          n2.exports = function(n3) {
            "use strict";
            var e3, o = "", r2 = (n3 = n3 || {}).video, i = n3.options, l = a2.$escape, s = n3.tran, p = n3.icons, d2 = n3.index, c = a2.$each;
            return n3.$value, n3.$index, o += '<div class="dplayer-mask"></div>\n<div class="dplayer-video-wrap">\n    ', e3 = t3(568)(r2), o += e3, o += "\n    ", i.logo && (o += '\n    <div class="dplayer-logo">\n        <img src="', o += l(i.logo), o += '">\n    </div>\n    '), o += '\n    <div class="dplayer-danmaku"', i.danmaku && i.danmaku.bottom && (o += ' style="margin-bottom:', o += l(i.danmaku.bottom), o += '"'), o += '>\n        <div class="dplayer-danmaku-item dplayer-danmaku-item--demo"></div>\n    </div>\n    <div class="dplayer-subtitle"></div>\n    <div class="dplayer-bezel">\n        <span class="dplayer-bezel-icon"></span>\n        ', i.danmaku && (o += '\n        <span class="dplayer-danloading">', o += l(s("danmaku-loading")), o += "</span>\n        "), o += '\n        <span class="diplayer-loading-icon">', o += p.loading, o += '</span>\n    </div>\n</div>\n<div class="dplayer-controller-mask"></div>\n<div class="dplayer-controller">\n    <div class="dplayer-icons dplayer-comment-box">\n        <button class="dplayer-icon dplayer-comment-setting-icon" data-balloon="', o += l(s("setting")), o += '" data-balloon-pos="up">\n            <span class="dplayer-icon-content">', o += p.pallette, o += '</span>\n        </button>\n        <div class="dplayer-comment-setting-box">\n            <div class="dplayer-comment-setting-color">\n                <div class="dplayer-comment-setting-title">', o += l(s("set-danmaku-color")), o += '</div>\n                <label>\n                    <input type="radio" name="dplayer-danmaku-color-', o += l(d2), o += '" value="#fff" checked>\n                    <span style="background: #fff;"></span>\n                </label>\n                <label>\n                    <input type="radio" name="dplayer-danmaku-color-', o += l(d2), o += '" value="#e54256">\n                    <span style="background: #e54256"></span>\n                </label>\n                <label>\n                    <input type="radio" name="dplayer-danmaku-color-', o += l(d2), o += '" value="#ffe133">\n                    <span style="background: #ffe133"></span>\n                </label>\n                <label>\n                    <input type="radio" name="dplayer-danmaku-color-', o += l(d2), o += '" value="#64DD17">\n                    <span style="background: #64DD17"></span>\n                </label>\n                <label>\n                    <input type="radio" name="dplayer-danmaku-color-', o += l(d2), o += '" value="#39ccff">\n                    <span style="background: #39ccff"></span>\n                </label>\n                <label>\n                    <input type="radio" name="dplayer-danmaku-color-', o += l(d2), o += '" value="#D500F9">\n                    <span style="background: #D500F9"></span>\n                </label>\n            </div>\n            <div class="dplayer-comment-setting-type">\n                <div class="dplayer-comment-setting-title">', o += l(s("set-danmaku-type")), o += '</div>\n                <label>\n                    <input type="radio" name="dplayer-danmaku-type-', o += l(d2), o += '" value="1">\n                    <span>', o += l(s("top")), o += '</span>\n                </label>\n                <label>\n                    <input type="radio" name="dplayer-danmaku-type-', o += l(d2), o += '" value="0" checked>\n                    <span>', o += l(s("rolling")), o += '</span>\n                </label>\n                <label>\n                    <input type="radio" name="dplayer-danmaku-type-', o += l(d2), o += '" value="2">\n                    <span>', o += l(s("bottom")), o += '</span>\n                </label>\n            </div>\n        </div>\n        <input class="dplayer-comment-input" type="text" placeholder="', o += l(s("input-danmaku-enter")), o += '" maxlength="30">\n        <button class="dplayer-icon dplayer-send-icon" data-balloon="', o += l(s("send")), o += '" data-balloon-pos="up">\n            <span class="dplayer-icon-content">', o += p.send, o += '</span>\n        </button>\n    </div>\n    <div class="dplayer-icons dplayer-icons-left">\n        <button class="dplayer-icon dplayer-play-icon">\n            <span class="dplayer-icon-content">', o += p.play, o += '</span>\n        </button>\n        <div class="dplayer-volume">\n            <button class="dplayer-icon dplayer-volume-icon">\n                <span class="dplayer-icon-content">', o += p.volumeDown, o += '</span>\n            </button>\n            <div class="dplayer-volume-bar-wrap" data-balloon-pos="up">\n                <div class="dplayer-volume-bar">\n                    <div class="dplayer-volume-bar-inner" style="background: ', o += l(i.theme), o += ';">\n                        <span class="dplayer-thumb" style="background: ', o += l(i.theme), o += '"></span>\n                    </div>\n                </div>\n            </div>\n        </div>\n        <span class="dplayer-time">\n            <span class="dplayer-ptime">0:00</span> /\n            <span class="dplayer-dtime">0:00</span>\n        </span>\n        ', i.live && (o += '\n        <span class="dplayer-live-badge"><span class="dplayer-live-dot" style="background: ', o += l(i.theme), o += ';"></span>', o += l(s("live")), o += "</span>\n        "), o += '\n    </div>\n    <div class="dplayer-icons dplayer-icons-right">\n        ', i.video.quality && (o += '\n        <div class="dplayer-quality">\n            <button class="dplayer-icon dplayer-quality-icon">', o += l(i.video.quality[i.video.defaultQuality].name), o += '</button>\n            <div class="dplayer-quality-mask">\n                <div class="dplayer-quality-list">\n                ', c(i.video.quality, function(n4, e4) {
              o += '\n                    <div class="dplayer-quality-item" data-index="', o += l(e4), o += '">', o += l(n4.name), o += "</div>\n                ";
            }), o += "\n                </div>\n            </div>\n        </div>\n        "), o += "\n        ", i.screenshot && (o += '\n        <div class="dplayer-icon dplayer-camera-icon" data-balloon="', o += l(s("screenshot")), o += '" data-balloon-pos="up">\n            <span class="dplayer-icon-content">', o += p.camera, o += "</span>\n        </div>\n        "), o += "\n        ", i.airplay && (o += '\n        <div class="dplayer-icon dplayer-airplay-icon" data-balloon="', o += l(s("airplay")), o += '" data-balloon-pos="up">\n            <span class="dplayer-icon-content">', o += p.airplay, o += "</span>\n        </div>\n        "), o += "\n        ", i.chromecast && (o += '\n        <div class="dplayer-icon dplayer-chromecast-icon" data-balloon="', o += l(s("chromecast")), o += '" data-balloon-pos="up">\n            <span class="dplayer-icon-content">', o += p.chromecast, o += "</span>\n        </div>\n        "), o += '\n        <div class="dplayer-comment">\n            <button class="dplayer-icon dplayer-comment-icon" data-balloon="', o += l(s("send-danmaku")), o += '" data-balloon-pos="up">\n                <span class="dplayer-icon-content">', o += p.comment, o += "</span>\n            </button>\n        </div>\n        ", i.subtitle && (o += "\n        ", "string" == typeof i.subtitle.url ? (o += '\n        <div class="dplayer-subtitle-btn">\n            <button class="dplayer-icon dplayer-subtitle-icon" data-balloon="', o += l(s("hide-subs")), o += '" data-balloon-pos="up">\n                <span class="dplayer-icon-content">', o += p.subtitle, o += "</span>\n            </button>\n        </div>\n        ") : (o += '\n        <div class="dplayer-subtitles">\n            <button class="dplayer-icon dplayer-subtitles-icon" data-balloon="', o += l(s("subtitle")), o += '" data-balloon-pos="up">\n                <span class="dplayer-icon-content">', o += p.subtitle, o += '</span>\n            </button>\n            <div class="dplayer-subtitles-box">\n                <div class="dplayer-subtitles-panel">\n                    ', c(i.subtitle.url, function(n4, e4) {
              o += '\n                        <div class="dplayer-subtitles-item" data-subtitle="', o += l(n4.url), o += '">\n                            <!-- if lang, show tran(lang). if lang and name, show name + (tran(lang)). if name, show name. off option use lang for translation. -->\n                            <span class="dplayer-label">', o += l(n4.lang ? n4.name ? n4.name + " (" + s(n4.lang) + ")" : s(n4.lang) : n4.name), o += "</span>\n                        </div>\n                    ";
            }), o += "\n                </div>\n            </div>\n        </div>\n        "), o += "\n        "), o += '\n        <div class="dplayer-setting">\n            <button class="dplayer-icon dplayer-setting-icon" data-balloon="', o += l(s("setting")), o += '" data-balloon-pos="up">\n                <span class="dplayer-icon-content">', o += p.setting, o += '</span>\n            </button>\n            <div class="dplayer-setting-box">\n                <div class="dplayer-setting-origin-panel">\n                    <div class="dplayer-setting-item dplayer-setting-speed">\n                        <span class="dplayer-label">', o += l(s("speed")), o += '</span>\n                        <div class="dplayer-toggle">', o += p.right, o += '</div>\n                    </div>\n                    <div class="dplayer-setting-item dplayer-setting-loop">\n                        <span class="dplayer-label">', o += l(s("loop")), o += '</span>\n                        <div class="dplayer-toggle">\n                            <input class="dplayer-toggle-setting-input" type="checkbox" name="dplayer-toggle">\n                            <label for="dplayer-toggle"></label>\n                        </div>\n                    </div>\n                    <div class="dplayer-setting-item dplayer-setting-showdan">\n                        <span class="dplayer-label">', o += l(s("show-danmaku")), o += '</span>\n                        <div class="dplayer-toggle">\n                            <input class="dplayer-showdan-setting-input" type="checkbox" name="dplayer-toggle-dan">\n                            <label for="dplayer-toggle-dan"></label>\n                        </div>\n                    </div>\n                    <div class="dplayer-setting-item dplayer-setting-danunlimit">\n                        <span class="dplayer-label">', o += l(s("unlimited-danmaku")), o += '</span>\n                        <div class="dplayer-toggle">\n                            <input class="dplayer-danunlimit-setting-input" type="checkbox" name="dplayer-toggle-danunlimit">\n                            <label for="dplayer-toggle-danunlimit"></label>\n                        </div>\n                    </div>\n                    <div class="dplayer-setting-item dplayer-setting-danmaku">\n                        <span class="dplayer-label">', o += l(s("opacity-danmaku")), o += '</span>\n                        <div class="dplayer-danmaku-bar-wrap">\n                            <div class="dplayer-danmaku-bar">\n                                <div class="dplayer-danmaku-bar-inner">\n                                    <span class="dplayer-thumb"></span>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n                <div class="dplayer-setting-speed-panel">\n                    ', c(i.playbackSpeed, function(n4, e4) {
              o += '\n                        <div class="dplayer-setting-speed-item" data-speed="', o += l(n4), o += '">\n                            <span class="dplayer-label">', o += l(1 === n4 ? s("normal") : n4), o += "</span>\n                        </div>\n                    ";
            }), o += '\n                </div>\n            </div>\n        </div>\n        <div class="dplayer-full">\n            <button class="dplayer-icon dplayer-full-in-icon" data-balloon="', o += l(s("web-fullscreen")), o += '" data-balloon-pos="up">\n                <span class="dplayer-icon-content">', o += p.fullWeb, o += '</span>\n            </button>\n            <button class="dplayer-icon dplayer-full-icon" data-balloon="', o += l(s("fullscreen")), o += '" data-balloon-pos="up">\n                <span class="dplayer-icon-content">', o += p.full, o += '</span>\n            </button>\n        </div>\n    </div>\n    <div class="dplayer-bar-wrap">\n        <div class="dplayer-bar-time hidden">00:00</div>\n        <div class="dplayer-bar-preview"></div>\n        <div class="dplayer-bar">\n            <div class="dplayer-loaded" style="width: 0;"></div>\n            <div class="dplayer-played" style="width: 0; background: ', o += l(i.theme), o += '">\n                <span class="dplayer-thumb" style="background: ', o += l(i.theme), o += '"></span>\n            </div>\n        </div>\n    </div>\n</div>\n<div class="dplayer-info-panel dplayer-info-panel-hide">\n    <div class="dplayer-info-panel-close">[x]</div>\n    <div class="dplayer-info-panel-item dplayer-info-panel-item-version">\n        <span class="dplayer-info-panel-item-title">Player version</span>\n        <span class="dplayer-info-panel-item-data"></span>\n    </div>\n    <div class="dplayer-info-panel-item dplayer-info-panel-item-fps">\n        <span class="dplayer-info-panel-item-title">Player FPS</span>\n        <span class="dplayer-info-panel-item-data"></span>\n    </div>\n    <div class="dplayer-info-panel-item dplayer-info-panel-item-type">\n        <span class="dplayer-info-panel-item-title">Video type</span>\n        <span class="dplayer-info-panel-item-data"></span>\n    </div>\n    <div class="dplayer-info-panel-item dplayer-info-panel-item-url">\n        <span class="dplayer-info-panel-item-title">Video url</span>\n        <span class="dplayer-info-panel-item-data"></span>\n    </div>\n    <div class="dplayer-info-panel-item dplayer-info-panel-item-resolution">\n        <span class="dplayer-info-panel-item-title">Video resolution</span>\n        <span class="dplayer-info-panel-item-data"></span>\n    </div>\n    <div class="dplayer-info-panel-item dplayer-info-panel-item-duration">\n        <span class="dplayer-info-panel-item-title">Video duration</span>\n        <span class="dplayer-info-panel-item-data"></span>\n    </div>\n    ', i.danmaku && (o += '\n    <div class="dplayer-info-panel-item dplayer-info-panel-item-danmaku-id">\n        <span class="dplayer-info-panel-item-title">Danmaku id</span>\n        <span class="dplayer-info-panel-item-data"></span>\n    </div>\n    <div class="dplayer-info-panel-item dplayer-info-panel-item-danmaku-api">\n        <span class="dplayer-info-panel-item-title">Danmaku api</span>\n        <span class="dplayer-info-panel-item-data"></span>\n    </div>\n    <div class="dplayer-info-panel-item dplayer-info-panel-item-danmaku-amount">\n        <span class="dplayer-info-panel-item-title">Danmaku amount</span>\n        <span class="dplayer-info-panel-item-data"></span>\n    </div>\n    '), o += '\n</div>\n<div class="dplayer-menu">\n    ', c(i.contextmenu, function(n4, e4) {
              o += '\n        <div class="dplayer-menu-item">\n            <a', n4.link && (o += ' target="_blank"'), o += ' href="', o += l(n4.link || "javascript:void(0);"), o += '">', n4.key && (o += " ", o += l(s(n4.key))), n4.text && (o += " ", o += l(n4.text)), o += "</a>\n        </div>\n    ";
            }), o += '\n</div>\n<div class="dplayer-notice-list"></div>\n<button class="dplayer-mobile-play">\n    ', o += p.play, o += "\n</button>";
          };
        },
        568: (n2, e2, t3) => {
          var a2 = t3(471);
          n2.exports = function(n3) {
            "use strict";
            var e3 = "", t4 = (n3 = n3 || {}).enableSubtitle, o = n3.subtitle, r2 = n3.current, i = n3.airplay, l = n3.pic, s = a2.$escape, p = n3.screenshot, d2 = n3.preload, c = n3.url;
            return t4 = o && "webvtt" === o.type, e3 += '\n<video\n    class="dplayer-video ', r2 && (e3 += "dplayer-video-current"), e3 += '"\n    webkit-playsinline\n    ', i && (e3 += ' x-webkit-airplay="allow" '), e3 += "\n    playsinline\n    ", l && (e3 += 'poster="', e3 += s(l), e3 += '"'), e3 += "\n    ", (p || t4) && (e3 += 'crossorigin="anonymous"'), e3 += "\n    ", d2 && (e3 += 'preload="', e3 += s(d2), e3 += '"'), e3 += "\n    ", i ? e3 += "\n    nosrc\n    " : c && (e3 += '\n    src="', e3 += s(c), e3 += '"\n    '), e3 += "\n    >\n    ", i && (e3 += '\n    <source src="', e3 += s(c), e3 += '">\n    '), e3 += "\n    ", t4 && (e3 += '\n    <track class="dplayer-subtrack" kind="metadata" default src="', e3 += s("string" == typeof o.url ? o.url : o.url[o.index].url), e3 += '"></track>\n    '), e3 + "\n</video>";
          };
        },
        49: (n2, e2, t3) => {
          "use strict";
          t3.d(e2, {
            Z: () => l
          });
          var a2 = t3(415), o = t3.n(a2), r2 = t3(352), i = t3.n(r2)()(o());
          i.push([n2.id, `:root {
  --balloon-border-radius: 2px;
  --balloon-color: rgba(16, 16, 16, 0.95);
  --balloon-text-color: #fff;
  --balloon-font-size: 12px;
  --balloon-move: 4px; }

button[aria-label][data-balloon-pos] {
  overflow: visible; }

[aria-label][data-balloon-pos] {
  position: relative;
  cursor: pointer; }
  [aria-label][data-balloon-pos]:after {
    opacity: 0;
    pointer-events: none;
    transition: all 0.18s ease-out 0.18s;
    text-indent: 0;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
    font-weight: normal;
    font-style: normal;
    text-shadow: none;
    font-size: 12px;
    font-size: var(--balloon-font-size);
    background: rgba(16, 16, 16, 0.95);
    background: var(--balloon-color);
    border-radius: 2px;
    color: #fff;
    color: var(--balloon-text-color);
    border-radius: var(--balloon-border-radius);
    content: attr(aria-label);
    padding: .5em 1em;
    position: absolute;
    white-space: nowrap;
    z-index: 10; }
  [aria-label][data-balloon-pos]:before {
    width: 0;
    height: 0;
    border: 5px solid transparent;
    border-top-color: rgba(16, 16, 16, 0.95);
    border-top-color: var(--balloon-color);
    opacity: 0;
    pointer-events: none;
    transition: all 0.18s ease-out 0.18s;
    content: "";
    position: absolute;
    z-index: 10; }
  [aria-label][data-balloon-pos]:hover:before, [aria-label][data-balloon-pos]:hover:after, [aria-label][data-balloon-pos][data-balloon-visible]:before, [aria-label][data-balloon-pos][data-balloon-visible]:after, [aria-label][data-balloon-pos]:not([data-balloon-nofocus]):focus:before, [aria-label][data-balloon-pos]:not([data-balloon-nofocus]):focus:after {
    opacity: 1;
    pointer-events: none; }
  [aria-label][data-balloon-pos].font-awesome:after {
    font-family: FontAwesome, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; }
  [aria-label][data-balloon-pos][data-balloon-break]:after {
    white-space: pre; }
  [aria-label][data-balloon-pos][data-balloon-break][data-balloon-length]:after {
    white-space: pre-line;
    word-break: break-word; }
  [aria-label][data-balloon-pos][data-balloon-blunt]:before, [aria-label][data-balloon-pos][data-balloon-blunt]:after {
    transition: none; }
  [aria-label][data-balloon-pos][data-balloon-pos="up"]:hover:after, [aria-label][data-balloon-pos][data-balloon-pos="up"][data-balloon-visible]:after, [aria-label][data-balloon-pos][data-balloon-pos="down"]:hover:after, [aria-label][data-balloon-pos][data-balloon-pos="down"][data-balloon-visible]:after {
    transform: translate(-50%, 0); }
  [aria-label][data-balloon-pos][data-balloon-pos="up"]:hover:before, [aria-label][data-balloon-pos][data-balloon-pos="up"][data-balloon-visible]:before, [aria-label][data-balloon-pos][data-balloon-pos="down"]:hover:before, [aria-label][data-balloon-pos][data-balloon-pos="down"][data-balloon-visible]:before {
    transform: translate(-50%, 0); }
  [aria-label][data-balloon-pos][data-balloon-pos*="-left"]:after {
    left: 0; }
  [aria-label][data-balloon-pos][data-balloon-pos*="-left"]:before {
    left: 5px; }
  [aria-label][data-balloon-pos][data-balloon-pos*="-right"]:after {
    right: 0; }
  [aria-label][data-balloon-pos][data-balloon-pos*="-right"]:before {
    right: 5px; }
  [aria-label][data-balloon-pos][data-balloon-po*="-left"]:hover:after, [aria-label][data-balloon-pos][data-balloon-po*="-left"][data-balloon-visible]:after, [aria-label][data-balloon-pos][data-balloon-pos*="-right"]:hover:after, [aria-label][data-balloon-pos][data-balloon-pos*="-right"][data-balloon-visible]:after {
    transform: translate(0, 0); }
  [aria-label][data-balloon-pos][data-balloon-po*="-left"]:hover:before, [aria-label][data-balloon-pos][data-balloon-po*="-left"][data-balloon-visible]:before, [aria-label][data-balloon-pos][data-balloon-pos*="-right"]:hover:before, [aria-label][data-balloon-pos][data-balloon-pos*="-right"][data-balloon-visible]:before {
    transform: translate(0, 0); }
  [aria-label][data-balloon-pos][data-balloon-pos^="up"]:before, [aria-label][data-balloon-pos][data-balloon-pos^="up"]:after {
    bottom: 100%;
    transform-origin: top;
    transform: translate(0, 4px);
    transform: translate(0, var(--balloon-move)); }
  [aria-label][data-balloon-pos][data-balloon-pos^="up"]:after {
    margin-bottom: 10px; }
  [aria-label][data-balloon-pos][data-balloon-pos="up"]:before, [aria-label][data-balloon-pos][data-balloon-pos="up"]:after {
    left: 50%;
    transform: translate(-50%, 4px);
    transform: translate(-50%, var(--balloon-move)); }
  [aria-label][data-balloon-pos][data-balloon-pos^="down"]:before, [aria-label][data-balloon-pos][data-balloon-pos^="down"]:after {
    top: 100%;
    transform: translate(0, calc(4px * -1));
    transform: translate(0, calc(var(--balloon-move) * -1)); }
  [aria-label][data-balloon-pos][data-balloon-pos^="down"]:after {
    margin-top: 10px; }
  [aria-label][data-balloon-pos][data-balloon-pos^="down"]:before {
    width: 0;
    height: 0;
    border: 5px solid transparent;
    border-bottom-color: rgba(16, 16, 16, 0.95);
    border-bottom-color: var(--balloon-color); }
  [aria-label][data-balloon-pos][data-balloon-pos="down"]:after, [aria-label][data-balloon-pos][data-balloon-pos="down"]:before {
    left: 50%;
    transform: translate(-50%, calc(4px * -1));
    transform: translate(-50%, calc(var(--balloon-move) * -1)); }
  [aria-label][data-balloon-pos][data-balloon-pos="left"]:hover:after, [aria-label][data-balloon-pos][data-balloon-pos="left"][data-balloon-visible]:after, [aria-label][data-balloon-pos][data-balloon-pos="right"]:hover:after, [aria-label][data-balloon-pos][data-balloon-pos="right"][data-balloon-visible]:after {
    transform: translate(0, -50%); }
  [aria-label][data-balloon-pos][data-balloon-pos="left"]:hover:before, [aria-label][data-balloon-pos][data-balloon-pos="left"][data-balloon-visible]:before, [aria-label][data-balloon-pos][data-balloon-pos="right"]:hover:before, [aria-label][data-balloon-pos][data-balloon-pos="right"][data-balloon-visible]:before {
    transform: translate(0, -50%); }
  [aria-label][data-balloon-pos][data-balloon-pos="left"]:after, [aria-label][data-balloon-pos][data-balloon-pos="left"]:before {
    right: 100%;
    top: 50%;
    transform: translate(4px, -50%);
    transform: translate(var(--balloon-move), -50%); }
  [aria-label][data-balloon-pos][data-balloon-pos="left"]:after {
    margin-right: 10px; }
  [aria-label][data-balloon-pos][data-balloon-pos="left"]:before {
    width: 0;
    height: 0;
    border: 5px solid transparent;
    border-left-color: rgba(16, 16, 16, 0.95);
    border-left-color: var(--balloon-color); }
  [aria-label][data-balloon-pos][data-balloon-pos="right"]:after, [aria-label][data-balloon-pos][data-balloon-pos="right"]:before {
    left: 100%;
    top: 50%;
    transform: translate(calc(4px * -1), -50%);
    transform: translate(calc(var(--balloon-move) * -1), -50%); }
  [aria-label][data-balloon-pos][data-balloon-pos="right"]:after {
    margin-left: 10px; }
  [aria-label][data-balloon-pos][data-balloon-pos="right"]:before {
    width: 0;
    height: 0;
    border: 5px solid transparent;
    border-right-color: rgba(16, 16, 16, 0.95);
    border-right-color: var(--balloon-color); }
  [aria-label][data-balloon-pos][data-balloon-length]:after {
    white-space: normal; }
  [aria-label][data-balloon-pos][data-balloon-length="small"]:after {
    width: 80px; }
  [aria-label][data-balloon-pos][data-balloon-length="medium"]:after {
    width: 150px; }
  [aria-label][data-balloon-pos][data-balloon-length="large"]:after {
    width: 260px; }
  [aria-label][data-balloon-pos][data-balloon-length="xlarge"]:after {
    width: 380px; }
    @media screen and (max-width: 768px) {
      [aria-label][data-balloon-pos][data-balloon-length="xlarge"]:after {
        width: 90vw; } }
  [aria-label][data-balloon-pos][data-balloon-length="fit"]:after {
    width: 100%; }
`, "", {
            version: 3,
            sources: ["webpack://./node_modules/.pnpm/balloon-css@1.2.0/node_modules/balloon-css/balloon.css"],
            names: [],
            mappings: "AAAA;EACE,4BAA4B;EAC5B,uCAAuC;EACvC,0BAA0B;EAC1B,yBAAyB;EACzB,mBAAmB,EAAE;;AAEvB;EACE,iBAAiB,EAAE;;AAErB;EACE,kBAAkB;EAClB,eAAe,EAAE;EACjB;IACE,UAAU;IACV,oBAAoB;IACpB,oCAAoC;IACpC,cAAc;IACd,wIAAwI;IACxI,mBAAmB;IACnB,kBAAkB;IAClB,iBAAiB;IACjB,eAAmC;IAAnC,mCAAmC;IACnC,kCAAgC;IAAhC,gCAAgC;IAChC,kBAAkB;IAClB,WAAgC;IAAhC,gCAAgC;IAChC,2CAA2C;IAC3C,yBAAyB;IACzB,iBAAiB;IACjB,kBAAkB;IAClB,mBAAmB;IACnB,WAAW,EAAE;EACf;IACE,QAAQ;IACR,SAAS;IACT,6BAA6B;IAC7B,wCAAsC;IAAtC,sCAAsC;IACtC,UAAU;IACV,oBAAoB;IACpB,oCAAoC;IACpC,WAAW;IACX,kBAAkB;IAClB,WAAW,EAAE;EACf;IACE,UAAU;IACV,oBAAoB,EAAE;EACxB;IACE,qJAAqJ,EAAE;EACzJ;IACE,gBAAgB,EAAE;EACpB;IACE,qBAAqB;IACrB,sBAAsB,EAAE;EAC1B;IACE,gBAAgB,EAAE;EACpB;IACE,6BAA6B,EAAE;EACjC;IACE,6BAA6B,EAAE;EACjC;IACE,OAAO,EAAE;EACX;IACE,SAAS,EAAE;EACb;IACE,QAAQ,EAAE;EACZ;IACE,UAAU,EAAE;EACd;IACE,0BAA0B,EAAE;EAC9B;IACE,0BAA0B,EAAE;EAC9B;IACE,YAAY;IACZ,qBAAqB;IACrB,4BAA4C;IAA5C,4CAA4C,EAAE;EAChD;IACE,mBAAmB,EAAE;EACvB;IACE,SAAS;IACT,+BAA+C;IAA/C,+CAA+C,EAAE;EACnD;IACE,SAAS;IACT,uCAAuD;IAAvD,uDAAuD,EAAE;EAC3D;IACE,gBAAgB,EAAE;EACpB;IACE,QAAQ;IACR,SAAS;IACT,6BAA6B;IAC7B,2CAAyC;IAAzC,yCAAyC,EAAE;EAC7C;IACE,SAAS;IACT,0CAA0D;IAA1D,0DAA0D,EAAE;EAC9D;IACE,6BAA6B,EAAE;EACjC;IACE,6BAA6B,EAAE;EACjC;IACE,WAAW;IACX,QAAQ;IACR,+BAA+C;IAA/C,+CAA+C,EAAE;EACnD;IACE,kBAAkB,EAAE;EACtB;IACE,QAAQ;IACR,SAAS;IACT,6BAA6B;IAC7B,yCAAuC;IAAvC,uCAAuC,EAAE;EAC3C;IACE,UAAU;IACV,QAAQ;IACR,0CAA0D;IAA1D,0DAA0D,EAAE;EAC9D;IACE,iBAAiB,EAAE;EACrB;IACE,QAAQ;IACR,SAAS;IACT,6BAA6B;IAC7B,0CAAwC;IAAxC,wCAAwC,EAAE;EAC5C;IACE,mBAAmB,EAAE;EACvB;IACE,WAAW,EAAE;EACf;IACE,YAAY,EAAE;EAChB;IACE,YAAY,EAAE;EAChB;IACE,YAAY,EAAE;IACd;MACE;QACE,WAAW,EAAE,EAAE;EACrB;IACE,WAAW,EAAE",
            sourcesContent: [`:root {
  --balloon-border-radius: 2px;
  --balloon-color: rgba(16, 16, 16, 0.95);
  --balloon-text-color: #fff;
  --balloon-font-size: 12px;
  --balloon-move: 4px; }

button[aria-label][data-balloon-pos] {
  overflow: visible; }

[aria-label][data-balloon-pos] {
  position: relative;
  cursor: pointer; }
  [aria-label][data-balloon-pos]:after {
    opacity: 0;
    pointer-events: none;
    transition: all 0.18s ease-out 0.18s;
    text-indent: 0;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
    font-weight: normal;
    font-style: normal;
    text-shadow: none;
    font-size: var(--balloon-font-size);
    background: var(--balloon-color);
    border-radius: 2px;
    color: var(--balloon-text-color);
    border-radius: var(--balloon-border-radius);
    content: attr(aria-label);
    padding: .5em 1em;
    position: absolute;
    white-space: nowrap;
    z-index: 10; }
  [aria-label][data-balloon-pos]:before {
    width: 0;
    height: 0;
    border: 5px solid transparent;
    border-top-color: var(--balloon-color);
    opacity: 0;
    pointer-events: none;
    transition: all 0.18s ease-out 0.18s;
    content: "";
    position: absolute;
    z-index: 10; }
  [aria-label][data-balloon-pos]:hover:before, [aria-label][data-balloon-pos]:hover:after, [aria-label][data-balloon-pos][data-balloon-visible]:before, [aria-label][data-balloon-pos][data-balloon-visible]:after, [aria-label][data-balloon-pos]:not([data-balloon-nofocus]):focus:before, [aria-label][data-balloon-pos]:not([data-balloon-nofocus]):focus:after {
    opacity: 1;
    pointer-events: none; }
  [aria-label][data-balloon-pos].font-awesome:after {
    font-family: FontAwesome, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; }
  [aria-label][data-balloon-pos][data-balloon-break]:after {
    white-space: pre; }
  [aria-label][data-balloon-pos][data-balloon-break][data-balloon-length]:after {
    white-space: pre-line;
    word-break: break-word; }
  [aria-label][data-balloon-pos][data-balloon-blunt]:before, [aria-label][data-balloon-pos][data-balloon-blunt]:after {
    transition: none; }
  [aria-label][data-balloon-pos][data-balloon-pos="up"]:hover:after, [aria-label][data-balloon-pos][data-balloon-pos="up"][data-balloon-visible]:after, [aria-label][data-balloon-pos][data-balloon-pos="down"]:hover:after, [aria-label][data-balloon-pos][data-balloon-pos="down"][data-balloon-visible]:after {
    transform: translate(-50%, 0); }
  [aria-label][data-balloon-pos][data-balloon-pos="up"]:hover:before, [aria-label][data-balloon-pos][data-balloon-pos="up"][data-balloon-visible]:before, [aria-label][data-balloon-pos][data-balloon-pos="down"]:hover:before, [aria-label][data-balloon-pos][data-balloon-pos="down"][data-balloon-visible]:before {
    transform: translate(-50%, 0); }
  [aria-label][data-balloon-pos][data-balloon-pos*="-left"]:after {
    left: 0; }
  [aria-label][data-balloon-pos][data-balloon-pos*="-left"]:before {
    left: 5px; }
  [aria-label][data-balloon-pos][data-balloon-pos*="-right"]:after {
    right: 0; }
  [aria-label][data-balloon-pos][data-balloon-pos*="-right"]:before {
    right: 5px; }
  [aria-label][data-balloon-pos][data-balloon-po*="-left"]:hover:after, [aria-label][data-balloon-pos][data-balloon-po*="-left"][data-balloon-visible]:after, [aria-label][data-balloon-pos][data-balloon-pos*="-right"]:hover:after, [aria-label][data-balloon-pos][data-balloon-pos*="-right"][data-balloon-visible]:after {
    transform: translate(0, 0); }
  [aria-label][data-balloon-pos][data-balloon-po*="-left"]:hover:before, [aria-label][data-balloon-pos][data-balloon-po*="-left"][data-balloon-visible]:before, [aria-label][data-balloon-pos][data-balloon-pos*="-right"]:hover:before, [aria-label][data-balloon-pos][data-balloon-pos*="-right"][data-balloon-visible]:before {
    transform: translate(0, 0); }
  [aria-label][data-balloon-pos][data-balloon-pos^="up"]:before, [aria-label][data-balloon-pos][data-balloon-pos^="up"]:after {
    bottom: 100%;
    transform-origin: top;
    transform: translate(0, var(--balloon-move)); }
  [aria-label][data-balloon-pos][data-balloon-pos^="up"]:after {
    margin-bottom: 10px; }
  [aria-label][data-balloon-pos][data-balloon-pos="up"]:before, [aria-label][data-balloon-pos][data-balloon-pos="up"]:after {
    left: 50%;
    transform: translate(-50%, var(--balloon-move)); }
  [aria-label][data-balloon-pos][data-balloon-pos^="down"]:before, [aria-label][data-balloon-pos][data-balloon-pos^="down"]:after {
    top: 100%;
    transform: translate(0, calc(var(--balloon-move) * -1)); }
  [aria-label][data-balloon-pos][data-balloon-pos^="down"]:after {
    margin-top: 10px; }
  [aria-label][data-balloon-pos][data-balloon-pos^="down"]:before {
    width: 0;
    height: 0;
    border: 5px solid transparent;
    border-bottom-color: var(--balloon-color); }
  [aria-label][data-balloon-pos][data-balloon-pos="down"]:after, [aria-label][data-balloon-pos][data-balloon-pos="down"]:before {
    left: 50%;
    transform: translate(-50%, calc(var(--balloon-move) * -1)); }
  [aria-label][data-balloon-pos][data-balloon-pos="left"]:hover:after, [aria-label][data-balloon-pos][data-balloon-pos="left"][data-balloon-visible]:after, [aria-label][data-balloon-pos][data-balloon-pos="right"]:hover:after, [aria-label][data-balloon-pos][data-balloon-pos="right"][data-balloon-visible]:after {
    transform: translate(0, -50%); }
  [aria-label][data-balloon-pos][data-balloon-pos="left"]:hover:before, [aria-label][data-balloon-pos][data-balloon-pos="left"][data-balloon-visible]:before, [aria-label][data-balloon-pos][data-balloon-pos="right"]:hover:before, [aria-label][data-balloon-pos][data-balloon-pos="right"][data-balloon-visible]:before {
    transform: translate(0, -50%); }
  [aria-label][data-balloon-pos][data-balloon-pos="left"]:after, [aria-label][data-balloon-pos][data-balloon-pos="left"]:before {
    right: 100%;
    top: 50%;
    transform: translate(var(--balloon-move), -50%); }
  [aria-label][data-balloon-pos][data-balloon-pos="left"]:after {
    margin-right: 10px; }
  [aria-label][data-balloon-pos][data-balloon-pos="left"]:before {
    width: 0;
    height: 0;
    border: 5px solid transparent;
    border-left-color: var(--balloon-color); }
  [aria-label][data-balloon-pos][data-balloon-pos="right"]:after, [aria-label][data-balloon-pos][data-balloon-pos="right"]:before {
    left: 100%;
    top: 50%;
    transform: translate(calc(var(--balloon-move) * -1), -50%); }
  [aria-label][data-balloon-pos][data-balloon-pos="right"]:after {
    margin-left: 10px; }
  [aria-label][data-balloon-pos][data-balloon-pos="right"]:before {
    width: 0;
    height: 0;
    border: 5px solid transparent;
    border-right-color: var(--balloon-color); }
  [aria-label][data-balloon-pos][data-balloon-length]:after {
    white-space: normal; }
  [aria-label][data-balloon-pos][data-balloon-length="small"]:after {
    width: 80px; }
  [aria-label][data-balloon-pos][data-balloon-length="medium"]:after {
    width: 150px; }
  [aria-label][data-balloon-pos][data-balloon-length="large"]:after {
    width: 260px; }
  [aria-label][data-balloon-pos][data-balloon-length="xlarge"]:after {
    width: 380px; }
    @media screen and (max-width: 768px) {
      [aria-label][data-balloon-pos][data-balloon-length="xlarge"]:after {
        width: 90vw; } }
  [aria-label][data-balloon-pos][data-balloon-length="fit"]:after {
    width: 100%; }
`],
            sourceRoot: ""
          }]);
          const l = i;
        },
        685: (n2, e2, t3) => {
          "use strict";
          t3.d(e2, {
            Z: () => u
          });
          var a2 = t3(415), o = t3.n(a2), r2 = t3(352), i = t3.n(r2), l = t3(49), s = t3(80), p = t3.n(s), d2 = new URL(t3(831), t3.b), c = i()(o());
          c.i(l.Z);
          var A = p()(d2);
          c.push([n2.id, '@keyframes my-face {\n  2% {\n    transform: translate(0, 1.5px) rotate(1.5deg);\n  }\n  4% {\n    transform: translate(0, -1.5px) rotate(-0.5deg);\n  }\n  6% {\n    transform: translate(0, 1.5px) rotate(-1.5deg);\n  }\n  8% {\n    transform: translate(0, -1.5px) rotate(-1.5deg);\n  }\n  10% {\n    transform: translate(0, 2.5px) rotate(1.5deg);\n  }\n  12% {\n    transform: translate(0, -0.5px) rotate(1.5deg);\n  }\n  14% {\n    transform: translate(0, -1.5px) rotate(1.5deg);\n  }\n  16% {\n    transform: translate(0, -0.5px) rotate(-1.5deg);\n  }\n  18% {\n    transform: translate(0, 0.5px) rotate(-1.5deg);\n  }\n  20% {\n    transform: translate(0, -1.5px) rotate(2.5deg);\n  }\n  22% {\n    transform: translate(0, 0.5px) rotate(-1.5deg);\n  }\n  24% {\n    transform: translate(0, 1.5px) rotate(1.5deg);\n  }\n  26% {\n    transform: translate(0, 0.5px) rotate(0.5deg);\n  }\n  28% {\n    transform: translate(0, 0.5px) rotate(1.5deg);\n  }\n  30% {\n    transform: translate(0, -0.5px) rotate(2.5deg);\n  }\n  32% {\n    transform: translate(0, 1.5px) rotate(-0.5deg);\n  }\n  34% {\n    transform: translate(0, 1.5px) rotate(-0.5deg);\n  }\n  36% {\n    transform: translate(0, -1.5px) rotate(2.5deg);\n  }\n  38% {\n    transform: translate(0, 1.5px) rotate(-1.5deg);\n  }\n  40% {\n    transform: translate(0, -0.5px) rotate(2.5deg);\n  }\n  42% {\n    transform: translate(0, 2.5px) rotate(-1.5deg);\n  }\n  44% {\n    transform: translate(0, 1.5px) rotate(0.5deg);\n  }\n  46% {\n    transform: translate(0, -1.5px) rotate(2.5deg);\n  }\n  48% {\n    transform: translate(0, -0.5px) rotate(0.5deg);\n  }\n  50% {\n    transform: translate(0, 0.5px) rotate(0.5deg);\n  }\n  52% {\n    transform: translate(0, 2.5px) rotate(2.5deg);\n  }\n  54% {\n    transform: translate(0, -1.5px) rotate(1.5deg);\n  }\n  56% {\n    transform: translate(0, 2.5px) rotate(2.5deg);\n  }\n  58% {\n    transform: translate(0, 0.5px) rotate(2.5deg);\n  }\n  60% {\n    transform: translate(0, 2.5px) rotate(2.5deg);\n  }\n  62% {\n    transform: translate(0, -0.5px) rotate(2.5deg);\n  }\n  64% {\n    transform: translate(0, -0.5px) rotate(1.5deg);\n  }\n  66% {\n    transform: translate(0, 1.5px) rotate(-0.5deg);\n  }\n  68% {\n    transform: translate(0, -1.5px) rotate(-0.5deg);\n  }\n  70% {\n    transform: translate(0, 1.5px) rotate(0.5deg);\n  }\n  72% {\n    transform: translate(0, 2.5px) rotate(1.5deg);\n  }\n  74% {\n    transform: translate(0, -0.5px) rotate(0.5deg);\n  }\n  76% {\n    transform: translate(0, -0.5px) rotate(2.5deg);\n  }\n  78% {\n    transform: translate(0, -0.5px) rotate(1.5deg);\n  }\n  80% {\n    transform: translate(0, 1.5px) rotate(1.5deg);\n  }\n  82% {\n    transform: translate(0, -0.5px) rotate(0.5deg);\n  }\n  84% {\n    transform: translate(0, 1.5px) rotate(2.5deg);\n  }\n  86% {\n    transform: translate(0, -1.5px) rotate(-1.5deg);\n  }\n  88% {\n    transform: translate(0, -0.5px) rotate(2.5deg);\n  }\n  90% {\n    transform: translate(0, 2.5px) rotate(-0.5deg);\n  }\n  92% {\n    transform: translate(0, 0.5px) rotate(-0.5deg);\n  }\n  94% {\n    transform: translate(0, 2.5px) rotate(0.5deg);\n  }\n  96% {\n    transform: translate(0, -0.5px) rotate(1.5deg);\n  }\n  98% {\n    transform: translate(0, -1.5px) rotate(-0.5deg);\n  }\n  0%,\n  100% {\n    transform: translate(0, 0) rotate(0deg);\n  }\n}\n.dplayer {\n  position: relative;\n  overflow: hidden;\n  -webkit-user-select: none;\n     -moz-user-select: none;\n          user-select: none;\n  line-height: 1;\n}\n.dplayer * {\n  box-sizing: content-box;\n}\n.dplayer svg {\n  width: 100%;\n  height: 100%;\n}\n.dplayer svg path,\n.dplayer svg circle {\n  fill: #fff;\n}\n.dplayer:-webkit-full-screen {\n  width: 100%;\n  height: 100%;\n  background: #000;\n  position: fixed;\n  z-index: 100000;\n  left: 0;\n  top: 0;\n  margin: 0;\n  padding: 0;\n  transform: translate(0, 0);\n}\n.dplayer.dplayer-no-danmaku .dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box .dplayer-setting-showdan,\n.dplayer.dplayer-no-danmaku .dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box .dplayer-setting-danmaku,\n.dplayer.dplayer-no-danmaku .dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box .dplayer-setting-danunlimit {\n  display: none;\n}\n.dplayer.dplayer-no-danmaku .dplayer-controller .dplayer-icons .dplayer-comment {\n  display: none;\n}\n.dplayer.dplayer-no-danmaku .dplayer-danmaku {\n  display: none;\n}\n.dplayer.dplayer-live .dplayer-time {\n  display: none;\n}\n.dplayer.dplayer-live .dplayer-bar-wrap {\n  display: none;\n}\n.dplayer.dplayer-live .dplayer-setting-speed {\n  display: none;\n}\n.dplayer.dplayer-live .dplayer-setting-loop {\n  display: none;\n}\n.dplayer.dplayer-live.dplayer-no-danmaku .dplayer-setting {\n  display: none;\n}\n.dplayer.dplayer-arrow .dplayer-danmaku {\n  font-size: 18px;\n}\n.dplayer.dplayer-arrow .dplayer-icon {\n  margin: 0 -3px;\n}\n.dplayer.dplayer-playing .dplayer-danmaku .dplayer-danmaku-move {\n  animation-play-state: running;\n}\n@media (min-width: 900px) {\n  .dplayer.dplayer-playing .dplayer-controller-mask {\n    opacity: 0;\n  }\n  .dplayer.dplayer-playing .dplayer-controller {\n    opacity: 0;\n  }\n  .dplayer.dplayer-playing:hover .dplayer-controller-mask {\n    opacity: 1;\n  }\n  .dplayer.dplayer-playing:hover .dplayer-controller {\n    opacity: 1;\n  }\n}\n.dplayer.dplayer-loading .dplayer-bezel .diplayer-loading-icon {\n  display: block;\n}\n.dplayer.dplayer-loading .dplayer-danmaku,\n.dplayer.dplayer-paused .dplayer-danmaku,\n.dplayer.dplayer-loading .dplayer-danmaku-move,\n.dplayer.dplayer-paused .dplayer-danmaku-move {\n  animation-play-state: paused;\n}\n.dplayer.dplayer-hide-controller {\n  cursor: none;\n}\n.dplayer.dplayer-hide-controller .dplayer-controller-mask {\n  opacity: 0;\n  transform: translateY(100%);\n}\n.dplayer.dplayer-hide-controller .dplayer-controller {\n  opacity: 0;\n  transform: translateY(100%);\n}\n.dplayer.dplayer-show-controller .dplayer-controller-mask {\n  opacity: 1;\n}\n.dplayer.dplayer-show-controller .dplayer-controller {\n  opacity: 1;\n}\n.dplayer.dplayer-fulled {\n  width: 100% !important;\n  height: 100% !important;\n}\n.dplayer.dplayer-fulled {\n  position: fixed;\n  z-index: 100000;\n  left: 0;\n  top: 0;\n}\n.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-volume,\n.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-camera-icon,\n.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-airplay-icon,\n.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-chromecast-icon,\n.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-play-icon {\n  display: none;\n}\n.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-full .dplayer-full-in-icon {\n  position: static;\n  display: inline-block;\n}\n.dplayer.dplayer-mobile .dplayer-bar-time {\n  display: none;\n}\n.dplayer.dplayer-mobile.dplayer-hide-controller .dplayer-mobile-play {\n  display: none;\n}\n.dplayer.dplayer-mobile .dplayer-mobile-play {\n  display: block;\n}\n.dplayer-web-fullscreen-fix {\n  position: fixed;\n  top: 0;\n  left: 0;\n  margin: 0;\n  padding: 0;\n}\n[data-balloon]:before {\n  display: none;\n}\n[data-balloon]:after {\n  padding: 0.3em 0.7em;\n  background: rgba(17, 17, 17, 0.7);\n}\n[data-balloon][data-balloon-pos="up"]:after {\n  margin-bottom: 0;\n}\n.dplayer-bezel {\n  position: absolute;\n  left: 0;\n  right: 0;\n  top: 0;\n  bottom: 0;\n  font-size: 22px;\n  color: #fff;\n  pointer-events: none;\n}\n.dplayer-bezel .dplayer-bezel-icon {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  margin: -26px 0 0 -26px;\n  height: 52px;\n  width: 52px;\n  padding: 12px;\n  box-sizing: border-box;\n  background: rgba(0, 0, 0, 0.5);\n  border-radius: 50%;\n  opacity: 0;\n  pointer-events: none;\n}\n.dplayer-bezel .dplayer-bezel-icon.dplayer-bezel-transition {\n  animation: bezel-hide 0.5s linear;\n}\n@keyframes bezel-hide {\n  from {\n    opacity: 1;\n    transform: scale(1);\n  }\n  to {\n    opacity: 0;\n    transform: scale(2);\n  }\n}\n.dplayer-bezel .dplayer-danloading {\n  position: absolute;\n  top: 50%;\n  margin-top: -7px;\n  width: 100%;\n  text-align: center;\n  font-size: 14px;\n  line-height: 14px;\n  animation: my-face 5s infinite ease-in-out;\n}\n.dplayer-bezel .diplayer-loading-icon {\n  display: none;\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  margin: -18px 0 0 -18px;\n  height: 36px;\n  width: 36px;\n  pointer-events: none;\n}\n.dplayer-bezel .diplayer-loading-icon .diplayer-loading-hide {\n  display: none;\n}\n.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot {\n  animation: diplayer-loading-dot-fade 0.8s ease infinite;\n  opacity: 0;\n  transform-origin: 4px 4px;\n}\n.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-1 {\n  animation-delay: 0.1s;\n}\n.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-2 {\n  animation-delay: 0.2s;\n}\n.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-3 {\n  animation-delay: 0.3s;\n}\n.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-4 {\n  animation-delay: 0.4s;\n}\n.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-5 {\n  animation-delay: 0.5s;\n}\n.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-6 {\n  animation-delay: 0.6s;\n}\n.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-7 {\n  animation-delay: 0.7s;\n}\n@keyframes diplayer-loading-dot-fade {\n  0% {\n    opacity: 0.7;\n    transform: scale(1.2, 1.2);\n  }\n  50% {\n    opacity: 0.25;\n    transform: scale(0.9, 0.9);\n  }\n  to {\n    opacity: 0.25;\n    transform: scale(0.85, 0.85);\n  }\n}\n.dplayer-controller-mask {\n  background: url(' + A + `) repeat-x bottom;
  height: 98px;
  width: 100%;
  position: absolute;
  bottom: 0;
  transition: all 0.3s ease;
}
.dplayer-controller {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 41px;
  padding: 0 20px;
  -webkit-user-select: none;
     -moz-user-select: none;
          user-select: none;
  transition: all 0.3s ease;
}
.dplayer-controller.dplayer-controller-comment .dplayer-icons {
  display: none;
}
.dplayer-controller.dplayer-controller-comment .dplayer-icons.dplayer-comment-box {
  display: block;
}
.dplayer-controller .dplayer-bar-wrap {
  padding: 5px 0;
  cursor: pointer;
  position: absolute;
  bottom: 33px;
  width: calc(100% - 40px);
  height: 3px;
}
.dplayer-controller .dplayer-bar-wrap:hover .dplayer-bar .dplayer-played .dplayer-thumb {
  transform: scale(1);
}
.dplayer-controller .dplayer-bar-wrap:hover .dplayer-highlight {
  display: block;
  width: 8px;
  transform: translateX(-4px);
  top: 4px;
  height: 40%;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-highlight {
  z-index: 12;
  position: absolute;
  top: 5px;
  width: 6px;
  height: 20%;
  border-radius: 6px;
  background-color: #fff;
  text-align: center;
  transform: translateX(-3px);
  transition: all 0.2s ease-in-out;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-highlight:hover .dplayer-highlight-text {
  display: block;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-highlight:hover ~ .dplayer-bar-preview {
  opacity: 0;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-highlight:hover ~ .dplayer-bar-time {
  opacity: 0;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-highlight .dplayer-highlight-text {
  display: none;
  position: absolute;
  left: 50%;
  top: -24px;
  padding: 5px 8px;
  background-color: rgba(0, 0, 0, 0.62);
  color: #fff;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  transform: translateX(-50%);
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar-preview {
  position: absolute;
  background: #fff;
  pointer-events: none;
  display: none;
  background-size: 16000px 100%;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar-preview-canvas {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 1;
  pointer-events: none;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar-time {
  position: absolute;
  left: 0px;
  top: -20px;
  border-radius: 4px;
  padding: 5px 7px;
  background-color: rgba(0, 0, 0, 0.62);
  color: #fff;
  font-size: 12px;
  text-align: center;
  opacity: 1;
  transition: opacity 0.1s ease-in-out;
  word-wrap: normal;
  word-break: normal;
  z-index: 2;
  pointer-events: none;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar-time.hidden {
  opacity: 0;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar {
  position: relative;
  height: 3px;
  width: 100%;
  background: rgba(255, 255, 255, 0.2);
  cursor: pointer;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar .dplayer-loaded {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.4);
  height: 3px;
  transition: all 0.5s ease;
  will-change: width;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar .dplayer-played {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  height: 3px;
  will-change: width;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar .dplayer-played .dplayer-thumb {
  position: absolute;
  top: 0;
  right: 5px;
  margin-top: -4px;
  margin-right: -10px;
  height: 11px;
  width: 11px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  transform: scale(0);
}
.dplayer-controller .dplayer-icons {
  height: 38px;
  position: absolute;
  bottom: 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box {
  display: none;
  position: absolute;
  transition: all 0.3s ease-in-out;
  z-index: 2;
  height: 38px;
  bottom: 0;
  left: 20px;
  right: 20px;
  color: #fff;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-icon {
  padding: 7px;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-icon {
  position: absolute;
  left: 0;
  top: 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-send-icon {
  position: absolute;
  right: 0;
  top: 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box {
  position: absolute;
  background: rgba(28, 28, 28, 0.9);
  bottom: 41px;
  left: 0;
  box-shadow: 0 0 25px rgba(0, 0, 0, 0.3);
  border-radius: 4px;
  padding: 10px 10px 16px;
  font-size: 14px;
  width: 204px;
  transition: all 0.3s ease-in-out;
  transform: scale(0);
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box.dplayer-comment-setting-open {
  transform: scale(1);
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box input[type=radio] {
  display: none;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box label {
  cursor: pointer;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-title {
  font-size: 13px;
  color: #fff;
  line-height: 30px;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type {
  font-size: 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type .dplayer-comment-setting-title {
  margin-bottom: 6px;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type label:nth-child(2) span {
  border-radius: 4px 0 0 4px;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type label:nth-child(4) span {
  border-radius: 0 4px 4px 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type span {
  width: 33%;
  padding: 4px 6px;
  line-height: 16px;
  display: inline-block;
  font-size: 12px;
  color: #fff;
  border: 1px solid #fff;
  margin-right: -1px;
  box-sizing: border-box;
  text-align: center;
  cursor: pointer;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type input:checked + span {
  background: #E4E4E6;
  color: #1c1c1c;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-color {
  font-size: 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-color label {
  font-size: 0;
  padding: 6px;
  display: inline-block;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-color span {
  width: 22px;
  height: 22px;
  display: inline-block;
  border-radius: 50%;
  box-sizing: border-box;
  cursor: pointer;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-color span:hover {
  animation: my-face 5s infinite ease-in-out;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-input {
  outline: none;
  border: none;
  padding: 8px 31px;
  font-size: 14px;
  line-height: 18px;
  text-align: center;
  border-radius: 4px;
  background: none;
  margin: 0;
  height: 100%;
  box-sizing: border-box;
  width: 100%;
  color: #fff;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-input::-moz-placeholder {
  color: #fff;
  opacity: 0.8;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-input::placeholder {
  color: #fff;
  opacity: 0.8;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-input::-ms-clear {
  display: none;
}
.dplayer-controller .dplayer-icons.dplayer-icons-left .dplayer-icon {
  padding: 7px;
}
.dplayer-controller .dplayer-icons.dplayer-icons-right {
  right: 20px;
}
.dplayer-controller .dplayer-icons.dplayer-icons-right .dplayer-icon {
  padding: 8px;
}
.dplayer-controller .dplayer-icons .dplayer-time,
.dplayer-controller .dplayer-icons .dplayer-live-badge {
  line-height: 38px;
  color: #eee;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
  vertical-align: middle;
  font-size: 13px;
  cursor: default;
}
.dplayer-controller .dplayer-icons .dplayer-live-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  vertical-align: 4%;
  margin-right: 5px;
  content: '';
  border-radius: 6px;
}
.dplayer-controller .dplayer-icons .dplayer-icon {
  width: 40px;
  height: 100%;
  border: none;
  background-color: transparent;
  outline: none;
  cursor: pointer;
  vertical-align: middle;
  box-sizing: border-box;
  display: inline-block;
}
.dplayer-controller .dplayer-icons .dplayer-icon .dplayer-icon-content {
  transition: all 0.2s ease-in-out;
  opacity: 0.8;
}
.dplayer-controller .dplayer-icons .dplayer-icon:hover .dplayer-icon-content {
  opacity: 1;
}
.dplayer-controller .dplayer-icons .dplayer-icon.dplayer-quality-icon {
  color: #fff;
  width: auto;
  line-height: 22px;
  font-size: 14px;
}
.dplayer-controller .dplayer-icons .dplayer-icon.dplayer-comment-icon {
  padding: 10px 9px 9px;
}
.dplayer-controller .dplayer-icons .dplayer-icon.dplayer-setting-icon {
  padding-top: 8.5px;
}
.dplayer-controller .dplayer-icons .dplayer-icon.dplayer-volume-icon {
  width: 43px;
}
.dplayer-controller .dplayer-icons .dplayer-volume {
  position: relative;
  display: inline-block;
  cursor: pointer;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-volume:hover .dplayer-volume-bar-wrap .dplayer-volume-bar {
  width: 45px;
}
.dplayer-controller .dplayer-icons .dplayer-volume:hover .dplayer-volume-bar-wrap .dplayer-volume-bar .dplayer-volume-bar-inner .dplayer-thumb {
  transform: scale(1);
}
.dplayer-controller .dplayer-icons .dplayer-volume.dplayer-volume-active .dplayer-volume-bar-wrap .dplayer-volume-bar {
  width: 45px;
}
.dplayer-controller .dplayer-icons .dplayer-volume.dplayer-volume-active .dplayer-volume-bar-wrap .dplayer-volume-bar .dplayer-volume-bar-inner .dplayer-thumb {
  transform: scale(1);
}
.dplayer-controller .dplayer-icons .dplayer-volume .dplayer-volume-bar-wrap {
  display: inline-block;
  margin: 0 10px 0 -5px;
  vertical-align: middle;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-volume .dplayer-volume-bar-wrap .dplayer-volume-bar {
  position: relative;
  top: 17px;
  width: 0;
  height: 3px;
  background: #aaa;
  transition: all 0.3s ease-in-out;
}
.dplayer-controller .dplayer-icons .dplayer-volume .dplayer-volume-bar-wrap .dplayer-volume-bar .dplayer-volume-bar-inner {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 100%;
  transition: all 0.1s ease;
  will-change: width;
}
.dplayer-controller .dplayer-icons .dplayer-volume .dplayer-volume-bar-wrap .dplayer-volume-bar .dplayer-volume-bar-inner .dplayer-thumb {
  position: absolute;
  top: 0;
  right: 5px;
  margin-top: -4px;
  margin-right: -10px;
  height: 11px;
  width: 11px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  transform: scale(0);
}
.dplayer-controller .dplayer-icons .dplayer-subtitle-btn {
  display: inline-block;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-subtitles {
  display: inline-block;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-subtitles .dplayer-subtitles-box {
  position: absolute;
  right: 0;
  bottom: 50px;
  transform: scale(0);
  width: -moz-fit-content;
  width: fit-content;
  max-width: 240px;
  min-width: 120px;
  border-radius: 2px;
  background: rgba(28, 28, 28, 0.9);
  padding: 7px 0;
  transition: all 0.3s ease-in-out;
  overflow: auto;
  z-index: 2;
}
.dplayer-controller .dplayer-icons .dplayer-subtitles .dplayer-subtitles-box.dplayer-subtitles-panel {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-subtitles .dplayer-subtitles-box.dplayer-subtitles-box-open {
  transform: scale(1);
}
.dplayer-controller .dplayer-icons .dplayer-subtitles .dplayer-subtitles-item {
  height: 30px;
  padding: 5px 10px;
  box-sizing: border-box;
  cursor: pointer;
  position: relative;
}
.dplayer-controller .dplayer-icons .dplayer-subtitles .dplayer-subtitles-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.dplayer-controller .dplayer-icons .dplayer-setting {
  display: inline-block;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box {
  position: absolute;
  right: 0;
  bottom: 50px;
  transform: scale(0);
  width: 150px;
  border-radius: 2px;
  background: rgba(28, 28, 28, 0.9);
  padding: 7px 0;
  transition: all 0.3s ease-in-out;
  overflow: hidden;
  z-index: 2;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box > div {
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box > div.dplayer-setting-origin-panel {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box.dplayer-setting-box-open {
  transform: scale(1);
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box.dplayer-setting-box-narrow {
  width: 70px;
  text-align: center;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box.dplayer-setting-box-speed .dplayer-setting-origin-panel {
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box.dplayer-setting-box-speed .dplayer-setting-speed-panel {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-item,
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-speed-item {
  height: 30px;
  padding: 5px 10px;
  box-sizing: border-box;
  cursor: pointer;
  position: relative;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-item:hover,
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-speed-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku {
  padding: 5px 0;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku .dplayer-label {
  padding: 0 10px;
  display: inline;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku:hover .dplayer-label {
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku:hover .dplayer-danmaku-bar-wrap {
  display: inline-block;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku.dplayer-setting-danmaku-active .dplayer-label {
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku.dplayer-setting-danmaku-active .dplayer-danmaku-bar-wrap {
  display: inline-block;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku .dplayer-danmaku-bar-wrap {
  padding: 0 10px;
  box-sizing: border-box;
  display: none;
  vertical-align: middle;
  height: 100%;
  width: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku .dplayer-danmaku-bar-wrap .dplayer-danmaku-bar {
  position: relative;
  top: 8.5px;
  width: 100%;
  height: 3px;
  background: #fff;
  transition: all 0.3s ease-in-out;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku .dplayer-danmaku-bar-wrap .dplayer-danmaku-bar .dplayer-danmaku-bar-inner {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 100%;
  transition: all 0.1s ease;
  background: #aaa;
  will-change: width;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku .dplayer-danmaku-bar-wrap .dplayer-danmaku-bar .dplayer-danmaku-bar-inner .dplayer-thumb {
  position: absolute;
  top: 0;
  right: 5px;
  margin-top: -4px;
  margin-right: -10px;
  height: 11px;
  width: 11px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  background: #aaa;
}
.dplayer-controller .dplayer-icons .dplayer-full {
  display: inline-block;
  height: 100%;
  position: relative;
}
.dplayer-controller .dplayer-icons .dplayer-full:hover .dplayer-full-in-icon {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-full .dplayer-full-in-icon {
  position: absolute;
  top: -30px;
  z-index: 1;
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-quality {
  position: relative;
  display: inline-block;
  height: 100%;
  z-index: 2;
}
.dplayer-controller .dplayer-icons .dplayer-quality:hover .dplayer-quality-list {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-quality:hover .dplayer-quality-mask {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-quality .dplayer-quality-mask {
  display: none;
  position: absolute;
  bottom: 38px;
  left: -18px;
  width: 80px;
  padding-bottom: 12px;
}
.dplayer-controller .dplayer-icons .dplayer-quality .dplayer-quality-list {
  display: none;
  font-size: 12px;
  width: 80px;
  border-radius: 2px;
  background: rgba(28, 28, 28, 0.9);
  padding: 5px 0;
  transition: all 0.3s ease-in-out;
  overflow: hidden;
  color: #fff;
  text-align: center;
}
.dplayer-controller .dplayer-icons .dplayer-quality .dplayer-quality-item {
  height: 25px;
  box-sizing: border-box;
  cursor: pointer;
  line-height: 25px;
}
.dplayer-controller .dplayer-icons .dplayer-quality .dplayer-quality-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.dplayer-controller .dplayer-icons .dplayer-comment {
  display: inline-block;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-label {
  color: #eee;
  font-size: 13px;
  display: inline-block;
  vertical-align: middle;
  white-space: nowrap;
}
.dplayer-controller .dplayer-icons .dplayer-toggle {
  width: 32px;
  height: 20px;
  text-align: center;
  font-size: 0;
  vertical-align: middle;
  position: absolute;
  top: 5px;
  right: 10px;
}
.dplayer-controller .dplayer-icons .dplayer-toggle input {
  max-height: 0;
  max-width: 0;
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-toggle input + label {
  display: inline-block;
  position: relative;
  box-shadow: #dfdfdf 0 0 0 0 inset;
  border: 1px solid #dfdfdf;
  height: 20px;
  width: 32px;
  border-radius: 10px;
  box-sizing: border-box;
  cursor: pointer;
  transition: 0.2s ease-in-out;
}
.dplayer-controller .dplayer-icons .dplayer-toggle input + label:before {
  content: "";
  position: absolute;
  display: block;
  height: 18px;
  width: 18px;
  top: 0;
  left: 0;
  border-radius: 15px;
  transition: 0.2s ease-in-out;
}
.dplayer-controller .dplayer-icons .dplayer-toggle input + label:after {
  content: "";
  position: absolute;
  display: block;
  left: 0;
  top: 0;
  border-radius: 15px;
  background: #fff;
  transition: 0.2s ease-in-out;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
  height: 18px;
  width: 18px;
}
.dplayer-controller .dplayer-icons .dplayer-toggle input:checked + label {
  border-color: rgba(255, 255, 255, 0.5);
}
.dplayer-controller .dplayer-icons .dplayer-toggle input:checked + label:before {
  width: 30px;
  background: rgba(255, 255, 255, 0.5);
}
.dplayer-controller .dplayer-icons .dplayer-toggle input:checked + label:after {
  left: 12px;
}
.dplayer-mobile-play {
  display: none;
  width: 50px;
  height: 50px;
  border: none;
  background-color: transparent;
  outline: none;
  cursor: pointer;
  box-sizing: border-box;
  bottom: 0;
  opacity: 0.8;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.dplayer-danmaku {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  font-size: 22px;
  color: #fff;
}
.dplayer-danmaku .dplayer-danmaku-item {
  display: inline-block;
  pointer-events: none;
  -webkit-user-select: none;
     -moz-user-select: none;
          user-select: none;
  cursor: default;
  white-space: nowrap;
  text-shadow: 0.5px 0.5px 0.5px rgba(0, 0, 0, 0.5);
}
.dplayer-danmaku .dplayer-danmaku-item--demo {
  position: absolute;
  visibility: hidden;
}
.dplayer-danmaku .dplayer-danmaku-right {
  position: absolute;
  right: 0;
  transform: translateX(100%);
}
.dplayer-danmaku .dplayer-danmaku-right.dplayer-danmaku-move {
  will-change: transform;
  animation-name: 'danmaku';
  animation-timing-function: linear;
  animation-play-state: paused;
}
@keyframes danmaku {
  from {
    transform: translateX(100%);
  }
}
.dplayer-danmaku .dplayer-danmaku-top,
.dplayer-danmaku .dplayer-danmaku-bottom {
  position: absolute;
  width: 100%;
  text-align: center;
  visibility: hidden;
}
.dplayer-danmaku .dplayer-danmaku-top.dplayer-danmaku-move,
.dplayer-danmaku .dplayer-danmaku-bottom.dplayer-danmaku-move {
  will-change: visibility;
  animation-name: 'danmaku-center';
  animation-timing-function: linear;
  animation-play-state: paused;
}
@keyframes danmaku-center {
  from {
    visibility: visible;
  }
  to {
    visibility: visible;
  }
}
.dplayer-logo {
  pointer-events: none;
  position: absolute;
  left: 20px;
  top: 20px;
  max-width: 50px;
  max-height: 50px;
}
.dplayer-logo img {
  max-width: 100%;
  max-height: 100%;
  background: none;
}
.dplayer-menu {
  position: absolute;
  width: 170px;
  border-radius: 2px;
  background: rgba(28, 28, 28, 0.85);
  padding: 5px 0;
  overflow: hidden;
  z-index: 3;
  display: none;
}
.dplayer-menu.dplayer-menu-show {
  display: block;
}
.dplayer-menu .dplayer-menu-item {
  height: 30px;
  box-sizing: border-box;
  cursor: pointer;
}
.dplayer-menu .dplayer-menu-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.dplayer-menu .dplayer-menu-item a {
  padding: 0 10px;
  line-height: 30px;
  color: #eee;
  font-size: 13px;
  display: inline-block;
  vertical-align: middle;
  width: 100%;
  box-sizing: border-box;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.dplayer-menu .dplayer-menu-item a:hover {
  text-decoration: none;
}
.dplayer-notice-list {
  position: absolute;
  bottom: 60px;
  left: 20px;
}
.dplayer-notice-list .dplayer-notice {
  border-radius: 2px;
  background: rgba(28, 28, 28, 0.9);
  transition: all 0.3s ease-in-out;
  overflow: hidden;
  color: #fff;
  display: table;
  pointer-events: none;
  animation: showNotice 0.3s ease 1 forwards;
}
.dplayer-notice-list .remove-notice {
  animation: removeNotice 0.3s ease 1 forwards;
}
@keyframes showNotice {
  from {
    padding: 0;
    font-size: 0;
    margin-top: 0;
  }
  to {
    padding: 7px 20px;
    font-size: 14px;
    margin-top: 5px;
  }
}
@keyframes removeNotice {
  0% {
    padding: 7px 20px;
    font-size: 14px;
    margin-top: 5px;
  }
  20% {
    font-size: 12px;
  }
  21% {
    font-size: 0;
    padding: 7px 10px;
  }
  100% {
    padding: 0;
    margin-top: 0;
    font-size: 0;
  }
}
.dplayer-subtitle {
  position: absolute;
  bottom: 40px;
  width: 90%;
  left: 5%;
  text-align: center;
  color: #fff;
  text-shadow: 0.5px 0.5px 0.5px rgba(0, 0, 0, 0.5);
  font-size: 20px;
}
.dplayer-subtitle.dplayer-subtitle-hide {
  display: none;
}
.dplayer-mask {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1;
  display: none;
}
.dplayer-mask.dplayer-mask-show {
  display: block;
}
.dplayer-video-wrap {
  position: relative;
  background: #000;
  font-size: 0;
  width: 100%;
  height: 100%;
}
.dplayer-video-wrap .dplayer-video {
  width: 100%;
  height: 100%;
  display: none;
}
.dplayer-video-wrap .dplayer-video-current {
  display: block;
}
.dplayer-video-wrap .dplayer-video-prepare {
  display: none;
}
.dplayer-info-panel {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 400px;
  background: rgba(28, 28, 28, 0.8);
  padding: 10px;
  color: #fff;
  font-size: 12px;
  border-radius: 2px;
}
.dplayer-info-panel-hide {
  display: none;
}
.dplayer-info-panel .dplayer-info-panel-close {
  cursor: pointer;
  position: absolute;
  right: 10px;
  top: 10px;
}
.dplayer-info-panel .dplayer-info-panel-item > span {
  display: inline-block;
  vertical-align: middle;
  line-height: 15px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.dplayer-info-panel .dplayer-info-panel-item-title {
  width: 100px;
  text-align: right;
  margin-right: 10px;
}
.dplayer-info-panel .dplayer-info-panel-item-data {
  width: 260px;
}
`, "", {
            version: 3,
            sources: ["webpack://./src/css/global.less", "webpack://./src/css/index.less", "webpack://./src/css/player.less", "webpack://./src/css/balloon.less", "webpack://./src/css/bezel.less", "webpack://./src/css/notice.less", "webpack://./src/css/controller.less", "webpack://./src/css/danmaku.less", "webpack://./src/css/logo.less", "webpack://./src/css/menu.less", "webpack://./src/css/subtitle.less", "webpack://./src/css/video.less", "webpack://./src/css/info-panel.less"],
            names: [],
            mappings: "AAAA;EACI;IACI,6CAAA;ECEN;EDAE;IACI,+CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,+CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,+CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,+CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,+CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,6CAAA;ECEN;EDAE;IACI,8CAAA;ECEN;EDAE;IACI,+CAAA;ECEN;EDAE;;IAEI,uCAAA;ECEN;AACF;ACzJA;EACI,kBAAA;EACA,gBAAA;EACA,yBAAA;KAAA,sBAAA;UAAA,iBAAA;EACA,cAAA;AD2JJ;AC/JA;EAOQ,uBAAA;AD2JR;AClKA;EAWQ,WAAA;EACA,YAAA;AD0JR;ACtKA;;EAgBY,UAAA;AD0JZ;ACtJI;EACI,WAAA;EACA,YAAA;EACA,gBAAA;EACA,eAAA;EACA,eAAA;EACA,OAAA;EACA,MAAA;EACA,SAAA;EACA,UAAA;EACA,0BAAA;ADwJR;ACpJI;;;EAKY,aAAA;ADoJhB;ACzJI;EAUQ,aAAA;ADkJZ;AC5JI;EAcQ,aAAA;ADiJZ;AC7II;EAEQ,aAAA;AD8IZ;AChJI;EAKQ,aAAA;AD8IZ;ACnJI;EAQQ,aAAA;AD8IZ;ACtJI;EAWQ,aAAA;AD8IZ;AC3IQ;EAEQ,aAAA;AD4IhB;ACvII;EAEQ,eAAA;ADwIZ;AC1II;EAKQ,cAAA;ADwIZ;ACpII;EAEQ,6BAAA;ADqIZ;AClIQ;EAAA;IAEQ,UAAA;EDoId;ECtIM;IAKQ,UAAA;EDoId;ECjIU;IAEQ,UAAA;EDkIlB;ECpIU;IAKQ,UAAA;EDkIlB;AACF;AC7HI;EAEQ,cAAA;AD8HZ;AC1HI;;;;EAIQ,4BAAA;AD4HZ;ACxHI;EACI,YAAA;AD0HR;AC3HI;EAIQ,UAAA;EACA,2BAAA;AD0HZ;AC/HI;EAQQ,UAAA;EACA,2BAAA;AD0HZ;ACvHI;EAEQ,UAAA;ADwHZ;AC1HI;EAKQ,UAAA;ADwHZ;ACrHI;EAKI,sBAAA;EACA,uBAAA;ADuHR;AC7HI;EACI,eAAA;EACA,eAAA;EACA,OAAA;EACA,MAAA;ADyHR;ACrHI;;;;;EAOY,aAAA;ADqHhB;AC5HI;EAUY,gBAAA;EACA,qBAAA;ADqHhB;AChII;EAgBQ,aAAA;ADmHZ;AChHQ;EAEQ,aAAA;ADiHhB;ACtII;EA0BQ,cAAA;AD+GZ;ACzGA;EACI,eAAA;EACA,MAAA;EACA,OAAA;EACA,SAAA;EACA,UAAA;AD2GJ;AElSA;EACI,aAAA;AFoSJ;AEjSA;EACI,oBAAA;EACA,iCAAA;AFmSJ;AEhSA;EACI,gBAAA;AFkSJ;AG9SA;EACI,kBAAA;EACA,OAAA;EACA,QAAA;EACA,MAAA;EACA,SAAA;EACA,eAAA;EACA,WAAA;EACA,oBAAA;AHgTJ;AGxTA;EAUQ,kBAAA;EACA,QAAA;EACA,SAAA;EACA,uBAAA;EACA,YAAA;EACA,WAAA;EACA,aAAA;EACA,sBAAA;EACA,8BAAA;EACA,kBAAA;EACA,UAAA;EACA,oBAAA;AHiTR;AGhTQ;EACI,iCAAA;AHkTZ;AGhTQ;EACI;IACI,UAAA;IACA,mBAAA;EHkTd;EGhTU;IACI,UAAA;IACA,mBAAA;EHkTd;AACF;AGnVA;EAqCQ,kBAAA;EACA,QAAA;EACA,gBAAA;EACA,WAAA;EACA,kBAAA;EACA,eAAA;EACA,iBAAA;EACA,0CAAA;AHiTR;AG7VA;EA+CQ,aAAA;EACA,kBAAA;EACA,QAAA;EACA,SAAA;EACA,uBAAA;EACA,YAAA;EACA,WAAA;EACA,oBAAA;AHiTR;AGvWA;EAwDY,aAAA;AHkTZ;AG1WA;EA2DY,uDAAA;EACA,UAAA;EACA,yBAAA;AHkTZ;AI/WC;EDgEmB,qBAAA;AHkTpB;AIlXC;EDgEmB,qBAAA;AHqTpB;AIrXC;EDgEmB,qBAAA;AHwTpB;AIxXC;EDgEmB,qBAAA;AH2TpB;AI3XC;EDgEmB,qBAAA;AH8TpB;AI9XC;EDgEmB,qBAAA;AHiUpB;AIjYC;EDgEmB,qBAAA;AHoUpB;AGhUQ;EACI;IACI,YAAA;IACA,0BAAA;EHkUd;EGhUU;IACI,aAAA;IACA,0BAAA;EHkUd;EGhUU;IACI,aAAA;IACA,4BAAA;EHkUd;AACF;AKlZA;EACI,mEAAA;EACA,YAAA;EACA,WAAA;EACA,kBAAA;EACA,SAAA;EACA,yBAAA;ALoZJ;AKjZA;EACI,kBAAA;EACA,SAAA;EACA,OAAA;EACA,QAAA;EACA,YAAA;EACA,eAAA;EACA,yBAAA;KAAA,sBAAA;UAAA,iBAAA;EACA,yBAAA;ALmZJ;AKlZI;EAEQ,aAAA;ALmZZ;AKrZI;EAKQ,cAAA;ALmZZ;AKjaA;EAkBQ,cAAA;EACA,eAAA;EACA,kBAAA;EACA,YAAA;EACA,wBAAA;EACA,WAAA;ALkZR;AKjZQ;EAEQ,mBAAA;ALkZhB;AKpZQ;EAKQ,cAAA;EACA,UAAA;EACA,2BAAA;EACA,QAAA;EACA,WAAA;ALkZhB;AKnbA;EAqCY,WAAA;EACA,kBAAA;EACA,QAAA;EACA,UAAA;EACA,WAAA;EACA,kBAAA;EACA,sBAAA;EACA,kBAAA;EACA,2BAAA;EACA,gCAAA;ALiZZ;AKhZY;EAEQ,cAAA;ALiZpB;AK/YgB;EACI,UAAA;ALiZpB;AK/YgB;EACI,UAAA;ALiZpB;AKxcA;EA2DgB,aAAA;EACA,kBAAA;EACA,SAAA;EACA,UAAA;EACA,gBAAA;EACA,qCAAA;EACA,WAAA;EACA,kBAAA;EACA,eAAA;EACA,mBAAA;EACA,2BAAA;ALgZhB;AKrdA;EAyEY,kBAAA;EACA,gBAAA;EACA,oBAAA;EACA,aAAA;EACA,6BAAA;AL+YZ;AK5dA;EAgFY,kBAAA;EACA,WAAA;EACA,YAAA;EACA,UAAA;EACA,oBAAA;AL+YZ;AKneA;EA0FY,kBAAA;EACA,SAAA;EACA,UAAA;EACA,kBAAA;EACA,gBAAA;EACA,qCAAA;EACA,WAAA;EACA,eAAA;EACA,kBAAA;EACA,UAAA;EACA,oCAAA;EACA,iBAAA;EACA,kBAAA;EACA,UAAA;EACA,oBAAA;AL4YZ;AK7ZY;EACI,UAAA;AL+ZhB;AKvfA;EA2GY,kBAAA;EACA,WAAA;EACA,WAAA;EACA,oCAAA;EACA,eAAA;AL+YZ;AK9fA;EAiHgB,kBAAA;EACA,OAAA;EACA,MAAA;EACA,SAAA;EACA,oCAAA;EACA,WAAA;EACA,yBAAA;EACA,kBAAA;ALgZhB;AKxgBA;EA2HgB,kBAAA;EACA,OAAA;EACA,MAAA;EACA,SAAA;EACA,WAAA;EACA,kBAAA;ALgZhB;AKhhBA;EAkIoB,kBAAA;EACA,MAAA;EACA,UAAA;EACA,gBAAA;EACA,mBAAA;EACA,YAAA;EACA,WAAA;EACA,kBAAA;EACA,eAAA;EACA,gCAAA;EACA,mBAAA;ALiZpB;AK7hBA;EAkJQ,YAAA;EACA,kBAAA;EACA,SAAA;AL8YR;AK7YQ;EACI,aAAA;EACA,kBAAA;EACA,gCAAA;EACA,UAAA;EACA,YAAA;EACA,SAAA;EACA,UAAA;EACA,WAAA;EACA,WAAA;AL+YZ;AKxZQ;EAWQ,YAAA;ALgZhB;AK3ZQ;EAcQ,kBAAA;EACA,OAAA;EACA,MAAA;ALgZhB;AKhaQ;EAmBQ,kBAAA;EACA,QAAA;EACA,MAAA;ALgZhB;AKraQ;EAwBQ,kBAAA;EACA,iCAAA;EACA,YAAA;EACA,OAAA;EACA,uCAAA;EACA,kBAAA;EACA,uBAAA;EACA,eAAA;EACA,YAAA;EACA,gCAAA;EACA,mBAAA;ALgZhB;AK/YgB;EACI,mBAAA;ALiZpB;AKrbQ;EAuCY,aAAA;ALiZpB;AKxbQ;EA0CY,eAAA;ALiZpB;AK3bQ;EA6CY,eAAA;EACA,WAAA;EACA,iBAAA;ALiZpB;AKhcQ;EAkDY,YAAA;ALiZpB;AKncQ;EAoDgB,kBAAA;ALkZxB;AK/YwB;EAEQ,0BAAA;ALgZhC;AK7YwB;EAEQ,0BAAA;AL8YhC;AK5cQ;EAmEgB,UAAA;EACA,gBAAA;EACA,iBAAA;EACA,qBAAA;EACA,eAAA;EACA,WAAA;EACA,sBAAA;EACA,kBAAA;EACA,sBAAA;EACA,kBAAA;EACA,eAAA;AL4YxB;AKzdQ;EAgFgB,mBAAA;EACA,cAAA;AL4YxB;AK7dQ;EAqFY,YAAA;AL2YpB;AKheQ;EAuFgB,YAAA;EACA,YAAA;EACA,qBAAA;AL4YxB;AKreQ;EA4FgB,WAAA;EACA,YAAA;EACA,qBAAA;EACA,kBAAA;EACA,sBAAA;EACA,eAAA;AL4YxB;AK3YwB;EACI,0CAAA;AL6Y5B;AKhfQ;EAyGQ,aAAA;EACA,YAAA;EACA,iBAAA;EACA,eAAA;EACA,iBAAA;EACA,kBAAA;EACA,kBAAA;EACA,gBAAA;EACA,SAAA;EACA,YAAA;EACA,sBAAA;EACA,WAAA;EACA,WAAA;AL0YhB;AKzYgB;EACI,WAAA;EACA,YAAA;AL2YpB;AK7YgB;EACI,WAAA;EACA,YAAA;AL2YpB;AKzYgB;EACI,aAAA;AL2YpB;AKvYQ;EAEQ,YAAA;ALwYhB;AKrYQ;EACI,WAAA;ALuYZ;AKxYQ;EAGQ,YAAA;ALwYhB;AKpqBA;;EAiSY,iBAAA;EACA,WAAA;EACA,uCAAA;EACA,sBAAA;EACA,eAAA;EACA,eAAA;ALuYZ;AK7qBA;EAySY,qBAAA;EACA,UAAA;EACA,WAAA;EACA,kBAAA;EACA,iBAAA;EACA,WAAA;EACA,kBAAA;ALuYZ;AKtrBA;EAkTY,WAAA;EACA,YAAA;EACA,YAAA;EACA,6BAAA;EACA,aAAA;EACA,eAAA;EACA,sBAAA;EACA,sBAAA;EACA,qBAAA;ALuYZ;AKjsBA;EA4TgB,gCAAA;EACA,YAAA;ALwYhB;AKtYY;EAEQ,UAAA;ALuYpB;AKpYY;EACI,WAAA;EACA,WAAA;EACA,iBAAA;EACA,eAAA;ALsYhB;AKpYY;EACI,qBAAA;ALsYhB;AKpYY;EACI,kBAAA;ALsYhB;AKpYY;EACI,WAAA;ALsYhB;AKvtBA;EAqVY,kBAAA;EACA,qBAAA;EACA,eAAA;EACA,YAAA;ALqYZ;AKpYY;EAEQ,WAAA;ALqYpB;AKvYY;EAKQ,mBAAA;ALqYpB;AKlYY;EAEQ,WAAA;ALmYpB;AKrYY;EAKQ,mBAAA;ALmYpB;AKzuBA;EA0WgB,qBAAA;EACA,qBAAA;EACA,sBAAA;EACA,YAAA;ALkYhB;AK/uBA;EA+WoB,kBAAA;EACA,SAAA;EACA,QAAA;EACA,WAAA;EACA,gBAAA;EACA,gCAAA;ALmYpB;AKvvBA;EAsXwB,kBAAA;EACA,SAAA;EACA,OAAA;EACA,YAAA;EACA,yBAAA;EACA,kBAAA;ALoYxB;AK/vBA;EA6X4B,kBAAA;EACA,MAAA;EACA,UAAA;EACA,gBAAA;EACA,mBAAA;EACA,YAAA;EACA,WAAA;EACA,kBAAA;EACA,eAAA;EACA,gCAAA;EACA,mBAAA;ALqY5B;AK5wBA;EA8YY,qBAAA;EACA,YAAA;ALiYZ;AKhxBA;EAkZY,qBAAA;EACA,YAAA;ALiYZ;AKpxBA;EAqZgB,kBAAA;EACA,QAAA;EACA,YAAA;EACA,mBAAA;EACA,uBAAA;EAAA,kBAAA;EACA,gBAAA;EACA,gBAAA;EACA,kBAAA;EACA,iCAAA;EACA,cAAA;EACA,gCAAA;EACA,cAAA;EACA,UAAA;ALkYhB;AKjYgB;EACI,cAAA;ALmYpB;AKjYgB;EACI,mBAAA;ALmYpB;AKzyBA;EA0agB,YAAA;EACA,iBAAA;EACA,sBAAA;EACA,eAAA;EACA,kBAAA;ALkYhB;AKjYgB;EACI,0CAAA;ALmYpB;AKnzBA;EAqbY,qBAAA;EACA,YAAA;ALiYZ;AKvzBA;EAwbgB,kBAAA;EACA,QAAA;EACA,YAAA;EACA,mBAAA;EACA,YAAA;EACA,kBAAA;EACA,iCAAA;EACA,cAAA;EACA,gCAAA;EACA,gBAAA;EACA,UAAA;ALkYhB;AKjYgB;EACI,aAAA;ALmYpB;AKlYoB;EACI,cAAA;ALoYxB;AKjYgB;EACI,mBAAA;ALmYpB;AKjYgB;EACI,WAAA;EACA,kBAAA;ALmYpB;AKjYgB;EAEQ,aAAA;ALkYxB;AKpYgB;EAKQ,cAAA;ALkYxB;AKv1BA;;EA2dgB,YAAA;EACA,iBAAA;EACA,sBAAA;EACA,eAAA;EACA,kBAAA;ALgYhB;AK/XgB;;EACI,0CAAA;ALkYpB;AKn2BA;EAqegB,cAAA;ALiYhB;AKt2BA;EAueoB,eAAA;EACA,eAAA;ALkYpB;AKhYgB;EAEQ,aAAA;ALiYxB;AKnYgB;EAKQ,qBAAA;ALiYxB;AK9XgB;EAEQ,aAAA;AL+XxB;AKjYgB;EAKQ,qBAAA;AL+XxB;AKt3BA;EA2foB,eAAA;EACA,sBAAA;EACA,aAAA;EACA,sBAAA;EACA,YAAA;EACA,WAAA;AL8XpB;AK93BA;EAkgBwB,kBAAA;EACA,UAAA;EACA,WAAA;EACA,WAAA;EACA,gBAAA;EACA,gCAAA;AL+XxB;AKt4BA;EAygB4B,kBAAA;EACA,SAAA;EACA,OAAA;EACA,YAAA;EACA,yBAAA;EACA,gBAAA;EACA,kBAAA;ALgY5B;AK/4BA;EAihBgC,kBAAA;EACA,MAAA;EACA,UAAA;EACA,gBAAA;EACA,mBAAA;EACA,YAAA;EACA,WAAA;EACA,kBAAA;EACA,eAAA;EACA,gCAAA;EACA,gBAAA;ALiYhC;AK55BA;EAmiBY,qBAAA;EACA,YAAA;EACA,kBAAA;AL4XZ;AK3XY;EAEQ,cAAA;AL4XpB;AKp6BA;EA4iBgB,kBAAA;EACA,UAAA;EACA,UAAA;EACA,aAAA;AL2XhB;AK16BA;EAmjBY,kBAAA;EACA,qBAAA;EACA,YAAA;EACA,UAAA;AL0XZ;AKzXY;EAEQ,cAAA;AL0XpB;AK5XY;EAKQ,cAAA;AL0XpB;AKt7BA;EAgkBgB,aAAA;EACA,kBAAA;EACA,YAAA;EACA,WAAA;EACA,WAAA;EACA,oBAAA;ALyXhB;AK97BA;EAwkBgB,aAAA;EACA,eAAA;EACA,WAAA;EACA,kBAAA;EACA,iCAAA;EACA,cAAA;EACA,gCAAA;EACA,gBAAA;EACA,WAAA;EACA,kBAAA;ALyXhB;AK18BA;EAolBgB,YAAA;EACA,sBAAA;EACA,eAAA;EACA,iBAAA;ALyXhB;AKxXgB;EACI,0CAAA;AL0XpB;AKn9BA;EA8lBY,qBAAA;EACA,YAAA;ALwXZ;AKv9BA;EAkmBY,WAAA;EACA,eAAA;EACA,qBAAA;EACA,sBAAA;EACA,mBAAA;ALwXZ;AK99BA;EAymBY,WAAA;EACA,YAAA;EACA,kBAAA;EACA,YAAA;EACA,sBAAA;EACA,kBAAA;EACA,QAAA;EACA,WAAA;ALwXZ;AKx+BA;EAknBgB,aAAA;EACA,YAAA;EACA,aAAA;ALyXhB;AK7+BA;EAunBgB,qBAAA;EACA,kBAAA;EACA,iCAAA;EACA,yBAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,sBAAA;EACA,eAAA;EACA,4BAAA;ALyXhB;AKz/BA;EAmoBgB,WAAA;EACA,kBAAA;EACA,cAAA;EACA,YAAA;EACA,WAAA;EACA,MAAA;EACA,OAAA;EACA,mBAAA;EACA,4BAAA;ALyXhB;AKpgCA;EA8oBgB,WAAA;EACA,kBAAA;EACA,cAAA;EACA,OAAA;EACA,MAAA;EACA,mBAAA;EACA,gBAAA;EACA,4BAAA;EACA,wCAAA;EACA,YAAA;EACA,WAAA;ALyXhB;AKjhCA;EA2pBgB,sCAAA;ALyXhB;AKphCA;EA8pBgB,WAAA;EACA,oCAAA;ALyXhB;AKxhCA;EAkqBgB,UAAA;ALyXhB;AKnXA;EACI,aAAA;EACA,WAAA;EACA,YAAA;EACA,YAAA;EACA,6BAAA;EACA,aAAA;EACA,eAAA;EACA,sBAAA;EAEA,SAAA;EACA,YAAA;EACA,kBAAA;EACA,SAAA;EACA,QAAA;EACA,gCAAA;ALoXJ;AMpjCA;EACI,kBAAA;EACA,OAAA;EACA,QAAA;EACA,MAAA;EACA,SAAA;EACA,eAAA;EACA,WAAA;ANsjCJ;AM7jCA;EASQ,qBAAA;EACA,oBAAA;EACA,yBAAA;KAAA,sBAAA;UAAA,iBAAA;EACA,eAAA;EACA,mBAAA;EACA,iDAAA;ANujCR;AMtjCQ;EACI,kBAAA;EACA,kBAAA;ANwjCZ;AMzkCA;EAqBQ,kBAAA;EACA,QAAA;EACA,2BAAA;ANujCR;AMtjCQ;EACI,sBAAA;EACA,yBAAA;EACA,iCAAA;EACA,4BAAA;ANwjCZ;AMrjCI;EACI;IACI,2BAAA;ENujCV;AACF;AMzlCA;;EAsCQ,kBAAA;EACA,WAAA;EACA,kBAAA;EACA,kBAAA;ANujCR;AMtjCQ;;EACI,uBAAA;EACA,gCAAA;EACA,iCAAA;EACA,4BAAA;ANyjCZ;AMtjCI;EACI;IACI,mBAAA;ENwjCV;EMtjCM;IACI,mBAAA;ENwjCV;AACF;AO/mCA;EACI,oBAAA;EACA,kBAAA;EACA,UAAA;EACA,SAAA;EACA,eAAA;EACA,gBAAA;APinCJ;AOvnCA;EAQQ,eAAA;EACA,gBAAA;EACA,gBAAA;APknCR;AQ5nCA;EACI,kBAAA;EACA,YAAA;EACA,kBAAA;EACA,kCAAA;EACA,cAAA;EACA,gBAAA;EACA,UAAA;EACA,aAAA;AR8nCJ;AQ7nCI;EACI,cAAA;AR+nCR;AQzoCA;EAaQ,YAAA;EACA,sBAAA;EACA,eAAA;AR+nCR;AQ9nCQ;EACI,0CAAA;ARgoCZ;AQjpCA;EAqBY,eAAA;EACA,iBAAA;EACA,WAAA;EACA,eAAA;EACA,qBAAA;EACA,sBAAA;EACA,WAAA;EACA,sBAAA;EACA,mBAAA;EACA,uBAAA;EACA,gBAAA;AR+nCZ;AQ9nCY;EACI,qBAAA;ARgoChB;AIjqCA;EACI,kBAAA;EACA,YAAA;EACA,UAAA;AJmqCJ;AItqCA;EAMQ,kBAAA;EACA,iCAAA;EACA,gCAAA;EACA,gBAAA;EACA,WAAA;EACA,cAAA;EACA,oBAAA;EACA,0CAAA;AJmqCR;AIhrCA;EAiBQ,4CAAA;AJkqCR;AI9pCA;EACI;IACI,UAAA;IACA,YAAA;IACA,aAAA;EJgqCN;EI9pCE;IACI,iBAAA;IACA,eAAA;IACA,eAAA;EJgqCN;AACF;AI7pCA;EACI;IACI,iBAAA;IACA,eAAA;IACA,eAAA;EJ+pCN;EI7pCE;IACI,eAAA;EJ+pCN;EI7pCE;IACI,YAAA;IACA,iBAAA;EJ+pCN;EI7pCE;IACI,UAAA;IACA,aAAA;IACA,YAAA;EJ+pCN;AACF;ASltCA;EACI,kBAAA;EACA,YAAA;EACA,UAAA;EACA,QAAA;EACA,kBAAA;EACA,WAAA;EACA,iDAAA;EACA,eAAA;ATotCJ;ASntCI;EACI,aAAA;ATqtCR;AU/tCA;EACI,kBAAA;EACA,MAAA;EACA,SAAA;EACA,OAAA;EACA,QAAA;EACA,UAAA;EACA,aAAA;AViuCJ;AUhuCI;EACI,cAAA;AVkuCR;AU9tCA;EACI,kBAAA;EACA,gBAAA;EACA,YAAA;EACA,WAAA;EACA,YAAA;AVguCJ;AUruCA;EAOQ,WAAA;EACA,YAAA;EACA,aAAA;AViuCR;AU1uCA;EAYQ,cAAA;AViuCR;AU7uCA;EAeQ,aAAA;AViuCR;AW7vCA;EACI,kBAAA;EACA,SAAA;EACA,UAAA;EACA,YAAA;EACA,iCAAA;EACA,aAAA;EACA,WAAA;EACA,eAAA;EACA,kBAAA;AX+vCJ;AW7vCI;EACI,aAAA;AX+vCR;AW3wCA;EAgBQ,eAAA;EACA,kBAAA;EACA,WAAA;EACA,SAAA;AX8vCR;AW1vCQ;EACI,qBAAA;EACA,sBAAA;EACA,iBAAA;EACA,mBAAA;EACA,uBAAA;EACA,gBAAA;AX4vCZ;AWzxCA;EAkCQ,YAAA;EACA,iBAAA;EACA,kBAAA;AX0vCR;AW9xCA;EAwCQ,YAAA;AXyvCR",
            sourcesContent: ["@keyframes my-face {\n    2% {\n        transform: translate(0, 1.5px) rotate(1.5deg);\n    }\n    4% {\n        transform: translate(0, -1.5px) rotate(-0.5deg);\n    }\n    6% {\n        transform: translate(0, 1.5px) rotate(-1.5deg);\n    }\n    8% {\n        transform: translate(0, -1.5px) rotate(-1.5deg);\n    }\n    10% {\n        transform: translate(0, 2.5px) rotate(1.5deg);\n    }\n    12% {\n        transform: translate(0, -0.5px) rotate(1.5deg);\n    }\n    14% {\n        transform: translate(0, -1.5px) rotate(1.5deg);\n    }\n    16% {\n        transform: translate(0, -0.5px) rotate(-1.5deg);\n    }\n    18% {\n        transform: translate(0, 0.5px) rotate(-1.5deg);\n    }\n    20% {\n        transform: translate(0, -1.5px) rotate(2.5deg);\n    }\n    22% {\n        transform: translate(0, 0.5px) rotate(-1.5deg);\n    }\n    24% {\n        transform: translate(0, 1.5px) rotate(1.5deg);\n    }\n    26% {\n        transform: translate(0, 0.5px) rotate(0.5deg);\n    }\n    28% {\n        transform: translate(0, 0.5px) rotate(1.5deg);\n    }\n    30% {\n        transform: translate(0, -0.5px) rotate(2.5deg);\n    }\n    32% {\n        transform: translate(0, 1.5px) rotate(-0.5deg);\n    }\n    34% {\n        transform: translate(0, 1.5px) rotate(-0.5deg);\n    }\n    36% {\n        transform: translate(0, -1.5px) rotate(2.5deg);\n    }\n    38% {\n        transform: translate(0, 1.5px) rotate(-1.5deg);\n    }\n    40% {\n        transform: translate(0, -0.5px) rotate(2.5deg);\n    }\n    42% {\n        transform: translate(0, 2.5px) rotate(-1.5deg);\n    }\n    44% {\n        transform: translate(0, 1.5px) rotate(0.5deg);\n    }\n    46% {\n        transform: translate(0, -1.5px) rotate(2.5deg);\n    }\n    48% {\n        transform: translate(0, -0.5px) rotate(0.5deg);\n    }\n    50% {\n        transform: translate(0, 0.5px) rotate(0.5deg);\n    }\n    52% {\n        transform: translate(0, 2.5px) rotate(2.5deg);\n    }\n    54% {\n        transform: translate(0, -1.5px) rotate(1.5deg);\n    }\n    56% {\n        transform: translate(0, 2.5px) rotate(2.5deg);\n    }\n    58% {\n        transform: translate(0, 0.5px) rotate(2.5deg);\n    }\n    60% {\n        transform: translate(0, 2.5px) rotate(2.5deg);\n    }\n    62% {\n        transform: translate(0, -0.5px) rotate(2.5deg);\n    }\n    64% {\n        transform: translate(0, -0.5px) rotate(1.5deg);\n    }\n    66% {\n        transform: translate(0, 1.5px) rotate(-0.5deg);\n    }\n    68% {\n        transform: translate(0, -1.5px) rotate(-0.5deg);\n    }\n    70% {\n        transform: translate(0, 1.5px) rotate(0.5deg);\n    }\n    72% {\n        transform: translate(0, 2.5px) rotate(1.5deg);\n    }\n    74% {\n        transform: translate(0, -0.5px) rotate(0.5deg);\n    }\n    76% {\n        transform: translate(0, -0.5px) rotate(2.5deg);\n    }\n    78% {\n        transform: translate(0, -0.5px) rotate(1.5deg);\n    }\n    80% {\n        transform: translate(0, 1.5px) rotate(1.5deg);\n    }\n    82% {\n        transform: translate(0, -0.5px) rotate(0.5deg);\n    }\n    84% {\n        transform: translate(0, 1.5px) rotate(2.5deg);\n    }\n    86% {\n        transform: translate(0, -1.5px) rotate(-1.5deg);\n    }\n    88% {\n        transform: translate(0, -0.5px) rotate(2.5deg);\n    }\n    90% {\n        transform: translate(0, 2.5px) rotate(-0.5deg);\n    }\n    92% {\n        transform: translate(0, 0.5px) rotate(-0.5deg);\n    }\n    94% {\n        transform: translate(0, 2.5px) rotate(0.5deg);\n    }\n    96% {\n        transform: translate(0, -0.5px) rotate(1.5deg);\n    }\n    98% {\n        transform: translate(0, -1.5px) rotate(-0.5deg);\n    }\n    0%,\n    100% {\n        transform: translate(0, 0) rotate(0deg);\n    }\n}", `@import '../../node_modules/balloon-css/balloon.css';
@keyframes my-face {
  2% {
    transform: translate(0, 1.5px) rotate(1.5deg);
  }
  4% {
    transform: translate(0, -1.5px) rotate(-0.5deg);
  }
  6% {
    transform: translate(0, 1.5px) rotate(-1.5deg);
  }
  8% {
    transform: translate(0, -1.5px) rotate(-1.5deg);
  }
  10% {
    transform: translate(0, 2.5px) rotate(1.5deg);
  }
  12% {
    transform: translate(0, -0.5px) rotate(1.5deg);
  }
  14% {
    transform: translate(0, -1.5px) rotate(1.5deg);
  }
  16% {
    transform: translate(0, -0.5px) rotate(-1.5deg);
  }
  18% {
    transform: translate(0, 0.5px) rotate(-1.5deg);
  }
  20% {
    transform: translate(0, -1.5px) rotate(2.5deg);
  }
  22% {
    transform: translate(0, 0.5px) rotate(-1.5deg);
  }
  24% {
    transform: translate(0, 1.5px) rotate(1.5deg);
  }
  26% {
    transform: translate(0, 0.5px) rotate(0.5deg);
  }
  28% {
    transform: translate(0, 0.5px) rotate(1.5deg);
  }
  30% {
    transform: translate(0, -0.5px) rotate(2.5deg);
  }
  32% {
    transform: translate(0, 1.5px) rotate(-0.5deg);
  }
  34% {
    transform: translate(0, 1.5px) rotate(-0.5deg);
  }
  36% {
    transform: translate(0, -1.5px) rotate(2.5deg);
  }
  38% {
    transform: translate(0, 1.5px) rotate(-1.5deg);
  }
  40% {
    transform: translate(0, -0.5px) rotate(2.5deg);
  }
  42% {
    transform: translate(0, 2.5px) rotate(-1.5deg);
  }
  44% {
    transform: translate(0, 1.5px) rotate(0.5deg);
  }
  46% {
    transform: translate(0, -1.5px) rotate(2.5deg);
  }
  48% {
    transform: translate(0, -0.5px) rotate(0.5deg);
  }
  50% {
    transform: translate(0, 0.5px) rotate(0.5deg);
  }
  52% {
    transform: translate(0, 2.5px) rotate(2.5deg);
  }
  54% {
    transform: translate(0, -1.5px) rotate(1.5deg);
  }
  56% {
    transform: translate(0, 2.5px) rotate(2.5deg);
  }
  58% {
    transform: translate(0, 0.5px) rotate(2.5deg);
  }
  60% {
    transform: translate(0, 2.5px) rotate(2.5deg);
  }
  62% {
    transform: translate(0, -0.5px) rotate(2.5deg);
  }
  64% {
    transform: translate(0, -0.5px) rotate(1.5deg);
  }
  66% {
    transform: translate(0, 1.5px) rotate(-0.5deg);
  }
  68% {
    transform: translate(0, -1.5px) rotate(-0.5deg);
  }
  70% {
    transform: translate(0, 1.5px) rotate(0.5deg);
  }
  72% {
    transform: translate(0, 2.5px) rotate(1.5deg);
  }
  74% {
    transform: translate(0, -0.5px) rotate(0.5deg);
  }
  76% {
    transform: translate(0, -0.5px) rotate(2.5deg);
  }
  78% {
    transform: translate(0, -0.5px) rotate(1.5deg);
  }
  80% {
    transform: translate(0, 1.5px) rotate(1.5deg);
  }
  82% {
    transform: translate(0, -0.5px) rotate(0.5deg);
  }
  84% {
    transform: translate(0, 1.5px) rotate(2.5deg);
  }
  86% {
    transform: translate(0, -1.5px) rotate(-1.5deg);
  }
  88% {
    transform: translate(0, -0.5px) rotate(2.5deg);
  }
  90% {
    transform: translate(0, 2.5px) rotate(-0.5deg);
  }
  92% {
    transform: translate(0, 0.5px) rotate(-0.5deg);
  }
  94% {
    transform: translate(0, 2.5px) rotate(0.5deg);
  }
  96% {
    transform: translate(0, -0.5px) rotate(1.5deg);
  }
  98% {
    transform: translate(0, -1.5px) rotate(-0.5deg);
  }
  0%,
  100% {
    transform: translate(0, 0) rotate(0deg);
  }
}
.dplayer {
  position: relative;
  overflow: hidden;
  user-select: none;
  line-height: 1;
}
.dplayer * {
  box-sizing: content-box;
}
.dplayer svg {
  width: 100%;
  height: 100%;
}
.dplayer svg path,
.dplayer svg circle {
  fill: #fff;
}
.dplayer:-webkit-full-screen {
  width: 100%;
  height: 100%;
  background: #000;
  position: fixed;
  z-index: 100000;
  left: 0;
  top: 0;
  margin: 0;
  padding: 0;
  transform: translate(0, 0);
}
.dplayer.dplayer-no-danmaku .dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box .dplayer-setting-showdan,
.dplayer.dplayer-no-danmaku .dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box .dplayer-setting-danmaku,
.dplayer.dplayer-no-danmaku .dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box .dplayer-setting-danunlimit {
  display: none;
}
.dplayer.dplayer-no-danmaku .dplayer-controller .dplayer-icons .dplayer-comment {
  display: none;
}
.dplayer.dplayer-no-danmaku .dplayer-danmaku {
  display: none;
}
.dplayer.dplayer-live .dplayer-time {
  display: none;
}
.dplayer.dplayer-live .dplayer-bar-wrap {
  display: none;
}
.dplayer.dplayer-live .dplayer-setting-speed {
  display: none;
}
.dplayer.dplayer-live .dplayer-setting-loop {
  display: none;
}
.dplayer.dplayer-live.dplayer-no-danmaku .dplayer-setting {
  display: none;
}
.dplayer.dplayer-arrow .dplayer-danmaku {
  font-size: 18px;
}
.dplayer.dplayer-arrow .dplayer-icon {
  margin: 0 -3px;
}
.dplayer.dplayer-playing .dplayer-danmaku .dplayer-danmaku-move {
  animation-play-state: running;
}
@media (min-width: 900px) {
  .dplayer.dplayer-playing .dplayer-controller-mask {
    opacity: 0;
  }
  .dplayer.dplayer-playing .dplayer-controller {
    opacity: 0;
  }
  .dplayer.dplayer-playing:hover .dplayer-controller-mask {
    opacity: 1;
  }
  .dplayer.dplayer-playing:hover .dplayer-controller {
    opacity: 1;
  }
}
.dplayer.dplayer-loading .dplayer-bezel .diplayer-loading-icon {
  display: block;
}
.dplayer.dplayer-loading .dplayer-danmaku,
.dplayer.dplayer-paused .dplayer-danmaku,
.dplayer.dplayer-loading .dplayer-danmaku-move,
.dplayer.dplayer-paused .dplayer-danmaku-move {
  animation-play-state: paused;
}
.dplayer.dplayer-hide-controller {
  cursor: none;
}
.dplayer.dplayer-hide-controller .dplayer-controller-mask {
  opacity: 0;
  transform: translateY(100%);
}
.dplayer.dplayer-hide-controller .dplayer-controller {
  opacity: 0;
  transform: translateY(100%);
}
.dplayer.dplayer-show-controller .dplayer-controller-mask {
  opacity: 1;
}
.dplayer.dplayer-show-controller .dplayer-controller {
  opacity: 1;
}
.dplayer.dplayer-fulled {
  position: fixed;
  z-index: 100000;
  left: 0;
  top: 0;
  width: 100% !important;
  height: 100% !important;
}
.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-volume,
.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-camera-icon,
.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-airplay-icon,
.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-chromecast-icon,
.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-play-icon {
  display: none;
}
.dplayer.dplayer-mobile .dplayer-controller .dplayer-icons .dplayer-full .dplayer-full-in-icon {
  position: static;
  display: inline-block;
}
.dplayer.dplayer-mobile .dplayer-bar-time {
  display: none;
}
.dplayer.dplayer-mobile.dplayer-hide-controller .dplayer-mobile-play {
  display: none;
}
.dplayer.dplayer-mobile .dplayer-mobile-play {
  display: block;
}
.dplayer-web-fullscreen-fix {
  position: fixed;
  top: 0;
  left: 0;
  margin: 0;
  padding: 0;
}
[data-balloon]:before {
  display: none;
}
[data-balloon]:after {
  padding: 0.3em 0.7em;
  background: rgba(17, 17, 17, 0.7);
}
[data-balloon][data-balloon-pos="up"]:after {
  margin-bottom: 0;
}
.dplayer-bezel {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  font-size: 22px;
  color: #fff;
  pointer-events: none;
}
.dplayer-bezel .dplayer-bezel-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -26px 0 0 -26px;
  height: 52px;
  width: 52px;
  padding: 12px;
  box-sizing: border-box;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  opacity: 0;
  pointer-events: none;
}
.dplayer-bezel .dplayer-bezel-icon.dplayer-bezel-transition {
  animation: bezel-hide 0.5s linear;
}
@keyframes bezel-hide {
  from {
    opacity: 1;
    transform: scale(1);
  }
  to {
    opacity: 0;
    transform: scale(2);
  }
}
.dplayer-bezel .dplayer-danloading {
  position: absolute;
  top: 50%;
  margin-top: -7px;
  width: 100%;
  text-align: center;
  font-size: 14px;
  line-height: 14px;
  animation: my-face 5s infinite ease-in-out;
}
.dplayer-bezel .diplayer-loading-icon {
  display: none;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -18px 0 0 -18px;
  height: 36px;
  width: 36px;
  pointer-events: none;
}
.dplayer-bezel .diplayer-loading-icon .diplayer-loading-hide {
  display: none;
}
.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot {
  animation: diplayer-loading-dot-fade 0.8s ease infinite;
  opacity: 0;
  transform-origin: 4px 4px;
}
.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-1 {
  animation-delay: 0.1s;
}
.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-2 {
  animation-delay: 0.2s;
}
.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-3 {
  animation-delay: 0.3s;
}
.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-4 {
  animation-delay: 0.4s;
}
.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-5 {
  animation-delay: 0.5s;
}
.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-6 {
  animation-delay: 0.6s;
}
.dplayer-bezel .diplayer-loading-icon .diplayer-loading-dot.diplayer-loading-dot-7 {
  animation-delay: 0.7s;
}
@keyframes diplayer-loading-dot-fade {
  0% {
    opacity: 0.7;
    transform: scale(1.2, 1.2);
  }
  50% {
    opacity: 0.25;
    transform: scale(0.9, 0.9);
  }
  to {
    opacity: 0.25;
    transform: scale(0.85, 0.85);
  }
}
.dplayer-controller-mask {
  background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAADGCAYAAAAT+OqFAAAAdklEQVQoz42QQQ7AIAgEF/T/D+kbq/RWAlnQyyazA4aoAB4FsBSA/bFjuF1EOL7VbrIrBuusmrt4ZZORfb6ehbWdnRHEIiITaEUKa5EJqUakRSaEYBJSCY2dEstQY7AuxahwXFrvZmWl2rh4JZ07z9dLtesfNj5q0FU3A5ObbwAAAABJRU5ErkJggg==) repeat-x bottom;
  height: 98px;
  width: 100%;
  position: absolute;
  bottom: 0;
  transition: all 0.3s ease;
}
.dplayer-controller {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 41px;
  padding: 0 20px;
  user-select: none;
  transition: all 0.3s ease;
}
.dplayer-controller.dplayer-controller-comment .dplayer-icons {
  display: none;
}
.dplayer-controller.dplayer-controller-comment .dplayer-icons.dplayer-comment-box {
  display: block;
}
.dplayer-controller .dplayer-bar-wrap {
  padding: 5px 0;
  cursor: pointer;
  position: absolute;
  bottom: 33px;
  width: calc(100% - 40px);
  height: 3px;
}
.dplayer-controller .dplayer-bar-wrap:hover .dplayer-bar .dplayer-played .dplayer-thumb {
  transform: scale(1);
}
.dplayer-controller .dplayer-bar-wrap:hover .dplayer-highlight {
  display: block;
  width: 8px;
  transform: translateX(-4px);
  top: 4px;
  height: 40%;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-highlight {
  z-index: 12;
  position: absolute;
  top: 5px;
  width: 6px;
  height: 20%;
  border-radius: 6px;
  background-color: #fff;
  text-align: center;
  transform: translateX(-3px);
  transition: all 0.2s ease-in-out;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-highlight:hover .dplayer-highlight-text {
  display: block;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-highlight:hover ~ .dplayer-bar-preview {
  opacity: 0;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-highlight:hover ~ .dplayer-bar-time {
  opacity: 0;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-highlight .dplayer-highlight-text {
  display: none;
  position: absolute;
  left: 50%;
  top: -24px;
  padding: 5px 8px;
  background-color: rgba(0, 0, 0, 0.62);
  color: #fff;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  transform: translateX(-50%);
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar-preview {
  position: absolute;
  background: #fff;
  pointer-events: none;
  display: none;
  background-size: 16000px 100%;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar-preview-canvas {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 1;
  pointer-events: none;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar-time {
  position: absolute;
  left: 0px;
  top: -20px;
  border-radius: 4px;
  padding: 5px 7px;
  background-color: rgba(0, 0, 0, 0.62);
  color: #fff;
  font-size: 12px;
  text-align: center;
  opacity: 1;
  transition: opacity 0.1s ease-in-out;
  word-wrap: normal;
  word-break: normal;
  z-index: 2;
  pointer-events: none;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar-time.hidden {
  opacity: 0;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar {
  position: relative;
  height: 3px;
  width: 100%;
  background: rgba(255, 255, 255, 0.2);
  cursor: pointer;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar .dplayer-loaded {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.4);
  height: 3px;
  transition: all 0.5s ease;
  will-change: width;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar .dplayer-played {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  height: 3px;
  will-change: width;
}
.dplayer-controller .dplayer-bar-wrap .dplayer-bar .dplayer-played .dplayer-thumb {
  position: absolute;
  top: 0;
  right: 5px;
  margin-top: -4px;
  margin-right: -10px;
  height: 11px;
  width: 11px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  transform: scale(0);
}
.dplayer-controller .dplayer-icons {
  height: 38px;
  position: absolute;
  bottom: 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box {
  display: none;
  position: absolute;
  transition: all 0.3s ease-in-out;
  z-index: 2;
  height: 38px;
  bottom: 0;
  left: 20px;
  right: 20px;
  color: #fff;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-icon {
  padding: 7px;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-icon {
  position: absolute;
  left: 0;
  top: 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-send-icon {
  position: absolute;
  right: 0;
  top: 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box {
  position: absolute;
  background: rgba(28, 28, 28, 0.9);
  bottom: 41px;
  left: 0;
  box-shadow: 0 0 25px rgba(0, 0, 0, 0.3);
  border-radius: 4px;
  padding: 10px 10px 16px;
  font-size: 14px;
  width: 204px;
  transition: all 0.3s ease-in-out;
  transform: scale(0);
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box.dplayer-comment-setting-open {
  transform: scale(1);
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box input[type=radio] {
  display: none;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box label {
  cursor: pointer;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-title {
  font-size: 13px;
  color: #fff;
  line-height: 30px;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type {
  font-size: 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type .dplayer-comment-setting-title {
  margin-bottom: 6px;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type label:nth-child(2) span {
  border-radius: 4px 0 0 4px;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type label:nth-child(4) span {
  border-radius: 0 4px 4px 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type span {
  width: 33%;
  padding: 4px 6px;
  line-height: 16px;
  display: inline-block;
  font-size: 12px;
  color: #fff;
  border: 1px solid #fff;
  margin-right: -1px;
  box-sizing: border-box;
  text-align: center;
  cursor: pointer;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-type input:checked + span {
  background: #E4E4E6;
  color: #1c1c1c;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-color {
  font-size: 0;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-color label {
  font-size: 0;
  padding: 6px;
  display: inline-block;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-color span {
  width: 22px;
  height: 22px;
  display: inline-block;
  border-radius: 50%;
  box-sizing: border-box;
  cursor: pointer;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-setting-box .dplayer-comment-setting-color span:hover {
  animation: my-face 5s infinite ease-in-out;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-input {
  outline: none;
  border: none;
  padding: 8px 31px;
  font-size: 14px;
  line-height: 18px;
  text-align: center;
  border-radius: 4px;
  background: none;
  margin: 0;
  height: 100%;
  box-sizing: border-box;
  width: 100%;
  color: #fff;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-input::placeholder {
  color: #fff;
  opacity: 0.8;
}
.dplayer-controller .dplayer-icons.dplayer-comment-box .dplayer-comment-input::-ms-clear {
  display: none;
}
.dplayer-controller .dplayer-icons.dplayer-icons-left .dplayer-icon {
  padding: 7px;
}
.dplayer-controller .dplayer-icons.dplayer-icons-right {
  right: 20px;
}
.dplayer-controller .dplayer-icons.dplayer-icons-right .dplayer-icon {
  padding: 8px;
}
.dplayer-controller .dplayer-icons .dplayer-time,
.dplayer-controller .dplayer-icons .dplayer-live-badge {
  line-height: 38px;
  color: #eee;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
  vertical-align: middle;
  font-size: 13px;
  cursor: default;
}
.dplayer-controller .dplayer-icons .dplayer-live-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  vertical-align: 4%;
  margin-right: 5px;
  content: '';
  border-radius: 6px;
}
.dplayer-controller .dplayer-icons .dplayer-icon {
  width: 40px;
  height: 100%;
  border: none;
  background-color: transparent;
  outline: none;
  cursor: pointer;
  vertical-align: middle;
  box-sizing: border-box;
  display: inline-block;
}
.dplayer-controller .dplayer-icons .dplayer-icon .dplayer-icon-content {
  transition: all 0.2s ease-in-out;
  opacity: 0.8;
}
.dplayer-controller .dplayer-icons .dplayer-icon:hover .dplayer-icon-content {
  opacity: 1;
}
.dplayer-controller .dplayer-icons .dplayer-icon.dplayer-quality-icon {
  color: #fff;
  width: auto;
  line-height: 22px;
  font-size: 14px;
}
.dplayer-controller .dplayer-icons .dplayer-icon.dplayer-comment-icon {
  padding: 10px 9px 9px;
}
.dplayer-controller .dplayer-icons .dplayer-icon.dplayer-setting-icon {
  padding-top: 8.5px;
}
.dplayer-controller .dplayer-icons .dplayer-icon.dplayer-volume-icon {
  width: 43px;
}
.dplayer-controller .dplayer-icons .dplayer-volume {
  position: relative;
  display: inline-block;
  cursor: pointer;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-volume:hover .dplayer-volume-bar-wrap .dplayer-volume-bar {
  width: 45px;
}
.dplayer-controller .dplayer-icons .dplayer-volume:hover .dplayer-volume-bar-wrap .dplayer-volume-bar .dplayer-volume-bar-inner .dplayer-thumb {
  transform: scale(1);
}
.dplayer-controller .dplayer-icons .dplayer-volume.dplayer-volume-active .dplayer-volume-bar-wrap .dplayer-volume-bar {
  width: 45px;
}
.dplayer-controller .dplayer-icons .dplayer-volume.dplayer-volume-active .dplayer-volume-bar-wrap .dplayer-volume-bar .dplayer-volume-bar-inner .dplayer-thumb {
  transform: scale(1);
}
.dplayer-controller .dplayer-icons .dplayer-volume .dplayer-volume-bar-wrap {
  display: inline-block;
  margin: 0 10px 0 -5px;
  vertical-align: middle;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-volume .dplayer-volume-bar-wrap .dplayer-volume-bar {
  position: relative;
  top: 17px;
  width: 0;
  height: 3px;
  background: #aaa;
  transition: all 0.3s ease-in-out;
}
.dplayer-controller .dplayer-icons .dplayer-volume .dplayer-volume-bar-wrap .dplayer-volume-bar .dplayer-volume-bar-inner {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 100%;
  transition: all 0.1s ease;
  will-change: width;
}
.dplayer-controller .dplayer-icons .dplayer-volume .dplayer-volume-bar-wrap .dplayer-volume-bar .dplayer-volume-bar-inner .dplayer-thumb {
  position: absolute;
  top: 0;
  right: 5px;
  margin-top: -4px;
  margin-right: -10px;
  height: 11px;
  width: 11px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  transform: scale(0);
}
.dplayer-controller .dplayer-icons .dplayer-subtitle-btn {
  display: inline-block;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-subtitles {
  display: inline-block;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-subtitles .dplayer-subtitles-box {
  position: absolute;
  right: 0;
  bottom: 50px;
  transform: scale(0);
  width: fit-content;
  max-width: 240px;
  min-width: 120px;
  border-radius: 2px;
  background: rgba(28, 28, 28, 0.9);
  padding: 7px 0;
  transition: all 0.3s ease-in-out;
  overflow: auto;
  z-index: 2;
}
.dplayer-controller .dplayer-icons .dplayer-subtitles .dplayer-subtitles-box.dplayer-subtitles-panel {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-subtitles .dplayer-subtitles-box.dplayer-subtitles-box-open {
  transform: scale(1);
}
.dplayer-controller .dplayer-icons .dplayer-subtitles .dplayer-subtitles-item {
  height: 30px;
  padding: 5px 10px;
  box-sizing: border-box;
  cursor: pointer;
  position: relative;
}
.dplayer-controller .dplayer-icons .dplayer-subtitles .dplayer-subtitles-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.dplayer-controller .dplayer-icons .dplayer-setting {
  display: inline-block;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box {
  position: absolute;
  right: 0;
  bottom: 50px;
  transform: scale(0);
  width: 150px;
  border-radius: 2px;
  background: rgba(28, 28, 28, 0.9);
  padding: 7px 0;
  transition: all 0.3s ease-in-out;
  overflow: hidden;
  z-index: 2;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box > div {
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box > div.dplayer-setting-origin-panel {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box.dplayer-setting-box-open {
  transform: scale(1);
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box.dplayer-setting-box-narrow {
  width: 70px;
  text-align: center;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box.dplayer-setting-box-speed .dplayer-setting-origin-panel {
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box.dplayer-setting-box-speed .dplayer-setting-speed-panel {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-item,
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-speed-item {
  height: 30px;
  padding: 5px 10px;
  box-sizing: border-box;
  cursor: pointer;
  position: relative;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-item:hover,
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-speed-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku {
  padding: 5px 0;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku .dplayer-label {
  padding: 0 10px;
  display: inline;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku:hover .dplayer-label {
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku:hover .dplayer-danmaku-bar-wrap {
  display: inline-block;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku.dplayer-setting-danmaku-active .dplayer-label {
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku.dplayer-setting-danmaku-active .dplayer-danmaku-bar-wrap {
  display: inline-block;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku .dplayer-danmaku-bar-wrap {
  padding: 0 10px;
  box-sizing: border-box;
  display: none;
  vertical-align: middle;
  height: 100%;
  width: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku .dplayer-danmaku-bar-wrap .dplayer-danmaku-bar {
  position: relative;
  top: 8.5px;
  width: 100%;
  height: 3px;
  background: #fff;
  transition: all 0.3s ease-in-out;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku .dplayer-danmaku-bar-wrap .dplayer-danmaku-bar .dplayer-danmaku-bar-inner {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 100%;
  transition: all 0.1s ease;
  background: #aaa;
  will-change: width;
}
.dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-danmaku .dplayer-danmaku-bar-wrap .dplayer-danmaku-bar .dplayer-danmaku-bar-inner .dplayer-thumb {
  position: absolute;
  top: 0;
  right: 5px;
  margin-top: -4px;
  margin-right: -10px;
  height: 11px;
  width: 11px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  background: #aaa;
}
.dplayer-controller .dplayer-icons .dplayer-full {
  display: inline-block;
  height: 100%;
  position: relative;
}
.dplayer-controller .dplayer-icons .dplayer-full:hover .dplayer-full-in-icon {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-full .dplayer-full-in-icon {
  position: absolute;
  top: -30px;
  z-index: 1;
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-quality {
  position: relative;
  display: inline-block;
  height: 100%;
  z-index: 2;
}
.dplayer-controller .dplayer-icons .dplayer-quality:hover .dplayer-quality-list {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-quality:hover .dplayer-quality-mask {
  display: block;
}
.dplayer-controller .dplayer-icons .dplayer-quality .dplayer-quality-mask {
  display: none;
  position: absolute;
  bottom: 38px;
  left: -18px;
  width: 80px;
  padding-bottom: 12px;
}
.dplayer-controller .dplayer-icons .dplayer-quality .dplayer-quality-list {
  display: none;
  font-size: 12px;
  width: 80px;
  border-radius: 2px;
  background: rgba(28, 28, 28, 0.9);
  padding: 5px 0;
  transition: all 0.3s ease-in-out;
  overflow: hidden;
  color: #fff;
  text-align: center;
}
.dplayer-controller .dplayer-icons .dplayer-quality .dplayer-quality-item {
  height: 25px;
  box-sizing: border-box;
  cursor: pointer;
  line-height: 25px;
}
.dplayer-controller .dplayer-icons .dplayer-quality .dplayer-quality-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.dplayer-controller .dplayer-icons .dplayer-comment {
  display: inline-block;
  height: 100%;
}
.dplayer-controller .dplayer-icons .dplayer-label {
  color: #eee;
  font-size: 13px;
  display: inline-block;
  vertical-align: middle;
  white-space: nowrap;
}
.dplayer-controller .dplayer-icons .dplayer-toggle {
  width: 32px;
  height: 20px;
  text-align: center;
  font-size: 0;
  vertical-align: middle;
  position: absolute;
  top: 5px;
  right: 10px;
}
.dplayer-controller .dplayer-icons .dplayer-toggle input {
  max-height: 0;
  max-width: 0;
  display: none;
}
.dplayer-controller .dplayer-icons .dplayer-toggle input + label {
  display: inline-block;
  position: relative;
  box-shadow: #dfdfdf 0 0 0 0 inset;
  border: 1px solid #dfdfdf;
  height: 20px;
  width: 32px;
  border-radius: 10px;
  box-sizing: border-box;
  cursor: pointer;
  transition: 0.2s ease-in-out;
}
.dplayer-controller .dplayer-icons .dplayer-toggle input + label:before {
  content: "";
  position: absolute;
  display: block;
  height: 18px;
  width: 18px;
  top: 0;
  left: 0;
  border-radius: 15px;
  transition: 0.2s ease-in-out;
}
.dplayer-controller .dplayer-icons .dplayer-toggle input + label:after {
  content: "";
  position: absolute;
  display: block;
  left: 0;
  top: 0;
  border-radius: 15px;
  background: #fff;
  transition: 0.2s ease-in-out;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
  height: 18px;
  width: 18px;
}
.dplayer-controller .dplayer-icons .dplayer-toggle input:checked + label {
  border-color: rgba(255, 255, 255, 0.5);
}
.dplayer-controller .dplayer-icons .dplayer-toggle input:checked + label:before {
  width: 30px;
  background: rgba(255, 255, 255, 0.5);
}
.dplayer-controller .dplayer-icons .dplayer-toggle input:checked + label:after {
  left: 12px;
}
.dplayer-mobile-play {
  display: none;
  width: 50px;
  height: 50px;
  border: none;
  background-color: transparent;
  outline: none;
  cursor: pointer;
  box-sizing: border-box;
  bottom: 0;
  opacity: 0.8;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.dplayer-danmaku {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  font-size: 22px;
  color: #fff;
}
.dplayer-danmaku .dplayer-danmaku-item {
  display: inline-block;
  pointer-events: none;
  user-select: none;
  cursor: default;
  white-space: nowrap;
  text-shadow: 0.5px 0.5px 0.5px rgba(0, 0, 0, 0.5);
}
.dplayer-danmaku .dplayer-danmaku-item--demo {
  position: absolute;
  visibility: hidden;
}
.dplayer-danmaku .dplayer-danmaku-right {
  position: absolute;
  right: 0;
  transform: translateX(100%);
}
.dplayer-danmaku .dplayer-danmaku-right.dplayer-danmaku-move {
  will-change: transform;
  animation-name: 'danmaku';
  animation-timing-function: linear;
  animation-play-state: paused;
}
@keyframes danmaku {
  from {
    transform: translateX(100%);
  }
}
.dplayer-danmaku .dplayer-danmaku-top,
.dplayer-danmaku .dplayer-danmaku-bottom {
  position: absolute;
  width: 100%;
  text-align: center;
  visibility: hidden;
}
.dplayer-danmaku .dplayer-danmaku-top.dplayer-danmaku-move,
.dplayer-danmaku .dplayer-danmaku-bottom.dplayer-danmaku-move {
  will-change: visibility;
  animation-name: 'danmaku-center';
  animation-timing-function: linear;
  animation-play-state: paused;
}
@keyframes danmaku-center {
  from {
    visibility: visible;
  }
  to {
    visibility: visible;
  }
}
.dplayer-logo {
  pointer-events: none;
  position: absolute;
  left: 20px;
  top: 20px;
  max-width: 50px;
  max-height: 50px;
}
.dplayer-logo img {
  max-width: 100%;
  max-height: 100%;
  background: none;
}
.dplayer-menu {
  position: absolute;
  width: 170px;
  border-radius: 2px;
  background: rgba(28, 28, 28, 0.85);
  padding: 5px 0;
  overflow: hidden;
  z-index: 3;
  display: none;
}
.dplayer-menu.dplayer-menu-show {
  display: block;
}
.dplayer-menu .dplayer-menu-item {
  height: 30px;
  box-sizing: border-box;
  cursor: pointer;
}
.dplayer-menu .dplayer-menu-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.dplayer-menu .dplayer-menu-item a {
  padding: 0 10px;
  line-height: 30px;
  color: #eee;
  font-size: 13px;
  display: inline-block;
  vertical-align: middle;
  width: 100%;
  box-sizing: border-box;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.dplayer-menu .dplayer-menu-item a:hover {
  text-decoration: none;
}
.dplayer-notice-list {
  position: absolute;
  bottom: 60px;
  left: 20px;
}
.dplayer-notice-list .dplayer-notice {
  border-radius: 2px;
  background: rgba(28, 28, 28, 0.9);
  transition: all 0.3s ease-in-out;
  overflow: hidden;
  color: #fff;
  display: table;
  pointer-events: none;
  animation: showNotice 0.3s ease 1 forwards;
}
.dplayer-notice-list .remove-notice {
  animation: removeNotice 0.3s ease 1 forwards;
}
@keyframes showNotice {
  from {
    padding: 0;
    font-size: 0;
    margin-top: 0;
  }
  to {
    padding: 7px 20px;
    font-size: 14px;
    margin-top: 5px;
  }
}
@keyframes removeNotice {
  0% {
    padding: 7px 20px;
    font-size: 14px;
    margin-top: 5px;
  }
  20% {
    font-size: 12px;
  }
  21% {
    font-size: 0;
    padding: 7px 10px;
  }
  100% {
    padding: 0;
    margin-top: 0;
    font-size: 0;
  }
}
.dplayer-subtitle {
  position: absolute;
  bottom: 40px;
  width: 90%;
  left: 5%;
  text-align: center;
  color: #fff;
  text-shadow: 0.5px 0.5px 0.5px rgba(0, 0, 0, 0.5);
  font-size: 20px;
}
.dplayer-subtitle.dplayer-subtitle-hide {
  display: none;
}
.dplayer-mask {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1;
  display: none;
}
.dplayer-mask.dplayer-mask-show {
  display: block;
}
.dplayer-video-wrap {
  position: relative;
  background: #000;
  font-size: 0;
  width: 100%;
  height: 100%;
}
.dplayer-video-wrap .dplayer-video {
  width: 100%;
  height: 100%;
  display: none;
}
.dplayer-video-wrap .dplayer-video-current {
  display: block;
}
.dplayer-video-wrap .dplayer-video-prepare {
  display: none;
}
.dplayer-info-panel {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 400px;
  background: rgba(28, 28, 28, 0.8);
  padding: 10px;
  color: #fff;
  font-size: 12px;
  border-radius: 2px;
}
.dplayer-info-panel-hide {
  display: none;
}
.dplayer-info-panel .dplayer-info-panel-close {
  cursor: pointer;
  position: absolute;
  right: 10px;
  top: 10px;
}
.dplayer-info-panel .dplayer-info-panel-item > span {
  display: inline-block;
  vertical-align: middle;
  line-height: 15px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.dplayer-info-panel .dplayer-info-panel-item-title {
  width: 100px;
  text-align: right;
  margin-right: 10px;
}
.dplayer-info-panel .dplayer-info-panel-item-data {
  width: 260px;
}
`, ".dplayer {\n    position: relative;\n    overflow: hidden;\n    user-select: none;\n    line-height: 1;\n\n    * {\n        box-sizing: content-box;\n    }\n\n    svg {\n        width: 100%;\n        height: 100%;\n\n        path,\n        circle {\n            fill: #fff;\n        }\n    }\n\n    &:-webkit-full-screen {\n        width: 100%;\n        height: 100%;\n        background: #000;\n        position: fixed;\n        z-index: 100000;\n        left: 0;\n        top: 0;\n        margin: 0;\n        padding: 0;\n        transform: translate(0, 0);\n        \n    }\n\n    &.dplayer-no-danmaku {\n        .dplayer-controller .dplayer-icons .dplayer-setting .dplayer-setting-box {\n            .dplayer-setting-showdan,\n            .dplayer-setting-danmaku,\n            .dplayer-setting-danunlimit {\n                display: none;\n            }\n        }\n\n        .dplayer-controller .dplayer-icons .dplayer-comment {\n            display: none;\n        }\n\n        .dplayer-danmaku {\n            display: none;\n        }\n    }\n\n    &.dplayer-live {\n        .dplayer-time {\n            display: none;\n        }\n        .dplayer-bar-wrap {\n            display: none;\n        }\n        .dplayer-setting-speed {\n            display: none;\n        }\n        .dplayer-setting-loop {\n            display: none;\n        }\n\n        &.dplayer-no-danmaku {\n            .dplayer-setting {\n                display: none;\n            }\n        }\n    }\n\n    &.dplayer-arrow {\n        .dplayer-danmaku {\n            font-size: 18px;\n        }\n        .dplayer-icon {\n            margin: 0 -3px;\n        }\n    }\n\n    &.dplayer-playing {\n        .dplayer-danmaku .dplayer-danmaku-move {\n            animation-play-state: running;\n        }\n\n        @media (min-width: 900px) {\n            .dplayer-controller-mask {\n                opacity: 0;\n            }\n            .dplayer-controller {\n                opacity: 0;\n            }\n\n            &:hover {\n                .dplayer-controller-mask {\n                    opacity: 1;\n                }\n                .dplayer-controller {\n                    opacity: 1;\n                }\n            }\n        }\n    }\n\n    &.dplayer-loading {\n        .dplayer-bezel .diplayer-loading-icon {\n            display: block;\n        }\n    }\n\n    &.dplayer-loading,\n    &.dplayer-paused {\n        .dplayer-danmaku,\n        .dplayer-danmaku-move {\n            animation-play-state: paused;\n        }\n    }\n\n    &.dplayer-hide-controller {\n        cursor: none;\n\n        .dplayer-controller-mask {\n            opacity: 0;\n            transform: translateY(100%);\n        }\n        .dplayer-controller {\n            opacity: 0;\n            transform: translateY(100%);\n        }\n    }\n    &.dplayer-show-controller {\n        .dplayer-controller-mask {\n            opacity: 1;\n        }\n        .dplayer-controller {\n            opacity: 1;\n        }\n    }\n    &.dplayer-fulled {\n        position: fixed;\n        z-index: 100000;\n        left: 0;\n        top: 0;\n        width: 100% !important;\n        height: 100% !important;\n    }\n    &.dplayer-mobile {\n        .dplayer-controller .dplayer-icons {\n            .dplayer-volume,\n            .dplayer-camera-icon,\n            .dplayer-airplay-icon,\n            .dplayer-chromecast-icon,\n            .dplayer-play-icon {\n                display: none;\n            }\n            .dplayer-full .dplayer-full-in-icon {\n                position: static;\n                display: inline-block;\n            }\n        }\n\n        .dplayer-bar-time {\n            display: none;\n        }\n\n        &.dplayer-hide-controller {\n            .dplayer-mobile-play {\n                display: none;\n            }\n        }\n\n        .dplayer-mobile-play {\n            display: block;\n        }\n    }\n}\n\n// To hide scroll bar, apply this class to <body>\n.dplayer-web-fullscreen-fix {\n    position: fixed;\n    top: 0;\n    left: 0;\n    margin: 0;\n    padding: 0;\n}\n", `@import '../../node_modules/balloon-css/balloon.css';

[data-balloon]:before {
    display: none;
}

[data-balloon]:after {
    padding: 0.3em 0.7em;
    background: rgba(17, 17, 17, 0.7);
}

[data-balloon][data-balloon-pos="up"]:after {
    margin-bottom: 0;
}`, ".dplayer-bezel {\n    position: absolute;\n    left: 0;\n    right: 0;\n    top: 0;\n    bottom: 0;\n    font-size: 22px;\n    color: #fff;\n    pointer-events: none;\n    .dplayer-bezel-icon {\n        position: absolute;\n        top: 50%;\n        left: 50%;\n        margin: -26px 0 0 -26px;\n        height: 52px;\n        width: 52px;\n        padding: 12px;\n        box-sizing: border-box;\n        background: rgba(0, 0, 0, .5);\n        border-radius: 50%;\n        opacity: 0;\n        pointer-events: none;\n        &.dplayer-bezel-transition {\n            animation: bezel-hide .5s linear;\n        }\n        @keyframes bezel-hide {\n            from {\n                opacity: 1;\n                transform: scale(1);\n            }\n            to {\n                opacity: 0;\n                transform: scale(2);\n            }\n        }\n    }\n    .dplayer-danloading {\n        position: absolute;\n        top: 50%;\n        margin-top: -7px;\n        width: 100%;\n        text-align: center;\n        font-size: 14px;\n        line-height: 14px;\n        animation: my-face 5s infinite ease-in-out;\n    }\n    .diplayer-loading-icon {\n        display: none;\n        position: absolute;\n        top: 50%;\n        left: 50%;\n        margin: -18px 0 0 -18px;\n        height: 36px;\n        width: 36px;\n        pointer-events: none;\n        .diplayer-loading-hide {\n            display: none;\n        }\n        .diplayer-loading-dot {\n            animation: diplayer-loading-dot-fade .8s ease infinite;\n            opacity: 0;\n            transform-origin: 4px 4px;\n            each(range(7), {\n                &.diplayer-loading-dot-@{value} {\n                    animation-delay: (@value * 0.1s);\n                }\n            });\n        }\n        @keyframes diplayer-loading-dot-fade {\n            0% {\n                opacity: .7;\n                transform: scale(1.2, 1.2)\n            }\n            50% {\n                opacity: .25;\n                transform: scale(.9, .9)\n            }\n            to {\n                opacity: .25;\n                transform: scale(.85, .85)\n            }\n        }\n    }\n}", ".dplayer-notice-list{\n    position: absolute;\n    bottom: 60px;\n    left: 20px;\n\n    .dplayer-notice {\n        border-radius: 2px;\n        background: rgba(28, 28, 28, 0.9);\n        transition: all .3s ease-in-out;\n        overflow: hidden;\n        color: #fff;\n        display: table;\n        pointer-events: none;\n        animation: showNotice .3s ease 1 forwards;\n    }\n\n    .remove-notice{\n        animation: removeNotice .3s ease 1 forwards;\n    }\n}\n\n@keyframes showNotice {\n    from {\n        padding: 0;\n        font-size: 0;\n        margin-top: 0;\n    }\n    to {\n        padding: 7px 20px;\n        font-size: 14px;\n        margin-top: 5px;\n    }\n}\n\n@keyframes removeNotice {\n    0%{\n        padding: 7px 20px;\n        font-size: 14px;\n        margin-top: 5px;\n    }\n    20%{\n        font-size: 12px;\n    }\n    21%{\n        font-size: 0;\n        padding: 7px 10px;\n    }\n    100%{\n        padding: 0;\n        margin-top: 0;\n        font-size: 0;\n    }\n}\n", `.dplayer-controller-mask {
    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAADGCAYAAAAT+OqFAAAAdklEQVQoz42QQQ7AIAgEF/T/D+kbq/RWAlnQyyazA4aoAB4FsBSA/bFjuF1EOL7VbrIrBuusmrt4ZZORfb6ehbWdnRHEIiITaEUKa5EJqUakRSaEYBJSCY2dEstQY7AuxahwXFrvZmWl2rh4JZ07z9dLtesfNj5q0FU3A5ObbwAAAABJRU5ErkJggg==) repeat-x bottom;
    height: 98px;
    width: 100%;
    position: absolute;
    bottom: 0;
    transition: all 0.3s ease;
}

.dplayer-controller {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 41px;
    padding: 0 20px;
    user-select: none;
    transition: all 0.3s ease;
    &.dplayer-controller-comment {
        .dplayer-icons {
            display: none;
        }
        .dplayer-icons.dplayer-comment-box {
            display: block;
        }
    }
    .dplayer-bar-wrap {
        padding: 5px 0;
        cursor: pointer;
        position: absolute;
        bottom: 33px;
        width: calc(100% - 40px);
        height: 3px;
        &:hover {
            .dplayer-bar .dplayer-played .dplayer-thumb {
                transform: scale(1);
            }
            .dplayer-highlight {
                display: block;
                width: 8px;
                transform: translateX(-4px);
                top: 4px;
                height: 40%;
            }
        }
        .dplayer-highlight {
            z-index: 12;
            position: absolute;
            top: 5px;
            width: 6px;
            height: 20%;
            border-radius: 6px;
            background-color: #fff;
            text-align: center;
            transform: translateX(-3px);
            transition: all .2s ease-in-out;
            &:hover {
                .dplayer-highlight-text {
                    display: block;
                }
                &~.dplayer-bar-preview {
                    opacity: 0;
                }
                &~.dplayer-bar-time {
                    opacity: 0;
                }
            }
            .dplayer-highlight-text {
                display: none;
                position: absolute;
                left: 50%;
                top: -24px;
                padding: 5px 8px;
                background-color: rgba(0, 0, 0, .62);
                color: #fff;
                border-radius: 4px;
                font-size: 12px;
                white-space: nowrap;
                transform: translateX(-50%);
            }
        }
        .dplayer-bar-preview {
            position: absolute;
            background: #fff;
            pointer-events: none;
            display: none;
            background-size: 16000px 100%;
        }
        .dplayer-bar-preview-canvas {
            position: absolute;
            width: 100%;
            height: 100%;
            z-index: 1;
            pointer-events: none;
        }
        .dplayer-bar-time {
            &.hidden {
                opacity: 0;
            }
            position: absolute;
            left: 0px;
            top: -20px;
            border-radius: 4px;
            padding: 5px 7px;
            background-color: rgba(0, 0, 0, 0.62);
            color: #fff;
            font-size: 12px;
            text-align: center;
            opacity: 1;
            transition: opacity .1s ease-in-out;
            word-wrap: normal;
            word-break: normal;
            z-index: 2;
            pointer-events: none;
        }
        .dplayer-bar {
            position: relative;
            height: 3px;
            width: 100%;
            background: rgba(255, 255, 255, .2);
            cursor: pointer;
            .dplayer-loaded {
                position: absolute;
                left: 0;
                top: 0;
                bottom: 0;
                background: rgba(255, 255, 255, .4);
                height: 3px;
                transition: all 0.5s ease;
                will-change: width;
            }
            .dplayer-played {
                position: absolute;
                left: 0;
                top: 0;
                bottom: 0;
                height: 3px;
                will-change: width;
                .dplayer-thumb {
                    position: absolute;
                    top: 0;
                    right: 5px;
                    margin-top: -4px;
                    margin-right: -10px;
                    height: 11px;
                    width: 11px;
                    border-radius: 50%;
                    cursor: pointer;
                    transition: all .3s ease-in-out;
                    transform: scale(0);
                }
            }
        }
    }
    .dplayer-icons {
        height: 38px;
        position: absolute;
        bottom: 0;
        &.dplayer-comment-box {
            display: none;
            position: absolute;
            transition: all .3s ease-in-out;
            z-index: 2;
            height: 38px;
            bottom: 0;
            left: 20px;
            right: 20px;
            color: #fff;
            .dplayer-icon {
                padding: 7px;
            }
            .dplayer-comment-setting-icon {
                position: absolute;
                left: 0;
                top: 0;
            }
            .dplayer-send-icon {
                position: absolute;
                right: 0;
                top: 0;
            }
            .dplayer-comment-setting-box {
                position: absolute;
                background: rgba(28, 28, 28, 0.9);
                bottom: 41px;
                left: 0;
                box-shadow: 0 0 25px rgba(0, 0, 0, .3);
                border-radius: 4px;
                padding: 10px 10px 16px;
                font-size: 14px;
                width: 204px;
                transition: all .3s ease-in-out;
                transform: scale(0);
                &.dplayer-comment-setting-open {
                    transform: scale(1);
                }
                input[type=radio] {
                    display: none;
                }
                label {
                    cursor: pointer;
                }
                .dplayer-comment-setting-title {
                    font-size: 13px;
                    color: #fff;
                    line-height: 30px;
                }
                .dplayer-comment-setting-type {
                    font-size: 0;
                    .dplayer-comment-setting-title {
                        margin-bottom: 6px;
                    }
                    label {
                        &:nth-child(2) {
                            span {
                                border-radius: 4px 0 0 4px;
                            }
                        }
                        &:nth-child(4) {
                            span {
                                border-radius: 0 4px 4px 0;
                            }
                        }
                    }
                    span {
                        width: 33%;
                        padding: 4px 6px;
                        line-height: 16px;
                        display: inline-block;
                        font-size: 12px;
                        color: #fff;
                        border: 1px solid #fff;
                        margin-right: -1px;
                        box-sizing: border-box;
                        text-align: center;
                        cursor: pointer;
                    }
                    input:checked+span {
                        background: #E4E4E6;
                        color: #1c1c1c;
                    }
                }
                .dplayer-comment-setting-color {
                    font-size: 0;
                    label {
                        font-size: 0;
                        padding: 6px;
                        display: inline-block;
                    }
                    span {
                        width: 22px;
                        height: 22px;
                        display: inline-block;
                        border-radius: 50%;
                        box-sizing: border-box;
                        cursor: pointer;
                        &:hover {
                            animation: my-face 5s infinite ease-in-out;
                        }
                    }
                }
            }
            .dplayer-comment-input {
                outline: none;
                border: none;
                padding: 8px 31px;
                font-size: 14px;
                line-height: 18px;
                text-align: center;
                border-radius: 4px;
                background: none;
                margin: 0;
                height: 100%;
                box-sizing: border-box;
                width: 100%;
                color: #fff;
                &::placeholder {
                    color: #fff;
                    opacity: 0.8;
                }
                &::-ms-clear {
                    display: none;
                }
            }
        }
        &.dplayer-icons-left {
            .dplayer-icon {
                padding: 7px;
            }
        }
        &.dplayer-icons-right {
            right: 20px;
            .dplayer-icon {
                padding: 8px;
            }
        }
        .dplayer-time,
        .dplayer-live-badge {
            line-height: 38px;
            color: #eee;
            text-shadow: 0 0 2px rgba(0, 0, 0, .5);
            vertical-align: middle;
            font-size: 13px;
            cursor: default;
        }
        .dplayer-live-dot {
            display: inline-block;
            width: 6px;
            height: 6px;
            vertical-align: 4%;
            margin-right: 5px;
            content: '';
            border-radius: 6px;
        }
        .dplayer-icon {
            width: 40px;
            height: 100%;
            border: none;
            background-color: transparent;
            outline: none;
            cursor: pointer;
            vertical-align: middle;
            box-sizing: border-box;
            display: inline-block;
            .dplayer-icon-content {
                transition: all .2s ease-in-out;
                opacity: .8;
            }
            &:hover {
                .dplayer-icon-content {
                    opacity: 1;
                }
            }
            &.dplayer-quality-icon {
                color: #fff;
                width: auto;
                line-height: 22px;
                font-size: 14px;
            }
            &.dplayer-comment-icon {
                padding: 10px 9px 9px;
            }
            &.dplayer-setting-icon {
                padding-top: 8.5px;
            }
            &.dplayer-volume-icon {
                width: 43px;
            }
        }
        .dplayer-volume {
            position: relative;
            display: inline-block;
            cursor: pointer;
            height: 100%;
            &:hover {
                .dplayer-volume-bar-wrap .dplayer-volume-bar {
                    width: 45px;
                }
                .dplayer-volume-bar-wrap .dplayer-volume-bar .dplayer-volume-bar-inner .dplayer-thumb {
                    transform: scale(1);
                }
            }
            &.dplayer-volume-active {
                .dplayer-volume-bar-wrap .dplayer-volume-bar {
                    width: 45px;
                }
                .dplayer-volume-bar-wrap .dplayer-volume-bar .dplayer-volume-bar-inner .dplayer-thumb {
                    transform: scale(1);
                }
            }
            .dplayer-volume-bar-wrap {
                display: inline-block;
                margin: 0 10px 0 -5px;
                vertical-align: middle;
                height: 100%;
                .dplayer-volume-bar {
                    position: relative;
                    top: 17px;
                    width: 0;
                    height: 3px;
                    background: #aaa;
                    transition: all 0.3s ease-in-out;
                    .dplayer-volume-bar-inner {
                        position: absolute;
                        bottom: 0;
                        left: 0;
                        height: 100%;
                        transition: all 0.1s ease;
                        will-change: width;
                        .dplayer-thumb {
                            position: absolute;
                            top: 0;
                            right: 5px;
                            margin-top: -4px;
                            margin-right: -10px;
                            height: 11px;
                            width: 11px;
                            border-radius: 50%;
                            cursor: pointer;
                            transition: all .3s ease-in-out;
                            transform: scale(0);
                        }
                    }
                }
            }
        }
        .dplayer-subtitle-btn {
            display: inline-block;
            height: 100%;
        }
        .dplayer-subtitles {
            display: inline-block;
            height: 100%;
            .dplayer-subtitles-box {
                position: absolute;
                right: 0;
                bottom: 50px;
                transform: scale(0);
                width: fit-content;
                max-width: 240px;
                min-width: 120px;
                border-radius: 2px;
                background: rgba(28, 28, 28, 0.9);
                padding: 7px 0;
                transition: all .3s ease-in-out;
                overflow: auto;
                z-index: 2;
                &.dplayer-subtitles-panel {
                    display: block;
                }
                &.dplayer-subtitles-box-open {
                    transform: scale(1);
                }
            }
            .dplayer-subtitles-item {
                height: 30px;
                padding: 5px 10px;
                box-sizing: border-box;
                cursor: pointer;
                position: relative;
                &:hover {
                    background-color: rgba(255, 255, 255, .1);
                }
            }
        }
        .dplayer-setting {
            display: inline-block;
            height: 100%;
            .dplayer-setting-box {
                position: absolute;
                right: 0;
                bottom: 50px;
                transform: scale(0);
                width: 150px;
                border-radius: 2px;
                background: rgba(28, 28, 28, 0.9);
                padding: 7px 0;
                transition: all .3s ease-in-out;
                overflow: hidden;
                z-index: 2;
                &>div {
                    display: none;
                    &.dplayer-setting-origin-panel {
                        display: block;
                    }
                }
                &.dplayer-setting-box-open {
                    transform: scale(1);
                }
                &.dplayer-setting-box-narrow {
                    width: 70px;
                    text-align: center;
                }
                &.dplayer-setting-box-speed {
                    .dplayer-setting-origin-panel {
                        display: none;
                    }
                    .dplayer-setting-speed-panel {
                        display: block;
                    }
                }
            }
            .dplayer-setting-item,
            .dplayer-setting-speed-item {
                height: 30px;
                padding: 5px 10px;
                box-sizing: border-box;
                cursor: pointer;
                position: relative;
                &:hover {
                    background-color: rgba(255, 255, 255, .1);
                }
            }
            .dplayer-setting-danmaku {
                padding: 5px 0;
                .dplayer-label {
                    padding: 0 10px;
                    display: inline;
                }
                &:hover {
                    .dplayer-label {
                        display: none;
                    }
                    .dplayer-danmaku-bar-wrap {
                        display: inline-block;
                    }
                }
                &.dplayer-setting-danmaku-active {
                    .dplayer-label {
                        display: none;
                    }
                    .dplayer-danmaku-bar-wrap {
                        display: inline-block;
                    }
                }
                .dplayer-danmaku-bar-wrap {
                    padding: 0 10px;
                    box-sizing: border-box;
                    display: none;
                    vertical-align: middle;
                    height: 100%;
                    width: 100%;
                    .dplayer-danmaku-bar {
                        position: relative;
                        top: 8.5px;
                        width: 100%;
                        height: 3px;
                        background: #fff;
                        transition: all 0.3s ease-in-out;
                        .dplayer-danmaku-bar-inner {
                            position: absolute;
                            bottom: 0;
                            left: 0;
                            height: 100%;
                            transition: all 0.1s ease;
                            background: #aaa;
                            will-change: width;
                            .dplayer-thumb {
                                position: absolute;
                                top: 0;
                                right: 5px;
                                margin-top: -4px;
                                margin-right: -10px;
                                height: 11px;
                                width: 11px;
                                border-radius: 50%;
                                cursor: pointer;
                                transition: all .3s ease-in-out;
                                background: #aaa;
                            }
                        }
                    }
                }
            }
        }
        .dplayer-full {
            display: inline-block;
            height: 100%;
            position: relative;
            &:hover {
                .dplayer-full-in-icon {
                    display: block;
                }
            }
            .dplayer-full-in-icon {
                position: absolute;
                top: -30px;
                z-index: 1;
                display: none;
            }
        }
        .dplayer-quality {
            position: relative;
            display: inline-block;
            height: 100%;
            z-index: 2;
            &:hover {
                .dplayer-quality-list {
                    display: block;
                }
                .dplayer-quality-mask {
                    display: block;
                }
            }
            .dplayer-quality-mask {
                display: none;
                position: absolute;
                bottom: 38px;
                left: -18px;
                width: 80px;
                padding-bottom: 12px;
            }
            .dplayer-quality-list {
                display: none;
                font-size: 12px;
                width: 80px;
                border-radius: 2px;
                background: rgba(28, 28, 28, 0.9);
                padding: 5px 0;
                transition: all .3s ease-in-out;
                overflow: hidden;
                color: #fff;
                text-align: center;
            }
            .dplayer-quality-item {
                height: 25px;
                box-sizing: border-box;
                cursor: pointer;
                line-height: 25px;
                &:hover {
                    background-color: rgba(255, 255, 255, .1);
                }
            }
        }
        .dplayer-comment {
            display: inline-block;
            height: 100%;
        }
        .dplayer-label {
            color: #eee;
            font-size: 13px;
            display: inline-block;
            vertical-align: middle;
            white-space: nowrap;
        }
        .dplayer-toggle {
            width: 32px;
            height: 20px;
            text-align: center;
            font-size: 0;
            vertical-align: middle;
            position: absolute;
            top: 5px;
            right: 10px;
            input {
                max-height: 0;
                max-width: 0;
                display: none;
            }
            input+label {
                display: inline-block;
                position: relative;
                box-shadow: rgb(223, 223, 223) 0 0 0 0 inset;
                border: 1px solid rgb(223, 223, 223);
                height: 20px;
                width: 32px;
                border-radius: 10px;
                box-sizing: border-box;
                cursor: pointer;
                transition: .2s ease-in-out;
            }
            input+label:before {
                content: "";
                position: absolute;
                display: block;
                height: 18px;
                width: 18px;
                top: 0;
                left: 0;
                border-radius: 15px;
                transition: .2s ease-in-out;
            }
            input+label:after {
                content: "";
                position: absolute;
                display: block;
                left: 0;
                top: 0;
                border-radius: 15px;
                background: #fff;
                transition: .2s ease-in-out;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
                height: 18px;
                width: 18px;
            }
            input:checked+label {
                border-color: rgba(255, 255, 255, 0.5);
            }
            input:checked+label:before {
                width: 30px;
                background: rgba(255, 255, 255, 0.5);
            }
            input:checked+label:after {
                left: 12px;
            }
        }
    }
}

.dplayer-mobile-play {
    display: none;
    width: 50px;
    height: 50px;
    border: none;
    background-color: transparent;
    outline: none;
    cursor: pointer;
    box-sizing: border-box;
    position: absolute;
    bottom: 0;
    opacity: 0.8;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}`, ".dplayer-danmaku {\n    position: absolute;\n    left: 0;\n    right: 0;\n    top: 0;\n    bottom: 0;\n    font-size: 22px;\n    color: #fff;\n    .dplayer-danmaku-item {\n        display: inline-block;\n        pointer-events: none;\n        user-select: none;\n        cursor: default;\n        white-space: nowrap;\n        text-shadow: .5px .5px .5px rgba(0, 0, 0, .5);\n        &--demo {\n            position: absolute;\n            visibility: hidden;\n        }\n    }\n    .dplayer-danmaku-right {\n        position: absolute;\n        right: 0;\n        transform: translateX(100%);\n        &.dplayer-danmaku-move {\n            will-change: transform;\n            animation-name: 'danmaku';\n            animation-timing-function: linear;\n            animation-play-state: paused;\n        }\n    }\n    @keyframes danmaku {\n        from {\n            transform: translateX(100%);\n        }\n    }\n    .dplayer-danmaku-top,\n    .dplayer-danmaku-bottom {\n        position: absolute;\n        width: 100%;\n        text-align: center;\n        visibility: hidden;\n        &.dplayer-danmaku-move {\n            will-change: visibility;\n            animation-name: 'danmaku-center';\n            animation-timing-function: linear;\n            animation-play-state: paused;\n        }\n    }\n    @keyframes danmaku-center {\n        from {\n            visibility: visible;\n        }\n        to {\n            visibility: visible;\n        }\n    }\n}", ".dplayer-logo {\n    pointer-events: none;\n    position: absolute;\n    left: 20px;\n    top: 20px;\n    max-width: 50px;\n    max-height: 50px;\n    img {\n        max-width: 100%;\n        max-height: 100%;\n        background: none;\n    }\n}", ".dplayer-menu {\n    position: absolute;\n    width: 170px;\n    border-radius: 2px;\n    background: rgba(28, 28, 28, 0.85);\n    padding: 5px 0;\n    overflow: hidden;\n    z-index: 3;\n    display: none;\n    &.dplayer-menu-show {\n        display: block;\n    }\n    .dplayer-menu-item {\n        height: 30px;\n        box-sizing: border-box;\n        cursor: pointer;\n        &:hover {\n            background-color: rgba(255, 255, 255, .1);\n        }\n        a {\n            display: inline-block;\n            padding: 0 10px;\n            line-height: 30px;\n            color: #eee;\n            font-size: 13px;\n            display: inline-block;\n            vertical-align: middle;\n            width: 100%;\n            box-sizing: border-box;\n            white-space: nowrap;\n            text-overflow: ellipsis;\n            overflow: hidden;\n            &:hover {\n                text-decoration: none;\n            }\n        }\n    }\n}", ".dplayer-subtitle {\n    position: absolute;\n    bottom: 40px;\n    width: 90%;\n    left: 5%;\n    text-align: center;\n    color: #fff;\n    text-shadow: 0.5px 0.5px 0.5px rgba(0, 0, 0, 0.5);\n    font-size: 20px;\n    &.dplayer-subtitle-hide {\n        display: none;\n    }\n}", ".dplayer-mask {\n    position: absolute;\n    top: 0;\n    bottom: 0;\n    left: 0;\n    right: 0;\n    z-index: 1;\n    display: none;\n    &.dplayer-mask-show {\n        display: block;\n    }\n}\n\n.dplayer-video-wrap {\n    position: relative;\n    background: #000;\n    font-size: 0;\n    width: 100%;\n    height: 100%;\n    .dplayer-video {\n        width: 100%;\n        height: 100%;\n        display: none;\n    }\n    .dplayer-video-current {\n        display: block;\n    }\n    .dplayer-video-prepare {\n        display: none;\n    }\n}", ".dplayer-info-panel {\n    position: absolute;\n    top: 10px;\n    left: 10px;\n    width: 400px;\n    background: rgba(28, 28, 28, 0.8);\n    padding: 10px;\n    color: #fff;\n    font-size: 12px;\n    border-radius: 2px;\n\n    &-hide {\n        display: none;\n    }\n\n    .dplayer-info-panel-close {\n        cursor: pointer;\n        position: absolute;\n        right: 10px;\n        top: 10px;\n    }\n\n    .dplayer-info-panel-item {\n        & > span {\n            display: inline-block;\n            vertical-align: middle;\n            line-height: 15px;\n            white-space: nowrap;\n            text-overflow: ellipsis;\n            overflow: hidden;\n        }\n    }\n\n    .dplayer-info-panel-item-title {\n        width: 100px;\n        text-align: right;\n        margin-right: 10px;\n    }\n    \n    .dplayer-info-panel-item-data {\n        width: 260px;\n    }\n}"],
            sourceRoot: ""
          }]);
          const u = c;
        },
        856: (n2) => {
          "use strict";
          var e2 = [];
          function t3(n3) {
            for (var t4 = -1, a3 = 0; a3 < e2.length; a3++) if (e2[a3].identifier === n3) {
              t4 = a3;
              break;
            }
            return t4;
          }
          function a2(n3, a3) {
            for (var r2 = {}, i = [], l = 0; l < n3.length; l++) {
              var s = n3[l], p = a3.base ? s[0] + a3.base : s[0], d2 = r2[p] || 0, c = "".concat(p, " ").concat(d2);
              r2[p] = d2 + 1;
              var A = t3(c), u = {
                css: s[1],
                media: s[2],
                sourceMap: s[3],
                supports: s[4],
                layer: s[5]
              };
              if (-1 !== A) e2[A].references++, e2[A].updater(u);
              else {
                var y = o(u, a3);
                a3.byIndex = l, e2.splice(l, 0, {
                  identifier: c,
                  updater: y,
                  references: 1
                });
              }
              i.push(c);
            }
            return i;
          }
          function o(n3, e3) {
            var t4 = e3.domAPI(e3);
            return t4.update(n3), function(e4) {
              if (e4) {
                if (e4.css === n3.css && e4.media === n3.media && e4.sourceMap === n3.sourceMap && e4.supports === n3.supports && e4.layer === n3.layer) return;
                t4.update(n3 = e4);
              } else t4.remove();
            };
          }
          n2.exports = function(n3, o2) {
            var r2 = a2(n3 = n3 || [], o2 = o2 || {});
            return function(n4) {
              n4 = n4 || [];
              for (var i = 0; i < r2.length; i++) {
                var l = t3(r2[i]);
                e2[l].references--;
              }
              for (var s = a2(n4, o2), p = 0; p < r2.length; p++) {
                var d2 = t3(r2[p]);
                0 === e2[d2].references && (e2[d2].updater(), e2.splice(d2, 1));
              }
              r2 = s;
            };
          };
        },
        370: (n2) => {
          "use strict";
          var e2 = {};
          n2.exports = function(n3, t3) {
            var a2 = function(n4) {
              if (void 0 === e2[n4]) {
                var t4 = document.querySelector(n4);
                if (window.HTMLIFrameElement && t4 instanceof window.HTMLIFrameElement) try {
                  t4 = t4.contentDocument.head;
                } catch (n5) {
                  t4 = null;
                }
                e2[n4] = t4;
              }
              return e2[n4];
            }(n3);
            if (!a2) throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
            a2.appendChild(t3);
          };
        },
        278: (n2) => {
          "use strict";
          n2.exports = function(n3) {
            var e2 = document.createElement("style");
            return n3.setAttributes(e2, n3.attributes), n3.insert(e2, n3.options), e2;
          };
        },
        458: (n2, e2, t3) => {
          "use strict";
          n2.exports = function(n3) {
            var e3 = t3.nc;
            e3 && n3.setAttribute("nonce", e3);
          };
        },
        470: (n2) => {
          "use strict";
          n2.exports = function(n3) {
            var e2 = n3.insertStyleElement(n3);
            return {
              update: function(t3) {
                !function(n4, e3, t4) {
                  var a2 = "";
                  t4.supports && (a2 += "@supports (".concat(t4.supports, ") {")), t4.media && (a2 += "@media ".concat(t4.media, " {"));
                  var o = void 0 !== t4.layer;
                  o && (a2 += "@layer".concat(t4.layer.length > 0 ? " ".concat(t4.layer) : "", " {")), a2 += t4.css, o && (a2 += "}"), t4.media && (a2 += "}"), t4.supports && (a2 += "}");
                  var r2 = t4.sourceMap;
                  r2 && "undefined" != typeof btoa && (a2 += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(r2)))), " */")), e3.styleTagTransform(a2, n4, e3.options);
                }(e2, n3, t3);
              },
              remove: function() {
                !function(n4) {
                  if (null === n4.parentNode) return false;
                  n4.parentNode.removeChild(n4);
                }(e2);
              }
            };
          };
        },
        488: (n2) => {
          "use strict";
          n2.exports = function(n3, e2) {
            if (e2.styleSheet) e2.styleSheet.cssText = n3;
            else {
              for (; e2.firstChild; ) e2.removeChild(e2.firstChild);
              e2.appendChild(document.createTextNode(n3));
            }
          };
        },
        251: (n2) => {
          n2.exports = '<svg viewBox="0 0 288 288" xmlns="http://www.w3.org/2000/svg"><path d="M288 90v96c0 20-16 36-36 36h-10c-16 0-16-24 0-24h10c7 0 12-5 12-12V90c0-7-5-12-12-12H36c-7 0-12 5-12 12v96c0 7 5 12 12 12h10c16 0 16 24 0 24H36c-20 0-36-16-36-36V90c0-20 16-36 36-36h216c20 0 36 16 36 36zm-120 62l48 68c14 20 1 38-20 38H92c-21 0-34-18-20-38l48-68c13-18 35-18 48 0z"></path></svg>';
        },
        113: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 32"><path d="M16 23c-3.309 0-6-2.691-6-6s2.691-6 6-6 6 2.691 6 6-2.691 6-6 6zM16 13c-2.206 0-4 1.794-4 4s1.794 4 4 4c2.206 0 4-1.794 4-4s-1.794-4-4-4zM27 28h-22c-1.654 0-3-1.346-3-3v-16c0-1.654 1.346-3 3-3h3c0.552 0 1 0.448 1 1s-0.448 1-1 1h-3c-0.551 0-1 0.449-1 1v16c0 0.552 0.449 1 1 1h22c0.552 0 1-0.448 1-1v-16c0-0.551-0.448-1-1-1h-11c-0.552 0-1-0.448-1-1s0.448-1 1-1h11c1.654 0 3 1.346 3 3v16c0 1.654-1.346 3-3 3zM24 10.5c0 0.828 0.672 1.5 1.5 1.5s1.5-0.672 1.5-1.5c0-0.828-0.672-1.5-1.5-1.5s-1.5 0.672-1.5 1.5zM15 4c0 0.552-0.448 1-1 1h-4c-0.552 0-1-0.448-1-1v0c0-0.552 0.448-1 1-1h4c0.552 0 1 0.448 1 1v0z"></path></svg>';
        },
        193: (n2) => {
          n2.exports = '<svg aria-hidden="true" focusable="false" data-prefix="fab" data-icon="chromecast" class="svg-inline--fa fa-chromecast fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M447.8,64H64c-23.6,0-42.7,19.1-42.7,42.7v63.9H64v-63.9h383.8v298.6H298.6V448H448c23.6,0,42.7-19.1,42.7-42.7V106.7 C490.7,83.1,471.4,64,447.8,64z M21.3,383.6L21.3,383.6l0,63.9h63.9C85.2,412.2,56.6,383.6,21.3,383.6L21.3,383.6z M21.3,298.6V341 c58.9,0,106.6,48.1,106.6,107h42.7C170.7,365.6,103.7,298.7,21.3,298.6z M213.4,448h42.7c-0.5-129.5-105.3-234.3-234.8-234.6l0,42.4 C127.3,255.6,213.3,342,213.4,448z"></path></svg>';
        },
        338: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 32"><path d="M27.090 0.131h-22.731c-2.354 0-4.262 1.839-4.262 4.109v16.401c0 2.269 1.908 4.109 4.262 4.109h4.262v-2.706h8.469l-8.853 8.135 1.579 1.451 7.487-6.88h9.787c2.353 0 4.262-1.84 4.262-4.109v-16.401c0-2.27-1.909-4.109-4.262-4.109v0zM28.511 19.304c0 1.512-1.272 2.738-2.841 2.738h-8.425l-0.076-0.070-0.076 0.070h-11.311c-1.569 0-2.841-1.226-2.841-2.738v-13.696c0-1.513 1.272-2.739 2.841-2.739h19.889c1.569 0 2.841-0.142 2.841 1.37v15.064z"></path></svg>';
        },
        807: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 32"><path d="M27.128 0.38h-22.553c-2.336 0-4.229 1.825-4.229 4.076v16.273c0 2.251 1.893 4.076 4.229 4.076h4.229v-2.685h8.403l-8.784 8.072 1.566 1.44 7.429-6.827h9.71c2.335 0 4.229-1.825 4.229-4.076v-16.273c0-2.252-1.894-4.076-4.229-4.076zM28.538 19.403c0 1.5-1.262 2.717-2.819 2.717h-8.36l-0.076-0.070-0.076 0.070h-11.223c-1.557 0-2.819-1.217-2.819-2.717v-13.589c0-1.501 1.262-2.718 2.819-2.718h19.734c1.557 0 2.819-0.141 2.819 1.359v14.947zM9.206 10.557c-1.222 0-2.215 0.911-2.215 2.036s0.992 2.035 2.215 2.035c1.224 0 2.216-0.911 2.216-2.035s-0.992-2.036-2.216-2.036zM22.496 10.557c-1.224 0-2.215 0.911-2.215 2.036s0.991 2.035 2.215 2.035c1.224 0 2.215-0.911 2.215-2.035s-0.991-2.036-2.215-2.036zM15.852 10.557c-1.224 0-2.215 0.911-2.215 2.036s0.991 2.035 2.215 2.035c1.222 0 2.215-0.911 2.215-2.035s-0.992-2.036-2.215-2.036z"></path></svg>';
        },
        300: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 33"><path d="M24.965 24.38h-18.132c-1.366 0-2.478-1.113-2.478-2.478v-11.806c0-1.364 1.111-2.478 2.478-2.478h18.132c1.366 0 2.478 1.113 2.478 2.478v11.806c0 1.364-1.11 2.478-2.478 2.478zM6.833 10.097v11.806h18.134l-0.002-11.806h-18.132zM2.478 28.928h5.952c0.684 0 1.238-0.554 1.238-1.239 0-0.684-0.554-1.238-1.238-1.238h-5.952v-5.802c0-0.684-0.554-1.239-1.238-1.239s-1.239 0.556-1.239 1.239v5.802c0 1.365 1.111 2.478 2.478 2.478zM30.761 19.412c-0.684 0-1.238 0.554-1.238 1.238v5.801h-5.951c-0.686 0-1.239 0.554-1.239 1.238 0 0.686 0.554 1.239 1.239 1.239h5.951c1.366 0 2.478-1.111 2.478-2.478v-5.801c0-0.683-0.554-1.238-1.239-1.238zM0 5.55v5.802c0 0.683 0.554 1.238 1.238 1.238s1.238-0.555 1.238-1.238v-5.802h5.952c0.684 0 1.238-0.554 1.238-1.238s-0.554-1.238-1.238-1.238h-5.951c-1.366-0.001-2.478 1.111-2.478 2.476zM32 11.35v-5.801c0-1.365-1.11-2.478-2.478-2.478h-5.951c-0.686 0-1.239 0.554-1.239 1.238s0.554 1.238 1.239 1.238h5.951v5.801c0 0.683 0.554 1.237 1.238 1.237 0.686 0.002 1.239-0.553 1.239-1.236z"></path></svg>';
        },
        574: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 33"><path d="M6.667 28h-5.333c-0.8 0-1.333-0.533-1.333-1.333v-5.333c0-0.8 0.533-1.333 1.333-1.333s1.333 0.533 1.333 1.333v4h4c0.8 0 1.333 0.533 1.333 1.333s-0.533 1.333-1.333 1.333zM30.667 28h-5.333c-0.8 0-1.333-0.533-1.333-1.333s0.533-1.333 1.333-1.333h4v-4c0-0.8 0.533-1.333 1.333-1.333s1.333 0.533 1.333 1.333v5.333c0 0.8-0.533 1.333-1.333 1.333zM30.667 12c-0.8 0-1.333-0.533-1.333-1.333v-4h-4c-0.8 0-1.333-0.533-1.333-1.333s0.533-1.333 1.333-1.333h5.333c0.8 0 1.333 0.533 1.333 1.333v5.333c0 0.8-0.533 1.333-1.333 1.333zM1.333 12c-0.8 0-1.333-0.533-1.333-1.333v-5.333c0-0.8 0.533-1.333 1.333-1.333h5.333c0.8 0 1.333 0.533 1.333 1.333s-0.533 1.333-1.333 1.333h-4v4c0 0.8-0.533 1.333-1.333 1.333z"></path></svg>';
        },
        182: (n2) => {
          n2.exports = '<svg version="1.1" viewBox="0 0 22 22"><svg x="7" y="1"><circle class="diplayer-loading-dot diplayer-loading-dot-0" cx="4" cy="4" r="2"></circle></svg><svg x="11" y="3"><circle class="diplayer-loading-dot diplayer-loading-dot-1" cx="4" cy="4" r="2"></circle></svg><svg x="13" y="7"><circle class="diplayer-loading-dot diplayer-loading-dot-2" cx="4" cy="4" r="2"></circle></svg><svg x="11" y="11"><circle class="diplayer-loading-dot diplayer-loading-dot-3" cx="4" cy="4" r="2"></circle></svg><svg x="7" y="13"><circle class="diplayer-loading-dot diplayer-loading-dot-4" cx="4" cy="4" r="2"></circle></svg><svg x="3" y="11"><circle class="diplayer-loading-dot diplayer-loading-dot-5" cx="4" cy="4" r="2"></circle></svg><svg x="1" y="7"><circle class="diplayer-loading-dot diplayer-loading-dot-6" cx="4" cy="4" r="2"></circle></svg><svg x="3" y="3"><circle class="diplayer-loading-dot diplayer-loading-dot-7" cx="4" cy="4" r="2"></circle></svg></svg>';
        },
        965: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 32"><path d="M19.357 2.88c1.749 0 3.366 0.316 4.851 0.946 1.485 0.632 2.768 1.474 3.845 2.533s1.922 2.279 2.532 3.661c0.611 1.383 0.915 2.829 0.915 4.334 0 1.425-0.304 2.847-0.915 4.271-0.611 1.425-1.587 2.767-2.928 4.028-0.855 0.813-1.811 1.607-2.869 2.38s-2.136 1.465-3.233 2.075c-1.099 0.61-2.198 1.098-3.296 1.465-1.098 0.366-2.115 0.549-3.051 0.549-1.343 0-2.441-0.438-3.296-1.311-0.854-0.876-1.281-2.41-1.281-4.608 0-0.366 0.020-0.773 0.060-1.221s0.062-0.895 0.062-1.343c0-0.773-0.183-1.353-0.55-1.738-0.366-0.387-0.793-0.58-1.281-0.58-0.652 0-1.21 0.295-1.678 0.886s-0.926 1.23-1.373 1.921c-0.447 0.693-0.905 1.334-1.372 1.923s-1.028 0.886-1.679 0.886c-0.529 0-1.048-0.427-1.556-1.282s-0.763-2.259-0.763-4.212c0-2.197 0.529-4.241 1.587-6.133s2.462-3.529 4.21-4.912c1.75-1.383 3.762-2.471 6.041-3.264 2.277-0.796 4.617-1.212 7.018-1.253zM7.334 15.817c0.569 0 1.047-0.204 1.434-0.611s0.579-0.875 0.579-1.404c0-0.569-0.193-1.047-0.579-1.434s-0.864-0.579-1.434-0.579c-0.529 0-0.987 0.193-1.373 0.579s-0.58 0.864-0.58 1.434c0 0.53 0.194 0.998 0.58 1.404 0.388 0.407 0.845 0.611 1.373 0.611zM12.216 11.79c0.691 0 1.292-0.254 1.8-0.763s0.762-1.107 0.762-1.8c0-0.732-0.255-1.343-0.762-1.831-0.509-0.489-1.109-0.732-1.8-0.732-0.732 0-1.342 0.244-1.831 0.732-0.488 0.488-0.732 1.098-0.732 1.831 0 0.693 0.244 1.292 0.732 1.8s1.099 0.763 1.831 0.763zM16.366 25.947c0.692 0 1.282-0.214 1.77-0.64s0.732-0.987 0.732-1.678-0.244-1.261-0.732-1.709c-0.489-0.448-1.078-0.671-1.77-0.671-0.65 0-1.21 0.223-1.678 0.671s-0.702 1.018-0.702 1.709c0 0.692 0.234 1.25 0.702 1.678s1.027 0.64 1.678 0.64zM19.113 9.592c0.651 0 1.129-0.203 1.433-0.611 0.305-0.406 0.459-0.874 0.459-1.404 0-0.488-0.154-0.947-0.459-1.373-0.304-0.427-0.782-0.641-1.433-0.641-0.529 0-1.008 0.193-1.434 0.58s-0.64 0.865-0.64 1.434c0 0.571 0.213 1.049 0.64 1.434 0.427 0.389 0.905 0.581 1.434 0.581zM24.848 12.826c0.57 0 1.067-0.213 1.495-0.64 0.427-0.427 0.64-0.947 0.64-1.556 0-0.57-0.214-1.068-0.64-1.495-0.428-0.427-0.927-0.64-1.495-0.64-0.611 0-1.129 0.213-1.555 0.64-0.428 0.427-0.642 0.926-0.642 1.495 0 0.611 0.213 1.129 0.642 1.556s0.947 0.64 1.555 0.64z"></path></svg>';
        },
        74: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 17 32"><path d="M14.080 4.8q2.88 0 2.88 2.048v18.24q0 2.112-2.88 2.112t-2.88-2.112v-18.24q0-2.048 2.88-2.048zM2.88 4.8q2.88 0 2.88 2.048v18.24q0 2.112-2.88 2.112t-2.88-2.112v-18.24q0-2.048 2.88-2.048z"></path></svg>';
        },
        730: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 16 32"><path d="M15.552 15.168q0.448 0.32 0.448 0.832 0 0.448-0.448 0.768l-13.696 8.512q-0.768 0.512-1.312 0.192t-0.544-1.28v-16.448q0-0.96 0.544-1.28t1.312 0.192z"></path></svg>';
        },
        428: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 32"><path d="M22 16l-10.105-10.6-1.895 1.987 8.211 8.613-8.211 8.612 1.895 1.988 8.211-8.613z"></path></svg>';
        },
        254: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 32"><path d="M13.725 30l3.9-5.325-3.9-1.125v6.45zM0 17.5l11.050 3.35 13.6-11.55-10.55 12.425 11.8 3.65 6.1-23.375-32 15.5z"></path></svg>';
        },
        934: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 28"><path d="M28.633 17.104c0.035 0.21 0.026 0.463-0.026 0.76s-0.14 0.598-0.262 0.904c-0.122 0.306-0.271 0.581-0.445 0.825s-0.367 0.419-0.576 0.524c-0.209 0.105-0.393 0.157-0.55 0.157s-0.332-0.035-0.524-0.105c-0.175-0.052-0.393-0.1-0.655-0.144s-0.528-0.052-0.799-0.026c-0.271 0.026-0.541 0.083-0.812 0.17s-0.502 0.236-0.694 0.445c-0.419 0.437-0.664 0.934-0.734 1.493s0.009 1.092 0.236 1.598c0.175 0.349 0.148 0.699-0.079 1.048-0.105 0.14-0.271 0.284-0.498 0.432s-0.476 0.284-0.747 0.406-0.555 0.218-0.851 0.288c-0.297 0.070-0.559 0.105-0.786 0.105-0.157 0-0.306-0.061-0.445-0.183s-0.236-0.253-0.288-0.393h-0.026c-0.192-0.541-0.52-1.009-0.982-1.402s-1-0.589-1.611-0.589c-0.594 0-1.131 0.197-1.611 0.589s-0.816 0.851-1.009 1.375c-0.087 0.21-0.218 0.362-0.393 0.458s-0.367 0.144-0.576 0.144c-0.244 0-0.52-0.044-0.825-0.131s-0.611-0.197-0.917-0.327c-0.306-0.131-0.581-0.284-0.825-0.458s-0.428-0.349-0.55-0.524c-0.087-0.122-0.135-0.266-0.144-0.432s0.057-0.397 0.197-0.694c0.192-0.402 0.266-0.86 0.223-1.375s-0.266-0.991-0.668-1.428c-0.244-0.262-0.541-0.432-0.891-0.511s-0.681-0.109-0.995-0.092c-0.367 0.017-0.742 0.087-1.127 0.21-0.244 0.070-0.489 0.052-0.734-0.052-0.192-0.070-0.371-0.231-0.537-0.485s-0.314-0.533-0.445-0.838c-0.131-0.306-0.231-0.62-0.301-0.943s-0.087-0.59-0.052-0.799c0.052-0.384 0.227-0.629 0.524-0.734 0.524-0.21 0.995-0.555 1.415-1.035s0.629-1.017 0.629-1.611c0-0.611-0.21-1.144-0.629-1.598s-0.891-0.786-1.415-0.996c-0.157-0.052-0.288-0.179-0.393-0.38s-0.157-0.406-0.157-0.616c0-0.227 0.035-0.48 0.105-0.76s0.162-0.55 0.275-0.812 0.244-0.502 0.393-0.72c0.148-0.218 0.31-0.38 0.485-0.485 0.14-0.087 0.275-0.122 0.406-0.105s0.275 0.052 0.432 0.105c0.524 0.21 1.070 0.275 1.637 0.197s1.070-0.327 1.506-0.747c0.21-0.209 0.362-0.467 0.458-0.773s0.157-0.607 0.183-0.904c0.026-0.297 0.026-0.568 0-0.812s-0.048-0.419-0.065-0.524c-0.035-0.105-0.066-0.227-0.092-0.367s-0.013-0.262 0.039-0.367c0.105-0.244 0.293-0.458 0.563-0.642s0.563-0.336 0.878-0.458c0.314-0.122 0.62-0.214 0.917-0.275s0.533-0.092 0.707-0.092c0.227 0 0.406 0.074 0.537 0.223s0.223 0.301 0.275 0.458c0.192 0.471 0.507 0.886 0.943 1.244s0.952 0.537 1.546 0.537c0.611 0 1.153-0.17 1.624-0.511s0.803-0.773 0.996-1.297c0.070-0.14 0.179-0.284 0.327-0.432s0.301-0.223 0.458-0.223c0.244 0 0.511 0.035 0.799 0.105s0.572 0.166 0.851 0.288c0.279 0.122 0.537 0.279 0.773 0.472s0.423 0.402 0.563 0.629c0.087 0.14 0.113 0.293 0.079 0.458s-0.070 0.284-0.105 0.354c-0.227 0.506-0.297 1.039-0.21 1.598s0.341 1.048 0.76 1.467c0.419 0.419 0.934 0.651 1.546 0.694s1.179-0.057 1.703-0.301c0.14-0.087 0.31-0.122 0.511-0.105s0.371 0.096 0.511 0.236c0.262 0.244 0.493 0.616 0.694 1.113s0.336 1 0.406 1.506c0.035 0.297-0.013 0.528-0.144 0.694s-0.266 0.275-0.406 0.327c-0.542 0.192-1.004 0.528-1.388 1.009s-0.576 1.026-0.576 1.637c0 0.594 0.162 1.113 0.485 1.559s0.747 0.764 1.27 0.956c0.122 0.070 0.227 0.14 0.314 0.21 0.192 0.157 0.323 0.358 0.393 0.602v0zM16.451 19.462c0.786 0 1.528-0.149 2.227-0.445s1.305-0.707 1.821-1.231c0.515-0.524 0.921-1.131 1.218-1.821s0.445-1.428 0.445-2.214c0-0.786-0.148-1.524-0.445-2.214s-0.703-1.292-1.218-1.808c-0.515-0.515-1.122-0.921-1.821-1.218s-1.441-0.445-2.227-0.445c-0.786 0-1.524 0.148-2.214 0.445s-1.292 0.703-1.808 1.218c-0.515 0.515-0.921 1.118-1.218 1.808s-0.445 1.428-0.445 2.214c0 0.786 0.149 1.524 0.445 2.214s0.703 1.297 1.218 1.821c0.515 0.524 1.118 0.934 1.808 1.231s1.428 0.445 2.214 0.445v0z"></path></svg>';
        },
        410: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 32"><path d="M26.667 5.333h-21.333c-0 0-0.001 0-0.001 0-1.472 0-2.666 1.194-2.666 2.666 0 0 0 0.001 0 0.001v-0 16c0 0 0 0.001 0 0.001 0 1.472 1.194 2.666 2.666 2.666 0 0 0.001 0 0.001 0h21.333c0 0 0.001 0 0.001 0 1.472 0 2.666-1.194 2.666-2.666 0-0 0-0.001 0-0.001v0-16c0-0 0-0.001 0-0.001 0-1.472-1.194-2.666-2.666-2.666-0 0-0.001 0-0.001 0h0zM5.333 16h5.333v2.667h-5.333v-2.667zM18.667 24h-13.333v-2.667h13.333v2.667zM26.667 24h-5.333v-2.667h5.333v2.667zM26.667 18.667h-13.333v-2.667h13.333v2.667z"></path></svg>';
        },
        644: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 21 32"><path d="M13.728 6.272v19.456q0 0.448-0.352 0.8t-0.8 0.32-0.8-0.32l-5.952-5.952h-4.672q-0.48 0-0.8-0.352t-0.352-0.8v-6.848q0-0.48 0.352-0.8t0.8-0.352h4.672l5.952-5.952q0.32-0.32 0.8-0.32t0.8 0.32 0.352 0.8zM20.576 16q0 1.344-0.768 2.528t-2.016 1.664q-0.16 0.096-0.448 0.096-0.448 0-0.8-0.32t-0.32-0.832q0-0.384 0.192-0.64t0.544-0.448 0.608-0.384 0.512-0.64 0.192-1.024-0.192-1.024-0.512-0.64-0.608-0.384-0.544-0.448-0.192-0.64q0-0.48 0.32-0.832t0.8-0.32q0.288 0 0.448 0.096 1.248 0.48 2.016 1.664t0.768 2.528z"></path></svg>';
        },
        324: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 21 32"><path d="M13.728 6.272v19.456q0 0.448-0.352 0.8t-0.8 0.32-0.8-0.32l-5.952-5.952h-4.672q-0.48 0-0.8-0.352t-0.352-0.8v-6.848q0-0.48 0.352-0.8t0.8-0.352h4.672l5.952-5.952q0.32-0.32 0.8-0.32t0.8 0.32 0.352 0.8z"></path></svg>';
        },
        437: (n2) => {
          n2.exports = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 21 32"><path d="M13.728 6.272v19.456q0 0.448-0.352 0.8t-0.8 0.32-0.8-0.32l-5.952-5.952h-4.672q-0.48 0-0.8-0.352t-0.352-0.8v-6.848q0-0.48 0.352-0.8t0.8-0.352h4.672l5.952-5.952q0.32-0.32 0.8-0.32t0.8 0.32 0.352 0.8zM20.576 16q0 1.344-0.768 2.528t-2.016 1.664q-0.16 0.096-0.448 0.096-0.448 0-0.8-0.32t-0.32-0.832q0-0.384 0.192-0.64t0.544-0.448 0.608-0.384 0.512-0.64 0.192-1.024-0.192-1.024-0.512-0.64-0.608-0.384-0.544-0.448-0.192-0.64q0-0.48 0.32-0.832t0.8-0.32q0.288 0 0.448 0.096 1.248 0.48 2.016 1.664t0.768 2.528zM25.152 16q0 2.72-1.536 5.056t-4 3.36q-0.256 0.096-0.448 0.096-0.48 0-0.832-0.352t-0.32-0.8q0-0.704 0.672-1.056 1.024-0.512 1.376-0.8 1.312-0.96 2.048-2.4t0.736-3.104-0.736-3.104-2.048-2.4q-0.352-0.288-1.376-0.8-0.672-0.352-0.672-1.056 0-0.448 0.32-0.8t0.8-0.352q0.224 0 0.48 0.096 2.496 1.056 4 3.36t1.536 5.056z"></path></svg>';
        },
        897: (n2, e2, t3) => {
          "use strict";
          var a2 = "undefined" != typeof self ? self : "undefined" != typeof window ? window : void 0 !== t3.g ? t3.g : {}, o = Object.create(a2), r2 = /["&'<>]/;
          function i(n3) {
            return "string" != typeof n3 && (n3 = null == n3 ? "" : "function" == typeof n3 ? i(n3.call(n3)) : JSON.stringify(n3)), n3;
          }
          o.$escape = function(n3) {
            return function(n4) {
              var e3 = "" + n4, t4 = r2.exec(e3);
              if (!t4) return n4;
              var a3 = "", o2 = void 0, i2 = void 0, l = void 0;
              for (o2 = t4.index, i2 = 0; o2 < e3.length; o2++) {
                switch (e3.charCodeAt(o2)) {
                  case 34:
                    l = "&#34;";
                    break;
                  case 38:
                    l = "&#38;";
                    break;
                  case 39:
                    l = "&#39;";
                    break;
                  case 60:
                    l = "&#60;";
                    break;
                  case 62:
                    l = "&#62;";
                    break;
                  default:
                    continue;
                }
                i2 !== o2 && (a3 += e3.substring(i2, o2)), i2 = o2 + 1, a3 += l;
              }
              return i2 !== o2 ? a3 + e3.substring(i2, o2) : a3;
            }(i(n3));
          }, o.$each = function(n3, e3) {
            if (Array.isArray(n3)) for (var t4 = 0, a3 = n3.length; t4 < a3; t4++) e3(n3[t4], t4);
            else for (var o2 in n3) e3(n3[o2], o2);
          }, n2.exports = o;
        },
        471: (n2, e2, t3) => {
          "use strict";
          n2.exports = t3(897);
        },
        352: (n2) => {
          "use strict";
          n2.exports = function(n3) {
            var e2 = [];
            return e2.toString = function() {
              return this.map(function(e3) {
                var t3 = "", a2 = void 0 !== e3[5];
                return e3[4] && (t3 += "@supports (".concat(e3[4], ") {")), e3[2] && (t3 += "@media ".concat(e3[2], " {")), a2 && (t3 += "@layer".concat(e3[5].length > 0 ? " ".concat(e3[5]) : "", " {")), t3 += n3(e3), a2 && (t3 += "}"), e3[2] && (t3 += "}"), e3[4] && (t3 += "}"), t3;
              }).join("");
            }, e2.i = function(n4, t3, a2, o, r2) {
              "string" == typeof n4 && (n4 = [[null, n4, void 0]]);
              var i = {};
              if (a2) for (var l = 0; l < this.length; l++) {
                var s = this[l][0];
                null != s && (i[s] = true);
              }
              for (var p = 0; p < n4.length; p++) {
                var d2 = [].concat(n4[p]);
                a2 && i[d2[0]] || (void 0 !== r2 && (void 0 === d2[5] || (d2[1] = "@layer".concat(d2[5].length > 0 ? " ".concat(d2[5]) : "", " {").concat(d2[1], "}")), d2[5] = r2), t3 && (d2[2] ? (d2[1] = "@media ".concat(d2[2], " {").concat(d2[1], "}"), d2[2] = t3) : d2[2] = t3), o && (d2[4] ? (d2[1] = "@supports (".concat(d2[4], ") {").concat(d2[1], "}"), d2[4] = o) : d2[4] = "".concat(o)), e2.push(d2));
              }
            }, e2;
          };
        },
        80: (n2) => {
          "use strict";
          n2.exports = function(n3, e2) {
            return e2 || (e2 = {}), n3 ? (n3 = String(n3.__esModule ? n3.default : n3), /^['"].*['"]$/.test(n3) && (n3 = n3.slice(1, -1)), e2.hash && (n3 += e2.hash), /["'() \t\n]|(%20)/.test(n3) || e2.needQuotes ? '"'.concat(n3.replace(/"/g, '\\"').replace(/\n/g, "\\n"), '"') : n3) : n3;
          };
        },
        415: (n2) => {
          "use strict";
          n2.exports = function(n3) {
            var e2 = n3[1], t3 = n3[3];
            if (!t3) return e2;
            if ("function" == typeof btoa) {
              var a2 = btoa(unescape(encodeURIComponent(JSON.stringify(t3)))), o = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(a2), r2 = "/*# ".concat(o, " */");
              return [e2].concat([r2]).join("\n");
            }
            return [e2].join("\n");
          };
        },
        937: (n2) => {
          function e2(n3) {
            return e2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
              return typeof n4;
            } : function(n4) {
              return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
            }, e2(n3);
          }
          n2.exports = "object" == ("undefined" == typeof self ? "undefined" : e2(self)) ? self.FormData : window.FormData;
        },
        831: (n2) => {
          "use strict";
          n2.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAADGCAYAAAAT+OqFAAAAdklEQVQoz42QQQ7AIAgEF/T/D+kbq/RWAlnQyyazA4aoAB4FsBSA/bFjuF1EOL7VbrIrBuusmrt4ZZORfb6ehbWdnRHEIiITaEUKa5EJqUakRSaEYBJSCY2dEstQY7AuxahwXFrvZmWl2rh4JZ07z9dLtesfNj5q0FU3A5ObbwAAAABJRU5ErkJggg==";
        }
      }, e = {};
      function t2(a2) {
        var o = e[a2];
        if (void 0 !== o) return o.exports;
        var r2 = e[a2] = {
          id: a2,
          exports: {}
        };
        return n[a2](r2, r2.exports, t2), r2.exports;
      }
      t2.m = n, t2.n = (n2) => {
        var e2 = n2 && n2.__esModule ? () => n2.default : () => n2;
        return t2.d(e2, {
          a: e2
        }), e2;
      }, t2.d = (n2, e2) => {
        for (var a2 in e2) t2.o(e2, a2) && !t2.o(n2, a2) && Object.defineProperty(n2, a2, {
          enumerable: true,
          get: e2[a2]
        });
      }, t2.g = function() {
        if ("object" == typeof globalThis) return globalThis;
        try {
          return this || new Function("return this")();
        } catch (n2) {
          if ("object" == typeof window) return window;
        }
      }(), t2.o = (n2, e2) => Object.prototype.hasOwnProperty.call(n2, e2), t2.b = document.baseURI || self.location.href, t2.nc = void 0;
      var a = {};
      return (() => {
        "use strict";
        t2.d(a, {
          default: () => Za
        });
        var n2 = t2(856), e2 = t2.n(n2), o = t2(470), r2 = t2.n(o), i = t2(370), l = t2.n(i), s = t2(458), p = t2.n(s), d2 = t2(278), c = t2.n(d2), A = t2(488), u = t2.n(A), y = t2(685), m = {};
        m.styleTagTransform = u(), m.setAttributes = p(), m.insert = l().bind(null, "head"), m.domAPI = r2(), m.insertStyleElement = c(), e2()(y.Z, m), y.Z && y.Z.locals && y.Z.locals;
        function h(n3) {
          return h = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, h(n3);
        }
        function f(n3, e3) {
          this.name = "AggregateError", this.errors = n3, this.message = e3 || "";
        }
        f.prototype = Error.prototype;
        function b(n3) {
          return b = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, b(n3);
        }
        var g = setTimeout;
        function v(n3) {
          return Boolean(n3 && void 0 !== n3.length);
        }
        function x() {
        }
        function E(n3) {
          if (!(this instanceof E)) throw new TypeError("Promises must be constructed via new");
          if ("function" != typeof n3) throw new TypeError("not a function");
          this._state = 0, this._handled = false, this._value = void 0, this._deferreds = [], I(n3, this);
        }
        function w(n3, e3) {
          for (; 3 === n3._state; ) n3 = n3._value;
          0 !== n3._state ? (n3._handled = true, E._immediateFn(function() {
            var t3 = 1 === n3._state ? e3.onFulfilled : e3.onRejected;
            if (null !== t3) {
              var a2;
              try {
                a2 = t3(n3._value);
              } catch (n4) {
                return void k(e3.promise, n4);
              }
              C(e3.promise, a2);
            } else (1 === n3._state ? C : k)(e3.promise, n3._value);
          })) : n3._deferreds.push(e3);
        }
        function C(n3, e3) {
          try {
            if (e3 === n3) throw new TypeError("A promise cannot be resolved with itself.");
            if (e3 && ("object" === b(e3) || "function" == typeof e3)) {
              var t3 = e3.then;
              if (e3 instanceof E) return n3._state = 3, n3._value = e3, void B(n3);
              if ("function" == typeof t3) return void I((a2 = t3, o2 = e3, function() {
                a2.apply(o2, arguments);
              }), n3);
            }
            n3._state = 1, n3._value = e3, B(n3);
          } catch (e4) {
            k(n3, e4);
          }
          var a2, o2;
        }
        function k(n3, e3) {
          n3._state = 2, n3._value = e3, B(n3);
        }
        function B(n3) {
          2 === n3._state && 0 === n3._deferreds.length && E._immediateFn(function() {
            n3._handled || E._unhandledRejectionFn(n3._value);
          });
          for (var e3 = 0, t3 = n3._deferreds.length; e3 < t3; e3++) w(n3, n3._deferreds[e3]);
          n3._deferreds = null;
        }
        function S(n3, e3, t3) {
          this.onFulfilled = "function" == typeof n3 ? n3 : null, this.onRejected = "function" == typeof e3 ? e3 : null, this.promise = t3;
        }
        function I(n3, e3) {
          var t3 = false;
          try {
            n3(function(n4) {
              t3 || (t3 = true, C(e3, n4));
            }, function(n4) {
              t3 || (t3 = true, k(e3, n4));
            });
          } catch (n4) {
            if (t3) return;
            t3 = true, k(e3, n4);
          }
        }
        E.prototype.catch = function(n3) {
          return this.then(null, n3);
        }, E.prototype.then = function(n3, e3) {
          var t3 = new this.constructor(x);
          return w(this, new S(n3, e3, t3)), t3;
        }, E.prototype.finally = function(n3) {
          var e3 = this.constructor;
          return this.then(function(t3) {
            return e3.resolve(n3()).then(function() {
              return t3;
            });
          }, function(t3) {
            return e3.resolve(n3()).then(function() {
              return e3.reject(t3);
            });
          });
        }, E.all = function(n3) {
          return new E(function(e3, t3) {
            if (!v(n3)) return t3(new TypeError("Promise.all accepts an array"));
            var a2 = Array.prototype.slice.call(n3);
            if (0 === a2.length) return e3([]);
            var o2 = a2.length;
            function r3(n4, i3) {
              try {
                if (i3 && ("object" === b(i3) || "function" == typeof i3)) {
                  var l2 = i3.then;
                  if ("function" == typeof l2) return void l2.call(i3, function(e4) {
                    r3(n4, e4);
                  }, t3);
                }
                a2[n4] = i3, 0 == --o2 && e3(a2);
              } catch (n5) {
                t3(n5);
              }
            }
            for (var i2 = 0; i2 < a2.length; i2++) r3(i2, a2[i2]);
          });
        }, E.any = function(n3) {
          var e3 = this;
          return new e3(function(t3, a2) {
            if (!n3 || void 0 === n3.length) return a2(new TypeError("Promise.any accepts an array"));
            var o2 = Array.prototype.slice.call(n3);
            if (0 === o2.length) return a2();
            for (var r3 = [], i2 = 0; i2 < o2.length; i2++) try {
              e3.resolve(o2[i2]).then(t3).catch(function(n4) {
                r3.push(n4), r3.length === o2.length && a2(new f(r3, "All promises were rejected"));
              });
            } catch (n4) {
              a2(n4);
            }
          });
        }, E.allSettled = function(n3) {
          return new this(function(e3, t3) {
            if (!n3 || void 0 === n3.length) return t3(new TypeError(h(n3) + " " + n3 + " is not iterable(cannot read property Symbol(Symbol.iterator))"));
            var a2 = Array.prototype.slice.call(n3);
            if (0 === a2.length) return e3([]);
            var o2 = a2.length;
            function r3(n4, t4) {
              if (t4 && ("object" === h(t4) || "function" == typeof t4)) {
                var i3 = t4.then;
                if ("function" == typeof i3) return void i3.call(t4, function(e4) {
                  r3(n4, e4);
                }, function(t5) {
                  a2[n4] = {
                    status: "rejected",
                    reason: t5
                  }, 0 == --o2 && e3(a2);
                });
              }
              a2[n4] = {
                status: "fulfilled",
                value: t4
              }, 0 == --o2 && e3(a2);
            }
            for (var i2 = 0; i2 < a2.length; i2++) r3(i2, a2[i2]);
          });
        }, E.resolve = function(n3) {
          return n3 && "object" === b(n3) && n3.constructor === E ? n3 : new E(function(e3) {
            e3(n3);
          });
        }, E.reject = function(n3) {
          return new E(function(e3, t3) {
            t3(n3);
          });
        }, E.race = function(n3) {
          return new E(function(e3, t3) {
            if (!v(n3)) return t3(new TypeError("Promise.race accepts an array"));
            for (var a2 = 0, o2 = n3.length; a2 < o2; a2++) E.resolve(n3[a2]).then(e3, t3);
          });
        }, E._immediateFn = "function" == typeof setImmediate && function(n3) {
          setImmediate(n3);
        } || function(n3) {
          g(n3, 0);
        }, E._unhandledRejectionFn = function(n3) {
          "undefined" != typeof console && console && console.warn("Possible Unhandled Promise Rejection:", n3);
        };
        const L = E;
        var z = /mobile/i.test(window.navigator.userAgent);
        const T = {
          secondToTime: function(n3) {
            if (0 === (n3 = n3 || 0) || n3 === 1 / 0 || "NaN" === n3.toString()) return "00:00";
            var e3 = Math.floor(n3 / 3600), t3 = Math.floor((n3 - 3600 * e3) / 60), a2 = Math.floor(n3 - 3600 * e3 - 60 * t3);
            return (e3 > 0 ? [e3, t3, a2] : [t3, a2]).map(function(n4) {
              return n4 < 10 ? "0" + n4 : "" + n4;
            }).join(":");
          },
          getElementViewLeft: function(n3) {
            var e3 = n3.offsetLeft, t3 = n3.offsetParent, a2 = document.body.scrollLeft + document.documentElement.scrollLeft;
            if (document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement) for (; null !== t3 && t3 !== n3; ) e3 += t3.offsetLeft, t3 = t3.offsetParent;
            else for (; null !== t3; ) e3 += t3.offsetLeft, t3 = t3.offsetParent;
            return e3 - a2;
          },
          getBoundingClientRectViewLeft: function(n3) {
            var e3 = window.scrollY || window.pageYOffset || document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0);
            if (n3.getBoundingClientRect) {
              if ("number" != typeof this.getBoundingClientRectViewLeft.offset) {
                var t3 = document.createElement("div");
                t3.style.cssText = "position:absolute;top:0;left:0;", document.body.appendChild(t3), this.getBoundingClientRectViewLeft.offset = -t3.getBoundingClientRect().top - e3, document.body.removeChild(t3), t3 = null;
              }
              var a2 = n3.getBoundingClientRect(), o2 = this.getBoundingClientRectViewLeft.offset;
              return a2.left + o2;
            }
            return this.getElementViewLeft(n3);
          },
          getScrollPosition: function() {
            return {
              left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0,
              top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
            };
          },
          setScrollPosition: function(n3) {
            var e3 = n3.left, t3 = void 0 === e3 ? 0 : e3, a2 = n3.top, o2 = void 0 === a2 ? 0 : a2;
            this.isFirefox ? (document.documentElement.scrollLeft = t3, document.documentElement.scrollTop = o2) : window.scrollTo(t3, o2);
          },
          isMobile: z,
          isFirefox: /firefox/i.test(window.navigator.userAgent),
          isChrome: /chrome/i.test(window.navigator.userAgent),
          isSafari: /safari/i.test(window.navigator.userAgent),
          storage: {
            set: function(n3, e3) {
              localStorage.setItem(n3, e3);
            },
            get: function(n3) {
              return localStorage.getItem(n3);
            }
          },
          nameMap: {
            dragStart: z ? "touchstart" : "mousedown",
            dragMove: z ? "touchmove" : "mousemove",
            dragEnd: z ? "touchend" : "mouseup"
          },
          color2Number: function(n3) {
            return "#" === n3[0] && (n3 = n3.substr(1)), 3 === n3.length && (n3 = "".concat(n3[0]).concat(n3[0]).concat(n3[1]).concat(n3[1]).concat(n3[2]).concat(n3[2])), parseInt(n3, 16) + 0 & 16777215;
          },
          number2Color: function(n3) {
            return "#" + ("00000" + n3.toString(16)).slice(-6);
          },
          number2Type: function(n3) {
            switch (n3) {
              case 0:
              default:
                return "right";
              case 1:
                return "top";
              case 2:
                return "bottom";
            }
          }
        };
        function q(n3, e3) {
          return function() {
            return n3.apply(e3, arguments);
          };
        }
        function O(n3) {
          return O = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, O(n3);
        }
        var j, D = Object.prototype.toString, P = Object.getPrototypeOf, R = (j = /* @__PURE__ */ Object.create(null), function(n3) {
          var e3 = D.call(n3);
          return j[e3] || (j[e3] = e3.slice(8, -1).toLowerCase());
        }), Y = function(n3) {
          return n3 = n3.toLowerCase(), function(e3) {
            return R(e3) === n3;
          };
        }, M = function(n3) {
          return function(e3) {
            return O(e3) === n3;
          };
        }, F = Array.isArray, W = M("undefined"), U = Y("ArrayBuffer"), N = M("string"), Q = M("function"), H = M("number"), _ = function(n3) {
          return null !== n3 && "object" === O(n3);
        }, K = function(n3) {
          if ("object" !== R(n3)) return false;
          var e3 = P(n3);
          return !(null !== e3 && e3 !== Object.prototype && null !== Object.getPrototypeOf(e3) || Symbol.toStringTag in n3 || Symbol.iterator in n3);
        }, Z = Y("Date"), V = Y("File"), X = Y("Blob"), J = Y("FileList"), G = Y("URLSearchParams");
        function $2(n3, e3) {
          var t3, a2, o2 = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, r3 = o2.allOwnKeys, i2 = void 0 !== r3 && r3;
          if (null != n3) if ("object" !== O(n3) && (n3 = [n3]), F(n3)) for (t3 = 0, a2 = n3.length; t3 < a2; t3++) e3.call(null, n3[t3], t3, n3);
          else {
            var l2, s2 = i2 ? Object.getOwnPropertyNames(n3) : Object.keys(n3), p2 = s2.length;
            for (t3 = 0; t3 < p2; t3++) l2 = s2[t3], e3.call(null, n3[l2], l2, n3);
          }
        }
        function nn(n3, e3) {
          e3 = e3.toLowerCase();
          for (var t3, a2 = Object.keys(n3), o2 = a2.length; o2-- > 0; ) if (e3 === (t3 = a2[o2]).toLowerCase()) return t3;
          return null;
        }
        var en, tn, an = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : "undefined" != typeof window ? window : global, on3 = function(n3) {
          return !W(n3) && n3 !== an;
        }, rn = (en = "undefined" != typeof Uint8Array && P(Uint8Array), function(n3) {
          return en && n3 instanceof en;
        }), ln = Y("HTMLFormElement"), sn = (tn = Object.prototype.hasOwnProperty, function(n3, e3) {
          return tn.call(n3, e3);
        }), pn = Y("RegExp"), dn = function(n3, e3) {
          var t3 = Object.getOwnPropertyDescriptors(n3), a2 = {};
          $2(t3, function(t4, o2) {
            false !== e3(t4, o2, n3) && (a2[o2] = t4);
          }), Object.defineProperties(n3, a2);
        };
        const cn = {
          isArray: F,
          isArrayBuffer: U,
          isBuffer: function(n3) {
            return null !== n3 && !W(n3) && null !== n3.constructor && !W(n3.constructor) && Q(n3.constructor.isBuffer) && n3.constructor.isBuffer(n3);
          },
          isFormData: function(n3) {
            var e3 = "[object FormData]";
            return n3 && ("function" == typeof FormData && n3 instanceof FormData || D.call(n3) === e3 || Q(n3.toString) && n3.toString() === e3);
          },
          isArrayBufferView: function(n3) {
            return "undefined" != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(n3) : n3 && n3.buffer && U(n3.buffer);
          },
          isString: N,
          isNumber: H,
          isBoolean: function(n3) {
            return true === n3 || false === n3;
          },
          isObject: _,
          isPlainObject: K,
          isUndefined: W,
          isDate: Z,
          isFile: V,
          isBlob: X,
          isRegExp: pn,
          isFunction: Q,
          isStream: function(n3) {
            return _(n3) && Q(n3.pipe);
          },
          isURLSearchParams: G,
          isTypedArray: rn,
          isFileList: J,
          forEach: $2,
          merge: function n3() {
            for (var e3 = on3(this) && this || {}, t3 = e3.caseless, a2 = {}, o2 = function(e4, o3) {
              var r4 = t3 && nn(a2, o3) || o3;
              K(a2[r4]) && K(e4) ? a2[r4] = n3(a2[r4], e4) : K(e4) ? a2[r4] = n3({}, e4) : F(e4) ? a2[r4] = e4.slice() : a2[r4] = e4;
            }, r3 = 0, i2 = arguments.length; r3 < i2; r3++) arguments[r3] && $2(arguments[r3], o2);
            return a2;
          },
          extend: function(n3, e3, t3) {
            var a2 = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, o2 = a2.allOwnKeys;
            return $2(e3, function(e4, a3) {
              t3 && Q(e4) ? n3[a3] = q(e4, t3) : n3[a3] = e4;
            }, {
              allOwnKeys: o2
            }), n3;
          },
          trim: function(n3) {
            return n3.trim ? n3.trim() : n3.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
          },
          stripBOM: function(n3) {
            return 65279 === n3.charCodeAt(0) && (n3 = n3.slice(1)), n3;
          },
          inherits: function(n3, e3, t3, a2) {
            n3.prototype = Object.create(e3.prototype, a2), n3.prototype.constructor = n3, Object.defineProperty(n3, "super", {
              value: e3.prototype
            }), t3 && Object.assign(n3.prototype, t3);
          },
          toFlatObject: function(n3, e3, t3, a2) {
            var o2, r3, i2, l2 = {};
            if (e3 = e3 || {}, null == n3) return e3;
            do {
              for (r3 = (o2 = Object.getOwnPropertyNames(n3)).length; r3-- > 0; ) i2 = o2[r3], a2 && !a2(i2, n3, e3) || l2[i2] || (e3[i2] = n3[i2], l2[i2] = true);
              n3 = false !== t3 && P(n3);
            } while (n3 && (!t3 || t3(n3, e3)) && n3 !== Object.prototype);
            return e3;
          },
          kindOf: R,
          kindOfTest: Y,
          endsWith: function(n3, e3, t3) {
            n3 = String(n3), (void 0 === t3 || t3 > n3.length) && (t3 = n3.length), t3 -= e3.length;
            var a2 = n3.indexOf(e3, t3);
            return -1 !== a2 && a2 === t3;
          },
          toArray: function(n3) {
            if (!n3) return null;
            if (F(n3)) return n3;
            var e3 = n3.length;
            if (!H(e3)) return null;
            for (var t3 = new Array(e3); e3-- > 0; ) t3[e3] = n3[e3];
            return t3;
          },
          forEachEntry: function(n3, e3) {
            for (var t3, a2 = (n3 && n3[Symbol.iterator]).call(n3); (t3 = a2.next()) && !t3.done; ) {
              var o2 = t3.value;
              e3.call(n3, o2[0], o2[1]);
            }
          },
          matchAll: function(n3, e3) {
            for (var t3, a2 = []; null !== (t3 = n3.exec(e3)); ) a2.push(t3);
            return a2;
          },
          isHTMLForm: ln,
          hasOwnProperty: sn,
          hasOwnProp: sn,
          reduceDescriptors: dn,
          freezeMethods: function(n3) {
            dn(n3, function(e3, t3) {
              if (Q(n3) && -1 !== ["arguments", "caller", "callee"].indexOf(t3)) return false;
              var a2 = n3[t3];
              Q(a2) && (e3.enumerable = false, "writable" in e3 ? e3.writable = false : e3.set || (e3.set = function() {
                throw Error("Can not rewrite read-only method '" + t3 + "'");
              }));
            });
          },
          toObjectSet: function(n3, e3) {
            var t3 = {}, a2 = function(n4) {
              n4.forEach(function(n5) {
                t3[n5] = true;
              });
            };
            return F(n3) ? a2(n3) : a2(String(n3).split(e3)), t3;
          },
          toCamelCase: function(n3) {
            return n3.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g, function(n4, e3, t3) {
              return e3.toUpperCase() + t3;
            });
          },
          noop: function() {
          },
          toFiniteNumber: function(n3, e3) {
            return n3 = +n3, Number.isFinite(n3) ? n3 : e3;
          },
          findKey: nn,
          global: an,
          isContextDefined: on3,
          toJSONObject: function(n3) {
            var e3 = new Array(10);
            return function n4(t3, a2) {
              if (_(t3)) {
                if (e3.indexOf(t3) >= 0) return;
                if (!("toJSON" in t3)) {
                  e3[a2] = t3;
                  var o2 = F(t3) ? [] : {};
                  return $2(t3, function(e4, t4) {
                    var r3 = n4(e4, a2 + 1);
                    !W(r3) && (o2[t4] = r3);
                  }), e3[a2] = void 0, o2;
                }
              }
              return t3;
            }(n3, 0);
          }
        };
        function An(n3, e3, t3, a2, o2) {
          Error.call(this), Error.captureStackTrace ? Error.captureStackTrace(this, this.constructor) : this.stack = new Error().stack, this.message = n3, this.name = "AxiosError", e3 && (this.code = e3), t3 && (this.config = t3), a2 && (this.request = a2), o2 && (this.response = o2);
        }
        cn.inherits(An, Error, {
          toJSON: function() {
            return {
              message: this.message,
              name: this.name,
              description: this.description,
              number: this.number,
              fileName: this.fileName,
              lineNumber: this.lineNumber,
              columnNumber: this.columnNumber,
              stack: this.stack,
              config: cn.toJSONObject(this.config),
              code: this.code,
              status: this.response && this.response.status ? this.response.status : null
            };
          }
        });
        var un = An.prototype, yn = {};
        ["ERR_BAD_OPTION_VALUE", "ERR_BAD_OPTION", "ECONNABORTED", "ETIMEDOUT", "ERR_NETWORK", "ERR_FR_TOO_MANY_REDIRECTS", "ERR_DEPRECATED", "ERR_BAD_RESPONSE", "ERR_BAD_REQUEST", "ERR_CANCELED", "ERR_NOT_SUPPORT", "ERR_INVALID_URL"].forEach(function(n3) {
          yn[n3] = {
            value: n3
          };
        }), Object.defineProperties(An, yn), Object.defineProperty(un, "isAxiosError", {
          value: true
        }), An.from = function(n3, e3, t3, a2, o2, r3) {
          var i2 = Object.create(un);
          return cn.toFlatObject(n3, i2, function(n4) {
            return n4 !== Error.prototype;
          }, function(n4) {
            return "isAxiosError" !== n4;
          }), An.call(i2, n3.message, e3, t3, a2, o2), i2.cause = n3, i2.name = n3.name, r3 && Object.assign(i2, r3), i2;
        };
        const mn = An, hn = t2(937);
        function fn(n3) {
          return fn = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, fn(n3);
        }
        function bn(n3) {
          return cn.isPlainObject(n3) || cn.isArray(n3);
        }
        function gn(n3) {
          return cn.endsWith(n3, "[]") ? n3.slice(0, -2) : n3;
        }
        function vn(n3, e3, t3) {
          return n3 ? n3.concat(e3).map(function(n4, e4) {
            return n4 = gn(n4), !t3 && e4 ? "[" + n4 + "]" : n4;
          }).join(t3 ? "." : "") : e3;
        }
        var xn = cn.toFlatObject(cn, {}, null, function(n3) {
          return /^is[A-Z]/.test(n3);
        });
        const En = function(n3, e3, t3) {
          if (!cn.isObject(n3)) throw new TypeError("target must be an object");
          e3 = e3 || new (hn || FormData)();
          var a2, o2 = (t3 = cn.toFlatObject(t3, {
            metaTokens: true,
            dots: false,
            indexes: false
          }, false, function(n4, e4) {
            return !cn.isUndefined(e4[n4]);
          })).metaTokens, r3 = t3.visitor || d3, i2 = t3.dots, l2 = t3.indexes, s2 = (t3.Blob || "undefined" != typeof Blob && Blob) && (a2 = e3) && cn.isFunction(a2.append) && "FormData" === a2[Symbol.toStringTag] && a2[Symbol.iterator];
          if (!cn.isFunction(r3)) throw new TypeError("visitor must be a function");
          function p2(n4) {
            if (null === n4) return "";
            if (cn.isDate(n4)) return n4.toISOString();
            if (!s2 && cn.isBlob(n4)) throw new mn("Blob is not supported. Use a Buffer instead.");
            return cn.isArrayBuffer(n4) || cn.isTypedArray(n4) ? s2 && "function" == typeof Blob ? new Blob([n4]) : Buffer.from(n4) : n4;
          }
          function d3(n4, t4, a3) {
            var r4 = n4;
            if (n4 && !a3 && "object" === fn(n4)) {
              if (cn.endsWith(t4, "{}")) t4 = o2 ? t4 : t4.slice(0, -2), n4 = JSON.stringify(n4);
              else if (cn.isArray(n4) && function(n5) {
                return cn.isArray(n5) && !n5.some(bn);
              }(n4) || cn.isFileList(n4) || cn.endsWith(t4, "[]") && (r4 = cn.toArray(n4))) return t4 = gn(t4), r4.forEach(function(n5, a4) {
                !cn.isUndefined(n5) && null !== n5 && e3.append(true === l2 ? vn([t4], a4, i2) : null === l2 ? t4 : t4 + "[]", p2(n5));
              }), false;
            }
            return !!bn(n4) || (e3.append(vn(a3, t4, i2), p2(n4)), false);
          }
          var c2 = [], A2 = Object.assign(xn, {
            defaultVisitor: d3,
            convertValue: p2,
            isVisitable: bn
          });
          if (!cn.isObject(n3)) throw new TypeError("data must be an object");
          return function n4(t4, a3) {
            if (!cn.isUndefined(t4)) {
              if (-1 !== c2.indexOf(t4)) throw Error("Circular reference detected in " + a3.join("."));
              c2.push(t4), cn.forEach(t4, function(t5, o3) {
                true === (!(cn.isUndefined(t5) || null === t5) && r3.call(e3, t5, cn.isString(o3) ? o3.trim() : o3, a3, A2)) && n4(t5, a3 ? a3.concat(o3) : [o3]);
              }), c2.pop();
            }
          }(n3), e3;
        };
        function wn(n3) {
          var e3 = {
            "!": "%21",
            "'": "%27",
            "(": "%28",
            ")": "%29",
            "~": "%7E",
            "%20": "+",
            "%00": "\0"
          };
          return encodeURIComponent(n3).replace(/[!'()~]|%20|%00/g, function(n4) {
            return e3[n4];
          });
        }
        function Cn(n3, e3) {
          this._pairs = [], n3 && En(n3, this, e3);
        }
        var kn = Cn.prototype;
        kn.append = function(n3, e3) {
          this._pairs.push([n3, e3]);
        }, kn.toString = function(n3) {
          var e3 = n3 ? function(e4) {
            return n3.call(this, e4, wn);
          } : wn;
          return this._pairs.map(function(n4) {
            return e3(n4[0]) + "=" + e3(n4[1]);
          }, "").join("&");
        };
        const Bn = Cn;
        function Sn(n3) {
          return encodeURIComponent(n3).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
        }
        function In(n3, e3, t3) {
          if (!e3) return n3;
          var a2, o2 = t3 && t3.encode || Sn, r3 = t3 && t3.serialize;
          if (a2 = r3 ? r3(e3, t3) : cn.isURLSearchParams(e3) ? e3.toString() : new Bn(e3, t3).toString(o2)) {
            var i2 = n3.indexOf("#");
            -1 !== i2 && (n3 = n3.slice(0, i2)), n3 += (-1 === n3.indexOf("?") ? "?" : "&") + a2;
          }
          return n3;
        }
        function Ln(n3) {
          return Ln = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Ln(n3);
        }
        function zn(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== Ln(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== Ln(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === Ln(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Tn = function() {
          function n3() {
            !function(n4, e4) {
              if (!(n4 instanceof e4)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.handlers = [];
          }
          var e3, t3;
          return e3 = n3, t3 = [{
            key: "use",
            value: function(n4, e4, t4) {
              return this.handlers.push({
                fulfilled: n4,
                rejected: e4,
                synchronous: !!t4 && t4.synchronous,
                runWhen: t4 ? t4.runWhen : null
              }), this.handlers.length - 1;
            }
          }, {
            key: "eject",
            value: function(n4) {
              this.handlers[n4] && (this.handlers[n4] = null);
            }
          }, {
            key: "clear",
            value: function() {
              this.handlers && (this.handlers = []);
            }
          }, {
            key: "forEach",
            value: function(n4) {
              cn.forEach(this.handlers, function(e4) {
                null !== e4 && n4(e4);
              });
            }
          }], t3 && zn(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const qn = Tn, On = {
          silentJSONParsing: true,
          forcedJSONParsing: true,
          clarifyTimeoutError: false
        }, jn = "undefined" != typeof URLSearchParams ? URLSearchParams : Bn, Dn = FormData;
        var Pn, Rn = ("undefined" == typeof navigator || "ReactNative" !== (Pn = navigator.product) && "NativeScript" !== Pn && "NS" !== Pn) && "undefined" != typeof window && "undefined" != typeof document, Yn = "undefined" != typeof WorkerGlobalScope && self instanceof WorkerGlobalScope && "function" == typeof self.importScripts;
        const Mn = {
          isBrowser: true,
          classes: {
            URLSearchParams: jn,
            FormData: Dn,
            Blob
          },
          isStandardBrowserEnv: Rn,
          isStandardBrowserWebWorkerEnv: Yn,
          protocols: ["http", "https", "file", "blob", "url", "data"]
        }, Fn = function(n3) {
          function e3(n4, t4, a2, o2) {
            var r3 = n4[o2++], i2 = Number.isFinite(+r3), l2 = o2 >= n4.length;
            return r3 = !r3 && cn.isArray(a2) ? a2.length : r3, l2 ? (cn.hasOwnProp(a2, r3) ? a2[r3] = [a2[r3], t4] : a2[r3] = t4, !i2) : (a2[r3] && cn.isObject(a2[r3]) || (a2[r3] = []), e3(n4, t4, a2[r3], o2) && cn.isArray(a2[r3]) && (a2[r3] = function(n5) {
              var e4, t5, a3 = {}, o3 = Object.keys(n5), r4 = o3.length;
              for (e4 = 0; e4 < r4; e4++) a3[t5 = o3[e4]] = n5[t5];
              return a3;
            }(a2[r3])), !i2);
          }
          if (cn.isFormData(n3) && cn.isFunction(n3.entries)) {
            var t3 = {};
            return cn.forEachEntry(n3, function(n4, a2) {
              e3(function(n5) {
                return cn.matchAll(/\w+|\[(\w*)]/g, n5).map(function(n6) {
                  return "[]" === n6[0] ? "" : n6[1] || n6[0];
                });
              }(n4), a2, t3, 0);
            }), t3;
          }
          return null;
        };
        var Wn = {
          "Content-Type": void 0
        }, Un = {
          transitional: On,
          adapter: ["xhr", "http"],
          transformRequest: [function(n3, e3) {
            var t3, a2 = e3.getContentType() || "", o2 = a2.indexOf("application/json") > -1, r3 = cn.isObject(n3);
            if (r3 && cn.isHTMLForm(n3) && (n3 = new FormData(n3)), cn.isFormData(n3)) return o2 && o2 ? JSON.stringify(Fn(n3)) : n3;
            if (cn.isArrayBuffer(n3) || cn.isBuffer(n3) || cn.isStream(n3) || cn.isFile(n3) || cn.isBlob(n3)) return n3;
            if (cn.isArrayBufferView(n3)) return n3.buffer;
            if (cn.isURLSearchParams(n3)) return e3.setContentType("application/x-www-form-urlencoded;charset=utf-8", false), n3.toString();
            if (r3) {
              if (a2.indexOf("application/x-www-form-urlencoded") > -1) return function(n4, e4) {
                return En(n4, new Mn.classes.URLSearchParams(), Object.assign({
                  visitor: function(n5, e5, t4, a3) {
                    return Mn.isNode && cn.isBuffer(n5) ? (this.append(e5, n5.toString("base64")), false) : a3.defaultVisitor.apply(this, arguments);
                  }
                }, e4));
              }(n3, this.formSerializer).toString();
              if ((t3 = cn.isFileList(n3)) || a2.indexOf("multipart/form-data") > -1) {
                var i2 = this.env && this.env.FormData;
                return En(t3 ? {
                  "files[]": n3
                } : n3, i2 && new i2(), this.formSerializer);
              }
            }
            return r3 || o2 ? (e3.setContentType("application/json", false), function(n4, e4, t4) {
              if (cn.isString(n4)) try {
                return (0, JSON.parse)(n4), cn.trim(n4);
              } catch (n5) {
                if ("SyntaxError" !== n5.name) throw n5;
              }
              return (0, JSON.stringify)(n4);
            }(n3)) : n3;
          }],
          transformResponse: [function(n3) {
            var e3 = this.transitional || Un.transitional, t3 = e3 && e3.forcedJSONParsing, a2 = "json" === this.responseType;
            if (n3 && cn.isString(n3) && (t3 && !this.responseType || a2)) {
              var o2 = !(e3 && e3.silentJSONParsing) && a2;
              try {
                return JSON.parse(n3);
              } catch (n4) {
                if (o2) {
                  if ("SyntaxError" === n4.name) throw mn.from(n4, mn.ERR_BAD_RESPONSE, this, null, this.response);
                  throw n4;
                }
              }
            }
            return n3;
          }],
          timeout: 0,
          xsrfCookieName: "XSRF-TOKEN",
          xsrfHeaderName: "X-XSRF-TOKEN",
          maxContentLength: -1,
          maxBodyLength: -1,
          env: {
            FormData: Mn.classes.FormData,
            Blob: Mn.classes.Blob
          },
          validateStatus: function(n3) {
            return n3 >= 200 && n3 < 300;
          },
          headers: {
            common: {
              Accept: "application/json, text/plain, */*"
            }
          }
        };
        cn.forEach(["delete", "get", "head"], function(n3) {
          Un.headers[n3] = {};
        }), cn.forEach(["post", "put", "patch"], function(n3) {
          Un.headers[n3] = cn.merge(Wn);
        });
        const Nn = Un;
        var Qn = cn.toObjectSet(["age", "authorization", "content-length", "content-type", "etag", "expires", "from", "host", "if-modified-since", "if-unmodified-since", "last-modified", "location", "max-forwards", "proxy-authorization", "referer", "retry-after", "user-agent"]);
        function Hn(n3) {
          return Hn = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Hn(n3);
        }
        function _n(n3, e3) {
          (null == e3 || e3 > n3.length) && (e3 = n3.length);
          for (var t3 = 0, a2 = new Array(e3); t3 < e3; t3++) a2[t3] = n3[t3];
          return a2;
        }
        function Kn(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== Hn(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== Hn(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === Hn(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Zn = Symbol("internals");
        function Vn(n3) {
          return n3 && String(n3).trim().toLowerCase();
        }
        function Xn(n3) {
          return false === n3 || null == n3 ? n3 : cn.isArray(n3) ? n3.map(Xn) : String(n3);
        }
        function Jn(n3, e3, t3, a2) {
          return cn.isFunction(a2) ? a2.call(this, e3, t3) : cn.isString(e3) ? cn.isString(a2) ? -1 !== e3.indexOf(a2) : cn.isRegExp(a2) ? a2.test(e3) : void 0 : void 0;
        }
        var Gn = function(n3, e3) {
          function t3(n4) {
            !function(n5, e4) {
              if (!(n5 instanceof e4)) throw new TypeError("Cannot call a class as a function");
            }(this, t3), n4 && this.set(n4);
          }
          var a2, o2, r3;
          return a2 = t3, o2 = [{
            key: "set",
            value: function(n4, e4, t4) {
              var a3 = this;
              function o3(n5, e5, t5) {
                var o4 = Vn(e5);
                if (!o4) throw new Error("header name must be a non-empty string");
                var r5 = cn.findKey(a3, o4);
                (!r5 || void 0 === a3[r5] || true === t5 || void 0 === t5 && false !== a3[r5]) && (a3[r5 || e5] = Xn(n5));
              }
              var r4, i2, l2, s2, p2, d3 = function(n5, e5) {
                return cn.forEach(n5, function(n6, t5) {
                  return o3(n6, t5, e5);
                });
              };
              return cn.isPlainObject(n4) || n4 instanceof this.constructor ? d3(n4, e4) : cn.isString(n4) && (n4 = n4.trim()) && !/^[-_a-zA-Z]+$/.test(n4.trim()) ? d3((p2 = {}, (r4 = n4) && r4.split("\n").forEach(function(n5) {
                s2 = n5.indexOf(":"), i2 = n5.substring(0, s2).trim().toLowerCase(), l2 = n5.substring(s2 + 1).trim(), !i2 || p2[i2] && Qn[i2] || ("set-cookie" === i2 ? p2[i2] ? p2[i2].push(l2) : p2[i2] = [l2] : p2[i2] = p2[i2] ? p2[i2] + ", " + l2 : l2);
              }), p2), e4) : null != n4 && o3(e4, n4, t4), this;
            }
          }, {
            key: "get",
            value: function(n4, e4) {
              if (n4 = Vn(n4)) {
                var t4 = cn.findKey(this, n4);
                if (t4) {
                  var a3 = this[t4];
                  if (!e4) return a3;
                  if (true === e4) return function(n5) {
                    for (var e5, t5 = /* @__PURE__ */ Object.create(null), a4 = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; e5 = a4.exec(n5); ) t5[e5[1]] = e5[2];
                    return t5;
                  }(a3);
                  if (cn.isFunction(e4)) return e4.call(this, a3, t4);
                  if (cn.isRegExp(e4)) return e4.exec(a3);
                  throw new TypeError("parser must be boolean|regexp|function");
                }
              }
            }
          }, {
            key: "has",
            value: function(n4, e4) {
              if (n4 = Vn(n4)) {
                var t4 = cn.findKey(this, n4);
                return !(!t4 || e4 && !Jn(0, this[t4], t4, e4));
              }
              return false;
            }
          }, {
            key: "delete",
            value: function(n4, e4) {
              var t4 = this, a3 = false;
              function o3(n5) {
                if (n5 = Vn(n5)) {
                  var o4 = cn.findKey(t4, n5);
                  !o4 || e4 && !Jn(0, t4[o4], o4, e4) || (delete t4[o4], a3 = true);
                }
              }
              return cn.isArray(n4) ? n4.forEach(o3) : o3(n4), a3;
            }
          }, {
            key: "clear",
            value: function() {
              return Object.keys(this).forEach(this.delete.bind(this));
            }
          }, {
            key: "normalize",
            value: function(n4) {
              var e4 = this, t4 = {};
              return cn.forEach(this, function(a3, o3) {
                var r4 = cn.findKey(t4, o3);
                if (r4) return e4[r4] = Xn(a3), void delete e4[o3];
                var i2 = n4 ? function(n5) {
                  return n5.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, function(n6, e5, t5) {
                    return e5.toUpperCase() + t5;
                  });
                }(o3) : String(o3).trim();
                i2 !== o3 && delete e4[o3], e4[i2] = Xn(a3), t4[i2] = true;
              }), this;
            }
          }, {
            key: "concat",
            value: function() {
              for (var n4, e4 = arguments.length, t4 = new Array(e4), a3 = 0; a3 < e4; a3++) t4[a3] = arguments[a3];
              return (n4 = this.constructor).concat.apply(n4, [this].concat(t4));
            }
          }, {
            key: "toJSON",
            value: function(n4) {
              var e4 = /* @__PURE__ */ Object.create(null);
              return cn.forEach(this, function(t4, a3) {
                null != t4 && false !== t4 && (e4[a3] = n4 && cn.isArray(t4) ? t4.join(", ") : t4);
              }), e4;
            }
          }, {
            key: Symbol.iterator,
            value: function() {
              return Object.entries(this.toJSON())[Symbol.iterator]();
            }
          }, {
            key: "toString",
            value: function() {
              return Object.entries(this.toJSON()).map(function(n4) {
                var e4, t4, a3 = (t4 = 2, function(n5) {
                  if (Array.isArray(n5)) return n5;
                }(e4 = n4) || function(n5, e5) {
                  var t5 = null == n5 ? null : "undefined" != typeof Symbol && n5[Symbol.iterator] || n5["@@iterator"];
                  if (null != t5) {
                    var a4, o3, r4, i2, l2 = [], s2 = true, p2 = false;
                    try {
                      if (r4 = (t5 = t5.call(n5)).next, 0 === e5) {
                        if (Object(t5) !== t5) return;
                        s2 = false;
                      } else for (; !(s2 = (a4 = r4.call(t5)).done) && (l2.push(a4.value), l2.length !== e5); s2 = true) ;
                    } catch (n6) {
                      p2 = true, o3 = n6;
                    } finally {
                      try {
                        if (!s2 && null != t5.return && (i2 = t5.return(), Object(i2) !== i2)) return;
                      } finally {
                        if (p2) throw o3;
                      }
                    }
                    return l2;
                  }
                }(e4, t4) || function(n5, e5) {
                  if (n5) {
                    if ("string" == typeof n5) return _n(n5, e5);
                    var t5 = Object.prototype.toString.call(n5).slice(8, -1);
                    return "Object" === t5 && n5.constructor && (t5 = n5.constructor.name), "Map" === t5 || "Set" === t5 ? Array.from(n5) : "Arguments" === t5 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t5) ? _n(n5, e5) : void 0;
                  }
                }(e4, t4) || function() {
                  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
                }());
                return a3[0] + ": " + a3[1];
              }).join("\n");
            }
          }, {
            key: Symbol.toStringTag,
            get: function() {
              return "AxiosHeaders";
            }
          }], r3 = [{
            key: "from",
            value: function(n4) {
              return n4 instanceof this ? n4 : new this(n4);
            }
          }, {
            key: "concat",
            value: function(n4) {
              for (var e4 = new this(n4), t4 = arguments.length, a3 = new Array(t4 > 1 ? t4 - 1 : 0), o3 = 1; o3 < t4; o3++) a3[o3 - 1] = arguments[o3];
              return a3.forEach(function(n5) {
                return e4.set(n5);
              }), e4;
            }
          }, {
            key: "accessor",
            value: function(n4) {
              var e4 = (this[Zn] = this[Zn] = {
                accessors: {}
              }).accessors, t4 = this.prototype;
              function a3(n5) {
                var a4 = Vn(n5);
                e4[a4] || (function(n6, e5) {
                  var t5 = cn.toCamelCase(" " + e5);
                  ["get", "set", "has"].forEach(function(a5) {
                    Object.defineProperty(n6, a5 + t5, {
                      value: function(n7, t6, o3) {
                        return this[a5].call(this, e5, n7, t6, o3);
                      },
                      configurable: true
                    });
                  });
                }(t4, n5), e4[a4] = true);
              }
              return cn.isArray(n4) ? n4.forEach(a3) : a3(n4), this;
            }
          }], o2 && Kn(a2.prototype, o2), r3 && Kn(a2, r3), Object.defineProperty(a2, "prototype", {
            writable: false
          }), t3;
        }();
        Gn.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent"]), cn.freezeMethods(Gn.prototype), cn.freezeMethods(Gn);
        const $n = Gn;
        function ne(n3, e3) {
          var t3 = this || Nn, a2 = e3 || t3, o2 = $n.from(a2.headers), r3 = a2.data;
          return cn.forEach(n3, function(n4) {
            r3 = n4.call(t3, r3, o2.normalize(), e3 ? e3.status : void 0);
          }), o2.normalize(), r3;
        }
        function ee(n3) {
          return !(!n3 || !n3.__CANCEL__);
        }
        function te(n3, e3, t3) {
          mn.call(this, null == n3 ? "canceled" : n3, mn.ERR_CANCELED, e3, t3), this.name = "CanceledError";
        }
        cn.inherits(te, mn, {
          __CANCEL__: true
        });
        const ae = te, oe = Mn.isStandardBrowserEnv ? {
          write: function(n3, e3, t3, a2, o2, r3) {
            var i2 = [];
            i2.push(n3 + "=" + encodeURIComponent(e3)), cn.isNumber(t3) && i2.push("expires=" + new Date(t3).toGMTString()), cn.isString(a2) && i2.push("path=" + a2), cn.isString(o2) && i2.push("domain=" + o2), true === r3 && i2.push("secure"), document.cookie = i2.join("; ");
          },
          read: function(n3) {
            var e3 = document.cookie.match(new RegExp("(^|;\\s*)(" + n3 + ")=([^;]*)"));
            return e3 ? decodeURIComponent(e3[3]) : null;
          },
          remove: function(n3) {
            this.write(n3, "", Date.now() - 864e5);
          }
        } : {
          write: function() {
          },
          read: function() {
            return null;
          },
          remove: function() {
          }
        };
        function re(n3, e3) {
          return n3 && !/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e3) ? function(n4, e4) {
            return e4 ? n4.replace(/\/+$/, "") + "/" + e4.replace(/^\/+/, "") : n4;
          }(n3, e3) : e3;
        }
        const ie = Mn.isStandardBrowserEnv ? function() {
          var n3, e3 = /(msie|trident)/i.test(navigator.userAgent), t3 = document.createElement("a");
          function a2(n4) {
            var a3 = n4;
            return e3 && (t3.setAttribute("href", a3), a3 = t3.href), t3.setAttribute("href", a3), {
              href: t3.href,
              protocol: t3.protocol ? t3.protocol.replace(/:$/, "") : "",
              host: t3.host,
              search: t3.search ? t3.search.replace(/^\?/, "") : "",
              hash: t3.hash ? t3.hash.replace(/^#/, "") : "",
              hostname: t3.hostname,
              port: t3.port,
              pathname: "/" === t3.pathname.charAt(0) ? t3.pathname : "/" + t3.pathname
            };
          }
          return n3 = a2(window.location.href), function(e4) {
            var t4 = cn.isString(e4) ? a2(e4) : e4;
            return t4.protocol === n3.protocol && t4.host === n3.host;
          };
        }() : function() {
          return true;
        };
        function le(n3, e3) {
          var t3 = 0, a2 = function(n4, e4) {
            n4 = n4 || 10;
            var t4, a3 = new Array(n4), o2 = new Array(n4), r3 = 0, i2 = 0;
            return e4 = void 0 !== e4 ? e4 : 1e3, function(l2) {
              var s2 = Date.now(), p2 = o2[i2];
              t4 || (t4 = s2), a3[r3] = l2, o2[r3] = s2;
              for (var d3 = i2, c2 = 0; d3 !== r3; ) c2 += a3[d3++], d3 %= n4;
              if ((r3 = (r3 + 1) % n4) === i2 && (i2 = (i2 + 1) % n4), !(s2 - t4 < e4)) {
                var A2 = p2 && s2 - p2;
                return A2 ? Math.round(1e3 * c2 / A2) : void 0;
              }
            };
          }(50, 250);
          return function(o2) {
            var r3 = o2.loaded, i2 = o2.lengthComputable ? o2.total : void 0, l2 = r3 - t3, s2 = a2(l2);
            t3 = r3;
            var p2 = {
              loaded: r3,
              total: i2,
              progress: i2 ? r3 / i2 : void 0,
              bytes: l2,
              rate: s2 || void 0,
              estimated: s2 && i2 && r3 <= i2 ? (i2 - r3) / s2 : void 0,
              event: o2
            };
            p2[e3 ? "download" : "upload"] = true, n3(p2);
          };
        }
        const se = "undefined" != typeof XMLHttpRequest && function(n3) {
          return new Promise(function(e3, t3) {
            var a2, o2 = n3.data, r3 = $n.from(n3.headers).normalize(), i2 = n3.responseType;
            function l2() {
              n3.cancelToken && n3.cancelToken.unsubscribe(a2), n3.signal && n3.signal.removeEventListener("abort", a2);
            }
            cn.isFormData(o2) && (Mn.isStandardBrowserEnv || Mn.isStandardBrowserWebWorkerEnv) && r3.setContentType(false);
            var s2 = new XMLHttpRequest();
            if (n3.auth) {
              var p2 = n3.auth.username || "", d3 = n3.auth.password ? unescape(encodeURIComponent(n3.auth.password)) : "";
              r3.set("Authorization", "Basic " + btoa(p2 + ":" + d3));
            }
            var c2 = re(n3.baseURL, n3.url);
            function A2() {
              if (s2) {
                var a3 = $n.from("getAllResponseHeaders" in s2 && s2.getAllResponseHeaders());
                !function(n4, e4, t4) {
                  var a4 = t4.config.validateStatus;
                  t4.status && a4 && !a4(t4.status) ? e4(new mn("Request failed with status code " + t4.status, [mn.ERR_BAD_REQUEST, mn.ERR_BAD_RESPONSE][Math.floor(t4.status / 100) - 4], t4.config, t4.request, t4)) : n4(t4);
                }(function(n4) {
                  e3(n4), l2();
                }, function(n4) {
                  t3(n4), l2();
                }, {
                  data: i2 && "text" !== i2 && "json" !== i2 ? s2.response : s2.responseText,
                  status: s2.status,
                  statusText: s2.statusText,
                  headers: a3,
                  config: n3,
                  request: s2
                }), s2 = null;
              }
            }
            if (s2.open(n3.method.toUpperCase(), In(c2, n3.params, n3.paramsSerializer), true), s2.timeout = n3.timeout, "onloadend" in s2 ? s2.onloadend = A2 : s2.onreadystatechange = function() {
              s2 && 4 === s2.readyState && (0 !== s2.status || s2.responseURL && 0 === s2.responseURL.indexOf("file:")) && setTimeout(A2);
            }, s2.onabort = function() {
              s2 && (t3(new mn("Request aborted", mn.ECONNABORTED, n3, s2)), s2 = null);
            }, s2.onerror = function() {
              t3(new mn("Network Error", mn.ERR_NETWORK, n3, s2)), s2 = null;
            }, s2.ontimeout = function() {
              var e4 = n3.timeout ? "timeout of " + n3.timeout + "ms exceeded" : "timeout exceeded", a3 = n3.transitional || On;
              n3.timeoutErrorMessage && (e4 = n3.timeoutErrorMessage), t3(new mn(e4, a3.clarifyTimeoutError ? mn.ETIMEDOUT : mn.ECONNABORTED, n3, s2)), s2 = null;
            }, Mn.isStandardBrowserEnv) {
              var u2 = (n3.withCredentials || ie(c2)) && n3.xsrfCookieName && oe.read(n3.xsrfCookieName);
              u2 && r3.set(n3.xsrfHeaderName, u2);
            }
            void 0 === o2 && r3.setContentType(null), "setRequestHeader" in s2 && cn.forEach(r3.toJSON(), function(n4, e4) {
              s2.setRequestHeader(e4, n4);
            }), cn.isUndefined(n3.withCredentials) || (s2.withCredentials = !!n3.withCredentials), i2 && "json" !== i2 && (s2.responseType = n3.responseType), "function" == typeof n3.onDownloadProgress && s2.addEventListener("progress", le(n3.onDownloadProgress, true)), "function" == typeof n3.onUploadProgress && s2.upload && s2.upload.addEventListener("progress", le(n3.onUploadProgress)), (n3.cancelToken || n3.signal) && (a2 = function(e4) {
              s2 && (t3(!e4 || e4.type ? new ae(null, n3, s2) : e4), s2.abort(), s2 = null);
            }, n3.cancelToken && n3.cancelToken.subscribe(a2), n3.signal && (n3.signal.aborted ? a2() : n3.signal.addEventListener("abort", a2)));
            var y2, m2 = (y2 = /^([-+\w]{1,25})(:?\/\/|:)/.exec(c2)) && y2[1] || "";
            m2 && -1 === Mn.protocols.indexOf(m2) ? t3(new mn("Unsupported protocol " + m2 + ":", mn.ERR_BAD_REQUEST, n3)) : s2.send(o2 || null);
          });
        };
        var pe = {
          http: null,
          xhr: se
        };
        cn.forEach(pe, function(n3, e3) {
          if (n3) {
            try {
              Object.defineProperty(n3, "name", {
                value: e3
              });
            } catch (n4) {
            }
            Object.defineProperty(n3, "adapterName", {
              value: e3
            });
          }
        });
        function de(n3) {
          if (n3.cancelToken && n3.cancelToken.throwIfRequested(), n3.signal && n3.signal.aborted) throw new ae(null, n3);
        }
        function ce(n3) {
          return de(n3), n3.headers = $n.from(n3.headers), n3.data = ne.call(n3, n3.transformRequest), -1 !== ["post", "put", "patch"].indexOf(n3.method) && n3.headers.setContentType("application/x-www-form-urlencoded", false), function(n4) {
            for (var e3, t3, a2 = (n4 = cn.isArray(n4) ? n4 : [n4]).length, o2 = 0; o2 < a2 && (e3 = n4[o2], !(t3 = cn.isString(e3) ? pe[e3.toLowerCase()] : e3)); o2++) ;
            if (!t3) {
              if (false === t3) throw new mn("Adapter ".concat(e3, " is not supported by the environment"), "ERR_NOT_SUPPORT");
              throw new Error(cn.hasOwnProp(pe, e3) ? "Adapter '".concat(e3, "' is not available in the build") : "Unknown adapter '".concat(e3, "'"));
            }
            if (!cn.isFunction(t3)) throw new TypeError("adapter is not a function");
            return t3;
          }(n3.adapter || Nn.adapter)(n3).then(function(e3) {
            return de(n3), e3.data = ne.call(n3, n3.transformResponse, e3), e3.headers = $n.from(e3.headers), e3;
          }, function(e3) {
            return ee(e3) || (de(n3), e3 && e3.response && (e3.response.data = ne.call(n3, n3.transformResponse, e3.response), e3.response.headers = $n.from(e3.response.headers))), Promise.reject(e3);
          });
        }
        var Ae = function(n3) {
          return n3 instanceof $n ? n3.toJSON() : n3;
        };
        function ue(n3, e3) {
          e3 = e3 || {};
          var t3 = {};
          function a2(n4, e4, t4) {
            return cn.isPlainObject(n4) && cn.isPlainObject(e4) ? cn.merge.call({
              caseless: t4
            }, n4, e4) : cn.isPlainObject(e4) ? cn.merge({}, e4) : cn.isArray(e4) ? e4.slice() : e4;
          }
          function o2(n4, e4, t4) {
            return cn.isUndefined(e4) ? cn.isUndefined(n4) ? void 0 : a2(void 0, n4, t4) : a2(n4, e4, t4);
          }
          function r3(n4, e4) {
            if (!cn.isUndefined(e4)) return a2(void 0, e4);
          }
          function i2(n4, e4) {
            return cn.isUndefined(e4) ? cn.isUndefined(n4) ? void 0 : a2(void 0, n4) : a2(void 0, e4);
          }
          function l2(t4, o3, r4) {
            return r4 in e3 ? a2(t4, o3) : r4 in n3 ? a2(void 0, t4) : void 0;
          }
          var s2 = {
            url: r3,
            method: r3,
            data: r3,
            baseURL: i2,
            transformRequest: i2,
            transformResponse: i2,
            paramsSerializer: i2,
            timeout: i2,
            timeoutMessage: i2,
            withCredentials: i2,
            adapter: i2,
            responseType: i2,
            xsrfCookieName: i2,
            xsrfHeaderName: i2,
            onUploadProgress: i2,
            onDownloadProgress: i2,
            decompress: i2,
            maxContentLength: i2,
            maxBodyLength: i2,
            beforeRedirect: i2,
            transport: i2,
            httpAgent: i2,
            httpsAgent: i2,
            cancelToken: i2,
            socketPath: i2,
            responseEncoding: i2,
            validateStatus: l2,
            headers: function(n4, e4) {
              return o2(Ae(n4), Ae(e4), true);
            }
          };
          return cn.forEach(Object.keys(n3).concat(Object.keys(e3)), function(a3) {
            var r4 = s2[a3] || o2, i3 = r4(n3[a3], e3[a3], a3);
            cn.isUndefined(i3) && r4 !== l2 || (t3[a3] = i3);
          }), t3;
        }
        function ye(n3) {
          return ye = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, ye(n3);
        }
        var me = {};
        ["object", "boolean", "number", "function", "string", "symbol"].forEach(function(n3, e3) {
          me[n3] = function(t3) {
            return ye(t3) === n3 || "a" + (e3 < 1 ? "n " : " ") + n3;
          };
        });
        var he = {};
        me.transitional = function(n3, e3, t3) {
          function a2(n4, e4) {
            return "[Axios v1.2.3] Transitional option '" + n4 + "'" + e4 + (t3 ? ". " + t3 : "");
          }
          return function(t4, o2, r3) {
            if (false === n3) throw new mn(a2(o2, " has been removed" + (e3 ? " in " + e3 : "")), mn.ERR_DEPRECATED);
            return e3 && !he[o2] && (he[o2] = true, console.warn(a2(o2, " has been deprecated since v" + e3 + " and will be removed in the near future"))), !n3 || n3(t4, o2, r3);
          };
        };
        const fe = {
          assertOptions: function(n3, e3, t3) {
            if ("object" !== ye(n3)) throw new mn("options must be an object", mn.ERR_BAD_OPTION_VALUE);
            for (var a2 = Object.keys(n3), o2 = a2.length; o2-- > 0; ) {
              var r3 = a2[o2], i2 = e3[r3];
              if (i2) {
                var l2 = n3[r3], s2 = void 0 === l2 || i2(l2, r3, n3);
                if (true !== s2) throw new mn("option " + r3 + " must be " + s2, mn.ERR_BAD_OPTION_VALUE);
              } else if (true !== t3) throw new mn("Unknown option " + r3, mn.ERR_BAD_OPTION);
            }
          },
          validators: me
        };
        function be(n3) {
          return be = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, be(n3);
        }
        function ge(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== be(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== be(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === be(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var ve = fe.validators, xe = function() {
          function n3(e4) {
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.defaults = e4, this.interceptors = {
              request: new qn(),
              response: new qn()
            };
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "request",
            value: function(n4, e4) {
              "string" == typeof n4 ? (e4 = e4 || {}).url = n4 : e4 = n4 || {};
              var t4, a2 = e4 = ue(this.defaults, e4), o2 = a2.transitional, r3 = a2.paramsSerializer, i2 = a2.headers;
              void 0 !== o2 && fe.assertOptions(o2, {
                silentJSONParsing: ve.transitional(ve.boolean),
                forcedJSONParsing: ve.transitional(ve.boolean),
                clarifyTimeoutError: ve.transitional(ve.boolean)
              }, false), void 0 !== r3 && fe.assertOptions(r3, {
                encode: ve.function,
                serialize: ve.function
              }, true), e4.method = (e4.method || this.defaults.method || "get").toLowerCase(), (t4 = i2 && cn.merge(i2.common, i2[e4.method])) && cn.forEach(["delete", "get", "head", "post", "put", "patch", "common"], function(n5) {
                delete i2[n5];
              }), e4.headers = $n.concat(t4, i2);
              var l2 = [], s2 = true;
              this.interceptors.request.forEach(function(n5) {
                "function" == typeof n5.runWhen && false === n5.runWhen(e4) || (s2 = s2 && n5.synchronous, l2.unshift(n5.fulfilled, n5.rejected));
              });
              var p2, d3 = [];
              this.interceptors.response.forEach(function(n5) {
                d3.push(n5.fulfilled, n5.rejected);
              });
              var c2, A2 = 0;
              if (!s2) {
                var u2 = [ce.bind(this), void 0];
                for (u2.unshift.apply(u2, l2), u2.push.apply(u2, d3), c2 = u2.length, p2 = Promise.resolve(e4); A2 < c2; ) p2 = p2.then(u2[A2++], u2[A2++]);
                return p2;
              }
              c2 = l2.length;
              var y2 = e4;
              for (A2 = 0; A2 < c2; ) {
                var m2 = l2[A2++], h2 = l2[A2++];
                try {
                  y2 = m2(y2);
                } catch (n5) {
                  h2.call(this, n5);
                  break;
                }
              }
              try {
                p2 = ce.call(this, y2);
              } catch (n5) {
                return Promise.reject(n5);
              }
              for (A2 = 0, c2 = d3.length; A2 < c2; ) p2 = p2.then(d3[A2++], d3[A2++]);
              return p2;
            }
          }, {
            key: "getUri",
            value: function(n4) {
              return In(re((n4 = ue(this.defaults, n4)).baseURL, n4.url), n4.params, n4.paramsSerializer);
            }
          }]) && ge(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        cn.forEach(["delete", "get", "head", "options"], function(n3) {
          xe.prototype[n3] = function(e3, t3) {
            return this.request(ue(t3 || {}, {
              method: n3,
              url: e3,
              data: (t3 || {}).data
            }));
          };
        }), cn.forEach(["post", "put", "patch"], function(n3) {
          function e3(e4) {
            return function(t3, a2, o2) {
              return this.request(ue(o2 || {}, {
                method: n3,
                headers: e4 ? {
                  "Content-Type": "multipart/form-data"
                } : {},
                url: t3,
                data: a2
              }));
            };
          }
          xe.prototype[n3] = e3(), xe.prototype[n3 + "Form"] = e3(true);
        });
        const Ee = xe;
        function we(n3) {
          return we = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, we(n3);
        }
        function Ce(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== we(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== we(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === we(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var ke = function() {
          function n3(e4) {
            if (function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), "function" != typeof e4) throw new TypeError("executor must be a function.");
            var t4;
            this.promise = new Promise(function(n4) {
              t4 = n4;
            });
            var a3 = this;
            this.promise.then(function(n4) {
              if (a3._listeners) {
                for (var e5 = a3._listeners.length; e5-- > 0; ) a3._listeners[e5](n4);
                a3._listeners = null;
              }
            }), this.promise.then = function(n4) {
              var e5, t5 = new Promise(function(n5) {
                a3.subscribe(n5), e5 = n5;
              }).then(n4);
              return t5.cancel = function() {
                a3.unsubscribe(e5);
              }, t5;
            }, e4(function(n4, e5, o2) {
              a3.reason || (a3.reason = new ae(n4, e5, o2), t4(a3.reason));
            });
          }
          var e3, t3, a2;
          return e3 = n3, t3 = [{
            key: "throwIfRequested",
            value: function() {
              if (this.reason) throw this.reason;
            }
          }, {
            key: "subscribe",
            value: function(n4) {
              this.reason ? n4(this.reason) : this._listeners ? this._listeners.push(n4) : this._listeners = [n4];
            }
          }, {
            key: "unsubscribe",
            value: function(n4) {
              if (this._listeners) {
                var e4 = this._listeners.indexOf(n4);
                -1 !== e4 && this._listeners.splice(e4, 1);
              }
            }
          }], a2 = [{
            key: "source",
            value: function() {
              var e4;
              return {
                token: new n3(function(n4) {
                  e4 = n4;
                }),
                cancel: e4
              };
            }
          }], t3 && Ce(e3.prototype, t3), a2 && Ce(e3, a2), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const Be = ke;
        function Se(n3, e3) {
          (null == e3 || e3 > n3.length) && (e3 = n3.length);
          for (var t3 = 0, a2 = new Array(e3); t3 < e3; t3++) a2[t3] = n3[t3];
          return a2;
        }
        var Ie = {
          Continue: 100,
          SwitchingProtocols: 101,
          Processing: 102,
          EarlyHints: 103,
          Ok: 200,
          Created: 201,
          Accepted: 202,
          NonAuthoritativeInformation: 203,
          NoContent: 204,
          ResetContent: 205,
          PartialContent: 206,
          MultiStatus: 207,
          AlreadyReported: 208,
          ImUsed: 226,
          MultipleChoices: 300,
          MovedPermanently: 301,
          Found: 302,
          SeeOther: 303,
          NotModified: 304,
          UseProxy: 305,
          Unused: 306,
          TemporaryRedirect: 307,
          PermanentRedirect: 308,
          BadRequest: 400,
          Unauthorized: 401,
          PaymentRequired: 402,
          Forbidden: 403,
          NotFound: 404,
          MethodNotAllowed: 405,
          NotAcceptable: 406,
          ProxyAuthenticationRequired: 407,
          RequestTimeout: 408,
          Conflict: 409,
          Gone: 410,
          LengthRequired: 411,
          PreconditionFailed: 412,
          PayloadTooLarge: 413,
          UriTooLong: 414,
          UnsupportedMediaType: 415,
          RangeNotSatisfiable: 416,
          ExpectationFailed: 417,
          ImATeapot: 418,
          MisdirectedRequest: 421,
          UnprocessableEntity: 422,
          Locked: 423,
          FailedDependency: 424,
          TooEarly: 425,
          UpgradeRequired: 426,
          PreconditionRequired: 428,
          TooManyRequests: 429,
          RequestHeaderFieldsTooLarge: 431,
          UnavailableForLegalReasons: 451,
          InternalServerError: 500,
          NotImplemented: 501,
          BadGateway: 502,
          ServiceUnavailable: 503,
          GatewayTimeout: 504,
          HttpVersionNotSupported: 505,
          VariantAlsoNegotiates: 506,
          InsufficientStorage: 507,
          LoopDetected: 508,
          NotExtended: 510,
          NetworkAuthenticationRequired: 511
        };
        Object.entries(Ie).forEach(function(n3) {
          var e3, t3, a2 = (t3 = 2, function(n4) {
            if (Array.isArray(n4)) return n4;
          }(e3 = n3) || function(n4, e4) {
            var t4 = null == n4 ? null : "undefined" != typeof Symbol && n4[Symbol.iterator] || n4["@@iterator"];
            if (null != t4) {
              var a3, o3, r4, i2, l2 = [], s2 = true, p2 = false;
              try {
                if (r4 = (t4 = t4.call(n4)).next, 0 === e4) {
                  if (Object(t4) !== t4) return;
                  s2 = false;
                } else for (; !(s2 = (a3 = r4.call(t4)).done) && (l2.push(a3.value), l2.length !== e4); s2 = true) ;
              } catch (n5) {
                p2 = true, o3 = n5;
              } finally {
                try {
                  if (!s2 && null != t4.return && (i2 = t4.return(), Object(i2) !== i2)) return;
                } finally {
                  if (p2) throw o3;
                }
              }
              return l2;
            }
          }(e3, t3) || function(n4, e4) {
            if (n4) {
              if ("string" == typeof n4) return Se(n4, e4);
              var t4 = Object.prototype.toString.call(n4).slice(8, -1);
              return "Object" === t4 && n4.constructor && (t4 = n4.constructor.name), "Map" === t4 || "Set" === t4 ? Array.from(n4) : "Arguments" === t4 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t4) ? Se(n4, e4) : void 0;
            }
          }(e3, t3) || function() {
            throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
          }()), o2 = a2[0], r3 = a2[1];
          Ie[r3] = o2;
        });
        const Le = Ie;
        var ze = function n3(e3) {
          var t3 = new Ee(e3), a2 = q(Ee.prototype.request, t3);
          return cn.extend(a2, Ee.prototype, t3, {
            allOwnKeys: true
          }), cn.extend(a2, t3, null, {
            allOwnKeys: true
          }), a2.create = function(t4) {
            return n3(ue(e3, t4));
          }, a2;
        }(Nn);
        ze.Axios = Ee, ze.CanceledError = ae, ze.CancelToken = Be, ze.isCancel = ee, ze.VERSION = "1.2.3", ze.toFormData = En, ze.AxiosError = mn, ze.Cancel = ze.CanceledError, ze.all = function(n3) {
          return Promise.all(n3);
        }, ze.spread = function(n3) {
          return function(e3) {
            return n3.apply(null, e3);
          };
        }, ze.isAxiosError = function(n3) {
          return cn.isObject(n3) && true === n3.isAxiosError;
        }, ze.mergeConfig = ue, ze.AxiosHeaders = $n, ze.formToJSON = function(n3) {
          return Fn(cn.isHTMLForm(n3) ? new FormData(n3) : n3);
        }, ze.HttpStatusCode = Le, ze.default = ze;
        const Te = ze, qe = {
          send: function(n3) {
            Te.post(n3.url, n3.data).then(function(e3) {
              var t3 = e3.data;
              t3 && 0 === t3.code ? n3.success && n3.success(t3) : n3.error && n3.error(t3 && t3.msg);
            }).catch(function(e3) {
              console.error(e3), n3.error && n3.error();
            });
          },
          read: function(n3) {
            Te.get(n3.url).then(function(e3) {
              var t3 = e3.data;
              t3 && 0 === t3.code ? n3.success && n3.success(t3.data.map(function(n4) {
                return {
                  time: n4[0],
                  type: n4[1],
                  color: n4[2],
                  author: n4[3],
                  text: n4[4]
                };
              })) : n3.error && n3.error(t3 && t3.msg);
            }).catch(function(e3) {
              console.error(e3), n3.error && n3.error();
            });
          }
        };
        function Oe(n3) {
          return Oe = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Oe(n3);
        }
        function je(n3) {
          var e3 = this;
          this.lang = n3, this.fallbackLang = this.lang.includes("-") ? this.lang.split("-")[0] : this.lang, this.tran = function(n4) {
            return n4 = n4.toLowerCase(), Pe[e3.lang] && Pe[e3.lang][n4] ? Pe[e3.lang][n4] : Pe[e3.fallbackLang] && Pe[e3.fallbackLang][n4] ? Pe[e3.fallbackLang][n4] : De[n4] ? De[n4] : n4;
          };
        }
        var De = {
          "danmaku-loading": "Danmaku is loading",
          top: "Top",
          bottom: "Bottom",
          rolling: "Rolling",
          "input-danmaku-enter": "Input danmaku, hit Enter",
          "about-author": "About author",
          "dplayer-feedback": "DPlayer feedback",
          "about-dplayer": "About DPlayer",
          loop: "Loop",
          speed: "Speed",
          "opacity-danmaku": "Opacity for danmaku",
          normal: "Normal",
          "please-input-danmaku": "Please input danmaku content!",
          "set-danmaku-color": "Set danmaku color",
          "set-danmaku-type": "Set danmaku type",
          "show-danmaku": "Show danmaku",
          "video-failed": "Video load failed",
          "danmaku-failed": "Danmaku load failed",
          "danmaku-send-failed": "Danmaku send failed",
          "switching-quality": "Switching to %q quality",
          "switched-quality": "Switched to %q quality",
          ff: "FF %s s",
          rew: "REW %s s",
          "unlimited-danmaku": "Unlimited danmaku",
          "send-danmaku": "Send danmaku",
          setting: "Setting",
          fullscreen: "Full screen",
          "web-fullscreen": "Web full screen",
          send: "Send",
          screenshot: "Screenshot",
          airplay: "AirPlay",
          chromecast: "ChromeCast",
          subtitle: "Subtitle",
          off: "Off",
          "show-subs": "Show subtitle",
          "hide-subs": "Hide subtitle",
          volume: "Volume",
          live: "Live",
          "video-info": "Video info"
        }, Pe = {
          en: De,
          "zh-cn": {
            "danmaku-loading": "\u5F39\u5E55\u52A0\u8F7D\u4E2D",
            top: "\u9876\u90E8",
            bottom: "\u5E95\u90E8",
            rolling: "\u6EDA\u52A8",
            "input-danmaku-enter": "\u8F93\u5165\u5F39\u5E55\uFF0C\u56DE\u8F66\u53D1\u9001",
            "about-author": "\u5173\u4E8E\u4F5C\u8005",
            "dplayer-feedback": "\u64AD\u653E\u5668\u610F\u89C1\u53CD\u9988",
            "about-dplayer": "\u5173\u4E8E DPlayer \u64AD\u653E\u5668",
            loop: "\u6D17\u8111\u5FAA\u73AF",
            speed: "\u901F\u5EA6",
            "opacity-danmaku": "\u5F39\u5E55\u900F\u660E\u5EA6",
            normal: "\u6B63\u5E38",
            "please-input-danmaku": "\u8981\u8F93\u5165\u5F39\u5E55\u5185\u5BB9\u554A\u5582\uFF01",
            "set-danmaku-color": "\u8BBE\u7F6E\u5F39\u5E55\u989C\u8272",
            "set-danmaku-type": "\u8BBE\u7F6E\u5F39\u5E55\u7C7B\u578B",
            "show-danmaku": "\u663E\u793A\u5F39\u5E55",
            "video-failed": "\u89C6\u9891\u52A0\u8F7D\u5931\u8D25",
            "danmaku-failed": "\u5F39\u5E55\u52A0\u8F7D\u5931\u8D25",
            "danmaku-send-failed": "\u5F39\u5E55\u53D1\u9001\u5931\u8D25",
            "switching-quality": "\u6B63\u5728\u5207\u6362\u81F3 %q \u753B\u8D28",
            "switched-quality": "\u5DF2\u7ECF\u5207\u6362\u81F3 %q \u753B\u8D28",
            ff: "\u5FEB\u8FDB %s \u79D2",
            rew: "\u5FEB\u9000 %s \u79D2",
            "unlimited-danmaku": "\u6D77\u91CF\u5F39\u5E55",
            "send-danmaku": "\u53D1\u9001\u5F39\u5E55",
            setting: "\u8BBE\u7F6E",
            fullscreen: "\u5168\u5C4F",
            "web-fullscreen": "\u9875\u9762\u5168\u5C4F",
            send: "\u53D1\u9001",
            screenshot: "\u622A\u56FE",
            airplay: "\u65E0\u7EBF\u6295\u5C4F",
            chromecast: "ChromeCast",
            subtitle: "\u5B57\u5E55",
            off: "\u5173\u95ED",
            "show-subs": "\u663E\u793A\u5B57\u5E55",
            "hide-subs": "\u9690\u85CF\u5B57\u5E55",
            volume: "\u97F3\u91CF",
            live: "\u76F4\u64AD",
            "video-info": "\u89C6\u9891\u7EDF\u8BA1\u4FE1\u606F"
          },
          "zh-tw": {
            "danmaku-loading": "\u5F48\u5E55\u8F09\u5165\u4E2D",
            top: "\u9802\u90E8",
            bottom: "\u5E95\u90E8",
            rolling: "\u6EFE\u52D5",
            "input-danmaku-enter": "\u8F38\u5165\u5F48\u5E55\uFF0CEnter \u767C\u9001",
            "about-author": "\u95DC\u65BC\u4F5C\u8005",
            "dplayer-feedback": "\u64AD\u653E\u5668\u610F\u898B\u56DE\u994B",
            "about-dplayer": "\u95DC\u65BC DPlayer \u64AD\u653E\u5668",
            loop: "\u5FAA\u74B0\u64AD\u653E",
            speed: "\u901F\u5EA6",
            "opacity-danmaku": "\u5F48\u5E55\u900F\u660E\u5EA6",
            normal: "\u6B63\u5E38",
            "please-input-danmaku": "\u8ACB\u8F38\u5165\u5F48\u5E55\u5167\u5BB9\u554A\uFF01",
            "set-danmaku-color": "\u8A2D\u5B9A\u5F48\u5E55\u984F\u8272",
            "set-danmaku-type": "\u8A2D\u5B9A\u5F48\u5E55\u985E\u578B",
            "show-danmaku": "\u986F\u793A\u5F48\u5E55",
            "video-failed": "\u5F71\u7247\u8F09\u5165\u5931\u6557",
            "danmaku-failed": "\u5F48\u5E55\u8F09\u5165\u5931\u6557",
            "danmaku-send-failed": "\u5F48\u5E55\u767C\u9001\u5931\u6557",
            "switching-quality": "\u6B63\u5728\u5207\u63DB\u81F3 %q \u756B\u8CEA",
            "switched-quality": "\u5DF2\u7D93\u5207\u63DB\u81F3 %q \u756B\u8CEA",
            ff: "\u5FEB\u9032 %s \u79D2",
            rew: "\u5FEB\u9000 %s \u79D2",
            "unlimited-danmaku": "\u5DE8\u91CF\u5F48\u5E55",
            "send-danmaku": "\u767C\u9001\u5F48\u5E55",
            setting: "\u8A2D\u5B9A",
            fullscreen: "\u5168\u87A2\u5E55",
            "web-fullscreen": "\u9801\u9762\u5168\u87A2\u5E55",
            send: "\u767C\u9001",
            screenshot: "\u622A\u5716",
            airplay: "\u7121\u7DDA\u6295\u5C4F",
            chromecast: "ChromeCast",
            subtitle: "\u5B57\u5E55",
            off: "\u95DC\u9589",
            "show-subs": "\u986F\u793A\u5B57\u5E55",
            "hide-subs": "\u96B1\u85CF\u5B57\u5E55",
            volume: "\u97F3\u91CF",
            live: "\u76F4\u64AD",
            "video-info": "\u5F71\u7247\u7D71\u8A08\u8A0A\u606F"
          },
          "ko-kr": {
            "danmaku-loading": "Danmaku\uB97C \uBD88\uB7EC\uC624\uB294 \uC911\uC785\uB2C8\uB2E4.",
            top: "Top",
            bottom: "Bottom",
            rolling: "Rolling",
            "input-danmaku-enter": "Danmaku\uB97C \uC785\uB825\uD558\uACE0 Enter\uB97C \uB204\uB974\uC138\uC694.",
            "about-author": "\uB9CC\uB4E0\uC774",
            "dplayer-feedback": "\uD53C\uB4DC\uBC31 \uBCF4\uB0B4\uAE30",
            "about-dplayer": "DPlayer \uC815\uBCF4",
            loop: "\uBC18\uBCF5",
            speed: "\uBC30\uC18D",
            "opacity-danmaku": "Danmaku \uBD88\uD22C\uBA85\uB3C4",
            normal: "\uD45C\uC900",
            "please-input-danmaku": "Danmaku\uB97C \uC785\uB825\uD558\uC138\uC694!",
            "set-danmaku-color": "Danmaku \uC0C9\uC0C1",
            "set-danmaku-type": "Danmaku \uC124\uC815",
            "show-danmaku": "Danmaku \uD45C\uC2DC",
            "video-failed": "\uBE44\uB514\uC624\uB97C \uBD88\uB7EC\uC624\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.",
            "danmaku-failed": "Danmaku\uB97C \uBD88\uB7EC\uC624\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.",
            "danmaku-send-failed": "Danmaku \uC804\uC1A1\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.",
            "Switching to": "",
            "Switched to": "",
            "switching-quality": "\uC804\uD658 %q \uD654\uC9C8",
            "switched-quality": "\uC804\uD658 \uB428 %q \uD654\uC9C8",
            ff: "\uC55E\uC73C\uB85C %s \uCD08",
            rew: "\uB4A4\uB85C %s \uCD08",
            "unlimited-danmaku": "\uB05D\uC5C6\uB294 Danmaku",
            "send-danmaku": "Danmaku \uBCF4\uB0B4\uAE30",
            setting: "\uC124\uC815",
            fullscreen: "\uC804\uCCB4 \uD654\uBA74",
            "web-fullscreen": "\uC6F9 \uB0B4 \uC804\uCCB4\uD654\uBA74",
            send: "\uBCF4\uB0B4\uAE30",
            screenshot: "\uD654\uBA74 \uCEA1\uCCD0",
            airplay: "\uC5D0\uC5B4\uD50C\uB808\uC774",
            chromecast: "ChromeCast",
            subtitle: "\uBD80\uC81C",
            off: "\uB044\uB2E4",
            "show-subs": "\uC790\uB9C9 \uBCF4\uC774\uAE30",
            "hide-subs": "\uC790\uB9C9 \uC228\uAE30\uAE30",
            Volume: "\uBCFC\uB968",
            live: "\uC0DD\uBC29\uC1A1",
            "video-info": "\uBE44\uB514\uC624 \uC815\uBCF4"
          },
          de: {
            "danmaku-loading": "Danmaku l\xE4dt...",
            top: "Oben",
            bottom: "Unten",
            rolling: "Rollend",
            "input-danmaku-enter": "Dr\xFCcke Enter nach dem Einf\xFCgen vom Danmaku",
            "about-author": "\xDCber den Autor",
            "dplayer-feedback": "DPlayer Feedback",
            "about-dplayer": "\xDCber DPlayer",
            loop: "Wiederholen",
            speed: "Geschwindigkeit",
            "opacity-danmaku": "Transparenz f\xFCr Danmaku",
            normal: "Normal",
            "please-input-danmaku": "Bitte Danmaku Inhalt eingeben!",
            "set-danmaku-color": "Danmaku Farbe festlegen",
            "set-danmaku-type": "Danmaku Typ festlegen",
            "show-danmaku": "Zeige Danmaku",
            "video-failed": "Das Video konnte nicht geladen werden",
            "danmaku-failed": "Danmaku konnte nicht geladen werden",
            "danmaku-send-failed": "Das senden von Danmaku ist fehgeschlagen",
            "switching-quality": "Wechsle zur %q Qualit\xE4t",
            "switched-quality": "Zur %q Qualit\xE4t gewechselt",
            ff: "%s s Vorw\xE4rts",
            rew: "%s s Zur\xFCck",
            "unlimited-danmaku": "Unlimitiertes Danmaku",
            "send-danmaku": "Sende Danmaku",
            setting: "Einstellungen",
            fullscreen: "Vollbild",
            "web-fullscreen": "Browser Vollbild",
            send: "Senden",
            screenshot: "Screenshot",
            airplay: "AirPlay",
            "show-subs": "Zeige Untertitel",
            chromecast: "ChromeCast",
            subtitle: "Untertitel",
            off: "Schlie\xDFung",
            "hide-subs": "Verstecke Untertitel",
            volume: "Lautst\xE4rke",
            live: "Live",
            "video-info": "Video Info"
          }
        }, Re = t2(730), Ye = t2.n(Re), Me = t2(74), Fe = t2.n(Me), We = t2(437), Ue = t2.n(We), Ne = t2(644), Qe = t2.n(Ne), He = t2(324), _e = t2.n(He), Ke = t2(574), Ze = t2.n(Ke), Ve = t2(300), Xe = t2.n(Ve), Je = t2(934), Ge = t2.n(Je), $e = t2(428), nt = t2.n($e), et = t2(807), tt = t2.n(et), at = t2(338), ot = t2.n(at), rt = t2(254), it = t2.n(rt), lt = t2(965), st = t2.n(lt), pt = t2(113), dt = t2.n(pt), ct = t2(251), At = t2.n(ct), ut = t2(410), yt = t2.n(ut), mt = t2(182), ht = t2.n(mt), ft = t2(193), bt = t2.n(ft);
        const gt = {
          play: Ye(),
          pause: Fe(),
          volumeUp: Ue(),
          volumeDown: Qe(),
          volumeOff: _e(),
          full: Ze(),
          fullWeb: Xe(),
          setting: Ge(),
          right: nt(),
          comment: tt(),
          commentOff: ot(),
          send: it(),
          pallette: st(),
          camera: dt(),
          subtitle: yt(),
          loading: ht(),
          airplay: At(),
          chromecast: bt()
        };
        var vt = t2(916), xt = t2.n(vt);
        function Et(n3) {
          return Et = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Et(n3);
        }
        function wt(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== Et(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== Et(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === Et(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Ct = function() {
          function n3(e4) {
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.container = e4.container, this.options = e4.options, this.index = e4.index, this.tran = e4.tran, this.init();
          }
          var e3, t3, a2;
          return e3 = n3, a2 = [{
            key: "NewNotice",
            value: function(n4, e4, t4) {
              var a3 = document.createElement("div");
              return a3.classList.add("dplayer-notice"), a3.style.opacity = e4, a3.innerText = n4, t4 && (a3.id = "dplayer-notice-".concat(t4)), a3;
            }
          }], (t3 = [{
            key: "init",
            value: function() {
              this.container.innerHTML = xt()({
                options: this.options,
                index: this.index,
                tran: this.tran,
                icons: gt,
                mobile: T.isMobile,
                video: {
                  current: true,
                  pic: this.options.video.pic,
                  screenshot: this.options.screenshot,
                  airplay: !(!T.isSafari || T.isChrome) && this.options.airplay,
                  chromecast: this.options.chromecast,
                  preload: this.options.preload,
                  url: this.options.video.url,
                  subtitle: this.options.subtitle
                }
              }), this.volumeBar = this.container.querySelector(".dplayer-volume-bar-inner"), this.volumeBarWrap = this.container.querySelector(".dplayer-volume-bar"), this.volumeBarWrapWrap = this.container.querySelector(".dplayer-volume-bar-wrap"), this.volumeButton = this.container.querySelector(".dplayer-volume"), this.volumeButtonIcon = this.container.querySelector(".dplayer-volume-icon"), this.volumeIcon = this.container.querySelector(".dplayer-volume-icon .dplayer-icon-content"), this.playedBar = this.container.querySelector(".dplayer-played"), this.loadedBar = this.container.querySelector(".dplayer-loaded"), this.playedBarWrap = this.container.querySelector(".dplayer-bar-wrap"), this.playedBarTime = this.container.querySelector(".dplayer-bar-time"), this.danmaku = this.container.querySelector(".dplayer-danmaku"), this.danmakuLoading = this.container.querySelector(".dplayer-danloading"), this.video = this.container.querySelector(".dplayer-video-current"), this.bezel = this.container.querySelector(".dplayer-bezel-icon"), this.playButton = this.container.querySelector(".dplayer-play-icon"), this.mobilePlayButton = this.container.querySelector(".dplayer-mobile-play"), this.videoWrap = this.container.querySelector(".dplayer-video-wrap"), this.controllerMask = this.container.querySelector(".dplayer-controller-mask"), this.ptime = this.container.querySelector(".dplayer-ptime"), this.settingButton = this.container.querySelector(".dplayer-setting-icon"), this.settingBox = this.container.querySelector(".dplayer-setting-box"), this.mask = this.container.querySelector(".dplayer-mask"), this.loop = this.container.querySelector(".dplayer-setting-loop"), this.loopToggle = this.container.querySelector(".dplayer-setting-loop .dplayer-toggle-setting-input"), this.showDanmaku = this.container.querySelector(".dplayer-setting-showdan"), this.showDanmakuToggle = this.container.querySelector(".dplayer-showdan-setting-input"), this.unlimitDanmaku = this.container.querySelector(".dplayer-setting-danunlimit"), this.unlimitDanmakuToggle = this.container.querySelector(".dplayer-danunlimit-setting-input"), this.speed = this.container.querySelector(".dplayer-setting-speed"), this.speedItem = this.container.querySelectorAll(".dplayer-setting-speed-item"), this.danmakuOpacityBar = this.container.querySelector(".dplayer-danmaku-bar-inner"), this.danmakuOpacityBarWrap = this.container.querySelector(".dplayer-danmaku-bar"), this.danmakuOpacityBarWrapWrap = this.container.querySelector(".dplayer-danmaku-bar-wrap"), this.danmakuOpacityBox = this.container.querySelector(".dplayer-setting-danmaku"), this.dtime = this.container.querySelector(".dplayer-dtime"), this.controller = this.container.querySelector(".dplayer-controller"), this.commentInput = this.container.querySelector(".dplayer-comment-input"), this.commentButton = this.container.querySelector(".dplayer-comment-icon"), this.commentSettingBox = this.container.querySelector(".dplayer-comment-setting-box"), this.commentSettingButton = this.container.querySelector(".dplayer-comment-setting-icon"), this.commentSettingFill = this.container.querySelector(".dplayer-comment-setting-icon path"), this.commentSendButton = this.container.querySelector(".dplayer-send-icon"), this.commentSendFill = this.container.querySelector(".dplayer-send-icon path"), this.commentColorSettingBox = this.container.querySelector(".dplayer-comment-setting-color"), this.browserFullButton = this.container.querySelector(".dplayer-full-icon"), this.webFullButton = this.container.querySelector(".dplayer-full-in-icon"), this.menu = this.container.querySelector(".dplayer-menu"), this.menuItem = this.container.querySelectorAll(".dplayer-menu-item"), this.qualityList = this.container.querySelector(".dplayer-quality-list"), this.camareButton = this.container.querySelector(".dplayer-camera-icon"), this.airplayButton = this.container.querySelector(".dplayer-airplay-icon"), this.chromecastButton = this.container.querySelector(".dplayer-chromecast-icon"), this.subtitleButton = this.container.querySelector(".dplayer-subtitle-icon"), this.subtitleButtonInner = this.container.querySelector(".dplayer-subtitle-icon .dplayer-icon-content"), this.subtitlesButton = this.container.querySelector(".dplayer-subtitles-icon"), this.subtitlesBox = this.container.querySelector(".dplayer-subtitles-box"), this.subtitlesItem = this.container.querySelectorAll(".dplayer-subtitles-item"), this.subtitle = this.container.querySelector(".dplayer-subtitle"), this.subtrack = this.container.querySelector(".dplayer-subtrack"), this.qualityButton = this.container.querySelector(".dplayer-quality-icon"), this.barPreview = this.container.querySelector(".dplayer-bar-preview"), this.barWrap = this.container.querySelector(".dplayer-bar-wrap"), this.noticeList = this.container.querySelector(".dplayer-notice-list"), this.infoPanel = this.container.querySelector(".dplayer-info-panel"), this.infoPanelClose = this.container.querySelector(".dplayer-info-panel-close"), this.infoVersion = this.container.querySelector(".dplayer-info-panel-item-version .dplayer-info-panel-item-data"), this.infoFPS = this.container.querySelector(".dplayer-info-panel-item-fps .dplayer-info-panel-item-data"), this.infoType = this.container.querySelector(".dplayer-info-panel-item-type .dplayer-info-panel-item-data"), this.infoUrl = this.container.querySelector(".dplayer-info-panel-item-url .dplayer-info-panel-item-data"), this.infoResolution = this.container.querySelector(".dplayer-info-panel-item-resolution .dplayer-info-panel-item-data"), this.infoDuration = this.container.querySelector(".dplayer-info-panel-item-duration .dplayer-info-panel-item-data"), this.infoDanmakuId = this.container.querySelector(".dplayer-info-panel-item-danmaku-id .dplayer-info-panel-item-data"), this.infoDanmakuApi = this.container.querySelector(".dplayer-info-panel-item-danmaku-api .dplayer-info-panel-item-data"), this.infoDanmakuAmount = this.container.querySelector(".dplayer-info-panel-item-danmaku-amount .dplayer-info-panel-item-data");
            }
          }]) && wt(e3.prototype, t3), a2 && wt(e3, a2), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const kt = Ct;
        function Bt(n3) {
          return Bt = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Bt(n3);
        }
        function St(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== Bt(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== Bt(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === Bt(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var It = function() {
          function n3(e4) {
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.options = e4, this.player = this.options.player, this.container = this.options.container, this.danTunnel = {
              right: {},
              top: {},
              bottom: {}
            }, this.danIndex = 0, this.dan = [], this.showing = true, this._opacity = this.options.opacity, this.events = this.options.events, this.unlimited = this.options.unlimited, this._measure(""), this.load();
          }
          var e3, t3;
          return e3 = n3, t3 = [{
            key: "load",
            value: function() {
              var n4, e4 = this;
              n4 = this.options.api.maximum ? "".concat(this.options.api.address, "v3/?id=").concat(this.options.api.id, "&max=").concat(this.options.api.maximum) : "".concat(this.options.api.address, "v3/?id=").concat(this.options.api.id);
              var t4 = (this.options.api.addition || []).slice(0);
              t4.push(n4), this.events && this.events.trigger("danmaku_load_start", t4), this._readAllEndpoints(t4, function(n5) {
                e4.dan = [].concat.apply([], n5).sort(function(n6, e5) {
                  return n6.time - e5.time;
                }), window.requestAnimationFrame(function() {
                  e4.frame();
                }), e4.options.callback(), e4.events && e4.events.trigger("danmaku_load_end");
              });
            }
          }, {
            key: "reload",
            value: function(n4) {
              this.options.api = n4, this.dan = [], this.clear(), this.load();
            }
          }, {
            key: "_readAllEndpoints",
            value: function(n4, e4) {
              for (var t4 = this, a2 = [], o2 = 0, r3 = function(r4) {
                t4.options.apiBackend.read({
                  url: n4[r4],
                  success: function(t5) {
                    a2[r4] = t5, ++o2 === n4.length && e4(a2);
                  },
                  error: function(i3) {
                    t4.options.error(i3 || t4.options.tran("danmaku-failed")), a2[r4] = [], ++o2 === n4.length && e4(a2);
                  }
                });
              }, i2 = 0; i2 < n4.length; ++i2) r3(i2);
            }
          }, {
            key: "send",
            value: function(n4, e4) {
              var t4 = this, a2 = {
                token: this.options.api.token,
                id: this.options.api.id,
                author: this.options.api.user,
                time: this.options.time(),
                text: n4.text,
                color: n4.color,
                type: n4.type
              };
              this.options.apiBackend.send({
                url: this.options.api.address + "v3/",
                data: a2,
                success: e4,
                error: function(n5) {
                  t4.options.error(n5 || t4.options.tran("danmaku-failed"));
                }
              }), this.dan.splice(this.danIndex, 0, a2), this.danIndex++;
              var o2 = {
                text: this.htmlEncode(a2.text),
                color: a2.color,
                type: a2.type,
                border: "2px solid ".concat(this.options.borderColor)
              };
              this.draw(o2), this.events && this.events.trigger("danmaku_send", a2);
            }
          }, {
            key: "frame",
            value: function() {
              var n4 = this;
              if (this.dan.length && !this.paused && this.showing) {
                for (var e4 = this.dan[this.danIndex], t4 = []; e4 && this.options.time() > parseFloat(e4.time); ) t4.push(e4), e4 = this.dan[++this.danIndex];
                this.draw(t4);
              }
              window.requestAnimationFrame(function() {
                n4.frame();
              });
            }
          }, {
            key: "opacity",
            value: function(n4) {
              if (void 0 !== n4) {
                for (var e4 = this.container.getElementsByClassName("dplayer-danmaku-item"), t4 = 0; t4 < e4.length; t4++) e4[t4].style.opacity = n4;
                this._opacity = n4, this.events && this.events.trigger("danmaku_opacity", this._opacity);
              }
              return this._opacity;
            }
          }, {
            key: "draw",
            value: function(n4) {
              var e4 = this;
              if (this.showing) {
                var t4 = this.options.height, a2 = this.container.offsetWidth, o2 = this.container.offsetHeight, r3 = parseInt(o2 / t4), i2 = function(n5) {
                  var t5 = n5.offsetWidth || parseInt(n5.style.width), a3 = n5.getBoundingClientRect().right || e4.container.getBoundingClientRect().right + t5;
                  return e4.container.getBoundingClientRect().right - a3;
                }, l2 = function(n5) {
                  return (a2 + n5) / 5;
                }, s2 = function(n5, t5, o3) {
                  for (var s3 = a2 / l2(o3), p3 = function(o4) {
                    var p4 = e4.danTunnel[t5][o4 + ""];
                    if (!p4 || !p4.length) return e4.danTunnel[t5][o4 + ""] = [n5], n5.addEventListener("animationend", function() {
                      e4.danTunnel[t5][o4 + ""].splice(0, 1);
                    }), {
                      v: o4 % r3
                    };
                    if ("right" !== t5) return "continue";
                    for (var d5 = 0; d5 < p4.length; d5++) {
                      var c4 = i2(p4[d5]) - 10;
                      if (c4 <= a2 - s3 * l2(parseInt(p4[d5].style.width)) || c4 <= 0) break;
                      if (d5 === p4.length - 1) return e4.danTunnel[t5][o4 + ""].push(n5), n5.addEventListener("animationend", function() {
                        e4.danTunnel[t5][o4 + ""].splice(0, 1);
                      }), {
                        v: o4 % r3
                      };
                    }
                  }, d4 = 0; e4.unlimited || d4 < r3; d4++) {
                    var c3 = p3(d4);
                    if ("continue" !== c3 && "object" === Bt(c3)) return c3.v;
                  }
                  return -1;
                };
                "[object Array]" !== Object.prototype.toString.call(n4) && (n4 = [n4]);
                for (var p2 = document.createDocumentFragment(), d3 = function() {
                  n4[c2].type = T.number2Type(n4[c2].type), n4[c2].color || (n4[c2].color = 16777215);
                  var o3 = document.createElement("div");
                  o3.classList.add("dplayer-danmaku-item"), o3.classList.add("dplayer-danmaku-".concat(n4[c2].type)), n4[c2].border ? o3.innerHTML = '<span style="border:'.concat(n4[c2].border, '">').concat(n4[c2].text, "</span>") : o3.innerHTML = n4[c2].text, o3.style.opacity = e4._opacity, o3.style.color = T.number2Color(n4[c2].color), o3.addEventListener("animationend", function() {
                    e4.container.removeChild(o3);
                  });
                  var r4, i3 = e4._measure(n4[c2].text);
                  switch (n4[c2].type) {
                    case "right":
                      (r4 = s2(o3, n4[c2].type, i3)) >= 0 && (o3.style.width = i3 + 1 + "px", o3.style.top = t4 * r4 + "px", o3.style.transform = "translateX(-".concat(a2, "px)"));
                      break;
                    case "top":
                      (r4 = s2(o3, n4[c2].type)) >= 0 && (o3.style.top = t4 * r4 + "px");
                      break;
                    case "bottom":
                      (r4 = s2(o3, n4[c2].type)) >= 0 && (o3.style.bottom = t4 * r4 + "px");
                      break;
                    default:
                      console.error("Can't handled danmaku type: ".concat(n4[c2].type));
                  }
                  r4 >= 0 && (o3.classList.add("dplayer-danmaku-move"), o3.style.animationDuration = e4._danAnimation(n4[c2].type), p2.appendChild(o3));
                }, c2 = 0; c2 < n4.length; c2++) d3();
                return this.container.appendChild(p2), p2;
              }
            }
          }, {
            key: "play",
            value: function() {
              this.paused = false;
            }
          }, {
            key: "pause",
            value: function() {
              this.paused = true;
            }
          }, {
            key: "_measure",
            value: function(n4) {
              if (!this.context) {
                var e4 = getComputedStyle(this.container.getElementsByClassName("dplayer-danmaku-item")[0], null);
                this.context = document.createElement("canvas").getContext("2d"), this.context.font = e4.getPropertyValue("font");
              }
              return this.context.measureText(n4).width;
            }
          }, {
            key: "seek",
            value: function() {
              this.clear();
              for (var n4 = 0; n4 < this.dan.length; n4++) {
                if (this.dan[n4].time >= this.options.time()) {
                  this.danIndex = n4;
                  break;
                }
                this.danIndex = this.dan.length;
              }
            }
          }, {
            key: "clear",
            value: function() {
              this.danTunnel = {
                right: {},
                top: {},
                bottom: {}
              }, this.danIndex = 0, this.options.container.innerHTML = "", this.events && this.events.trigger("danmaku_clear");
            }
          }, {
            key: "htmlEncode",
            value: function(n4) {
              return n4.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;").replace(/\//g, "&#x2f;");
            }
          }, {
            key: "resize",
            value: function() {
              for (var n4 = this.container.offsetWidth, e4 = this.container.getElementsByClassName("dplayer-danmaku-item"), t4 = 0; t4 < e4.length; t4++) e4[t4].style.transform = "translateX(-".concat(n4, "px)");
            }
          }, {
            key: "hide",
            value: function() {
              this.showing = false, this.pause(), this.clear(), this.events && this.events.trigger("danmaku_hide");
            }
          }, {
            key: "show",
            value: function() {
              this.seek(), this.showing = true, this.play(), this.events && this.events.trigger("danmaku_show");
            }
          }, {
            key: "unlimit",
            value: function(n4) {
              this.unlimited = n4;
            }
          }, {
            key: "speed",
            value: function(n4) {
              this.options.api.speedRate = n4;
            }
          }, {
            key: "_danAnimation",
            value: function(n4) {
              var e4 = this.options.api.speedRate || 1, t4 = !!this.player.fullScreen.isFullScreen();
              return {
                top: "".concat((t4 ? 6 : 4) / e4, "s"),
                right: "".concat((t4 ? 8 : 5) / e4, "s"),
                bottom: "".concat((t4 ? 6 : 4) / e4, "s")
              }[n4];
            }
          }], t3 && St(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const Lt = It;
        function zt(n3) {
          return zt = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, zt(n3);
        }
        function Tt(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== zt(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== zt(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === zt(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        const qt = function() {
          function n3() {
            !function(n4, e4) {
              if (!(n4 instanceof e4)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.events = {}, this.videoEvents = ["abort", "canplay", "canplaythrough", "durationchange", "emptied", "ended", "error", "loadeddata", "loadedmetadata", "loadstart", "mozaudioavailable", "pause", "play", "playing", "progress", "ratechange", "seeked", "seeking", "stalled", "suspend", "timeupdate", "volumechange", "waiting"], this.playerEvents = ["screenshot", "thumbnails_show", "thumbnails_hide", "danmaku_show", "danmaku_hide", "danmaku_clear", "danmaku_loaded", "danmaku_send", "danmaku_opacity", "contextmenu_show", "contextmenu_hide", "notice_show", "notice_hide", "quality_start", "quality_end", "destroy", "resize", "fullscreen", "fullscreen_cancel", "webfullscreen", "webfullscreen_cancel", "subtitle_show", "subtitle_hide", "subtitle_change"];
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "on",
            value: function(n4, e4) {
              this.type(n4) && "function" == typeof e4 && (this.events[n4] || (this.events[n4] = []), this.events[n4].push(e4));
            }
          }, {
            key: "trigger",
            value: function(n4, e4) {
              if (this.events[n4] && this.events[n4].length) for (var t4 = 0; t4 < this.events[n4].length; t4++) this.events[n4][t4](e4);
            }
          }, {
            key: "type",
            value: function(n4) {
              return -1 !== this.playerEvents.indexOf(n4) ? "player" : -1 !== this.videoEvents.indexOf(n4) ? "video" : (console.error("Unknown event name: ".concat(n4)), null);
            }
          }]) && Tt(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        function Ot(n3) {
          return Ot = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Ot(n3);
        }
        function jt(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== Ot(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== Ot(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === Ot(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Dt = function() {
          function n3(e4) {
            var t4 = this;
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.player = e4, this.lastScrollPosition = {
              left: 0,
              top: 0
            }, this.player.events.on("webfullscreen", function() {
              t4.player.resize();
            }), this.player.events.on("webfullscreen_cancel", function() {
              t4.player.resize(), T.setScrollPosition(t4.lastScrollPosition);
            }), this.fullscreenchange = function() {
              t4.player.resize(), t4.isFullScreen("browser") ? t4.player.events.trigger("fullscreen") : (T.setScrollPosition(t4.lastScrollPosition), t4.player.events.trigger("fullscreen_cancel"));
            }, this.docfullscreenchange = function() {
              var n4 = document.fullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
              n4 && n4 !== t4.player.container || (t4.player.resize(), n4 ? t4.player.events.trigger("fullscreen") : (T.setScrollPosition(t4.lastScrollPosition), t4.player.events.trigger("fullscreen_cancel")));
            }, /Firefox/.test(navigator.userAgent) ? (document.addEventListener("mozfullscreenchange", this.docfullscreenchange), document.addEventListener("fullscreenchange", this.docfullscreenchange)) : (this.player.container.addEventListener("fullscreenchange", this.fullscreenchange), this.player.container.addEventListener("webkitfullscreenchange", this.fullscreenchange), document.addEventListener("msfullscreenchange", this.docfullscreenchange), document.addEventListener("MSFullscreenChange", this.docfullscreenchange));
          }
          var e3, t3;
          return e3 = n3, t3 = [{
            key: "isFullScreen",
            value: function() {
              var n4 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "browser";
              switch (n4) {
                case "browser":
                  return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement;
                case "web":
                  return this.player.container.classList.contains("dplayer-fulled");
              }
            }
          }, {
            key: "request",
            value: function() {
              var n4 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "browser", e4 = "browser" === n4 ? "web" : "browser", t4 = this.isFullScreen(e4);
              switch (t4 || (this.lastScrollPosition = T.getScrollPosition()), n4) {
                case "browser":
                  this.player.container.requestFullscreen ? this.player.container.requestFullscreen() : this.player.container.mozRequestFullScreen ? this.player.container.mozRequestFullScreen() : this.player.container.webkitRequestFullscreen ? this.player.container.webkitRequestFullscreen() : this.player.video.webkitEnterFullscreen ? this.player.video.webkitEnterFullscreen() : this.player.video.webkitEnterFullScreen ? this.player.video.webkitEnterFullScreen() : this.player.container.msRequestFullscreen && this.player.container.msRequestFullscreen();
                  break;
                case "web":
                  this.player.container.classList.add("dplayer-fulled"), document.body.classList.add("dplayer-web-fullscreen-fix"), this.player.events.trigger("webfullscreen");
              }
              t4 && this.cancel(e4);
            }
          }, {
            key: "cancel",
            value: function() {
              var n4 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "browser";
              switch (n4) {
                case "browser":
                  document.cancelFullScreen ? document.cancelFullScreen() : document.mozCancelFullScreen ? document.mozCancelFullScreen() : document.webkitCancelFullScreen ? document.webkitCancelFullScreen() : document.webkitCancelFullscreen ? document.webkitCancelFullscreen() : document.msCancelFullScreen ? document.msCancelFullScreen() : document.msExitFullscreen && document.msExitFullscreen();
                  break;
                case "web":
                  this.player.container.classList.remove("dplayer-fulled"), document.body.classList.remove("dplayer-web-fullscreen-fix"), this.player.events.trigger("webfullscreen_cancel");
              }
            }
          }, {
            key: "toggle",
            value: function() {
              var n4 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "browser";
              this.isFullScreen(n4) ? this.cancel(n4) : this.request(n4);
            }
          }, {
            key: "destroy",
            value: function() {
              /Firefox/.test(navigator.userAgent) ? (document.removeEventListener("mozfullscreenchange", this.docfullscreenchange), document.removeEventListener("fullscreenchange", this.docfullscreenchange)) : (this.player.container.removeEventListener("fullscreenchange", this.fullscreenchange), this.player.container.removeEventListener("webkitfullscreenchange", this.fullscreenchange), document.removeEventListener("msfullscreenchange", this.docfullscreenchange), document.removeEventListener("MSFullscreenChange", this.docfullscreenchange));
            }
          }], t3 && jt(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const Pt = Dt;
        function Rt(n3) {
          return Rt = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Rt(n3);
        }
        function Yt(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== Rt(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== Rt(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === Rt(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Mt = function() {
          function n3(e4) {
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.storageName = {
              opacity: "dplayer-danmaku-opacity",
              volume: "dplayer-volume",
              unlimited: "dplayer-danmaku-unlimited",
              danmaku: "dplayer-danmaku-show",
              subtitle: "dplayer-subtitle-show"
            }, this.default = {
              opacity: 0.7,
              volume: e4.options.hasOwnProperty("volume") ? e4.options.volume : 0.7,
              unlimited: (e4.options.danmaku && e4.options.danmaku.unlimited ? 1 : 0) || 0,
              danmaku: 1,
              subtitle: 1
            }, this.data = {}, this.init();
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "init",
            value: function() {
              for (var n4 in this.storageName) {
                var e4 = this.storageName[n4];
                this.data[n4] = parseFloat(T.storage.get(e4) || this.default[n4]);
              }
            }
          }, {
            key: "get",
            value: function(n4) {
              return this.data[n4];
            }
          }, {
            key: "set",
            value: function(n4, e4) {
              this.data[n4] = e4, T.storage.set(this.storageName[n4], e4);
            }
          }]) && Yt(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const Ft = Mt;
        function Wt(n3) {
          return Wt = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Wt(n3);
        }
        function Ut(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== Wt(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== Wt(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === Wt(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Nt = function() {
          function n3(e4, t4, a2, o2) {
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.container = e4, this.video = t4, this.options = a2, this.events = o2, this.init();
          }
          var e3, t3;
          return e3 = n3, t3 = [{
            key: "init",
            value: function() {
              var n4 = this;
              if (this.container.style.fontSize = this.options.fontSize, this.container.style.bottom = this.options.bottom, this.container.style.color = this.options.color, this.video.textTracks && this.video.textTracks[0]) {
                var e4 = this.video.textTracks[0];
                e4.oncuechange = function() {
                  var t4 = e4.activeCues[e4.activeCues.length - 1];
                  if (n4.container.innerHTML = "", t4) {
                    var a2 = document.createElement("div");
                    a2.appendChild(t4.getCueAsHTML());
                    var o2 = a2.innerHTML.split(/\r?\n/).map(function(n5) {
                      return "<p>".concat(n5, "</p>");
                    }).join("");
                    n4.container.innerHTML = o2;
                  }
                  n4.events.trigger("subtitle_change");
                };
              }
            }
          }, {
            key: "show",
            value: function() {
              this.container.classList.remove("dplayer-subtitle-hide"), this.events.trigger("subtitle_show");
            }
          }, {
            key: "hide",
            value: function() {
              this.container.classList.add("dplayer-subtitle-hide"), this.events.trigger("subtitle_hide");
            }
          }, {
            key: "toggle",
            value: function() {
              this.container.classList.contains("dplayer-subtitle-hide") ? this.show() : this.hide();
            }
          }], t3 && Ut(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const Qt = Nt;
        function Ht(n3) {
          return Ht = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Ht(n3);
        }
        function _t(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== Ht(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== Ht(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === Ht(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Kt = function() {
          function n3(e4) {
            var t4 = this;
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.player = e4, this.player.template.mask.addEventListener("click", function() {
              t4.hide();
            }), this.player.template.subtitlesButton.addEventListener("click", function() {
              t4.adaptiveHeight(), t4.show();
            });
            for (var a2 = this.player.template.subtitlesItem.length - 1, o2 = function(n4) {
              t4.player.template.subtitlesItem[n4].addEventListener("click", function() {
                t4.hide(), t4.player.options.subtitle.index !== n4 && (t4.player.template.subtitle.innerHTML = "<p></p>", t4.player.template.subtrack.src = t4.player.template.subtitlesItem[n4].dataset.subtitle, t4.player.options.subtitle.index = n4, t4.player.template.subtitle.classList.contains("dplayer-subtitle-hide") && t4.subContainerShow());
              });
            }, r3 = 0; r3 < a2; r3++) o2(r3);
            this.player.template.subtitlesItem[a2].addEventListener("click", function() {
              t4.hide(), t4.player.options.subtitle.index !== a2 && (t4.player.template.subtitle.innerHTML = "<p></p>", t4.player.template.subtrack.src = "", t4.player.options.subtitle.index = a2, t4.subContainerHide());
            });
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "subContainerShow",
            value: function() {
              this.player.template.subtitle.classList.remove("dplayer-subtitle-hide"), this.player.events.trigger("subtitle_show");
            }
          }, {
            key: "subContainerHide",
            value: function() {
              this.player.template.subtitle.classList.add("dplayer-subtitle-hide"), this.player.events.trigger("subtitle_hide");
            }
          }, {
            key: "hide",
            value: function() {
              this.player.template.subtitlesBox.classList.remove("dplayer-subtitles-box-open"), this.player.template.mask.classList.remove("dplayer-mask-show"), this.player.controller.disableAutoHide = false;
            }
          }, {
            key: "show",
            value: function() {
              this.player.template.subtitlesBox.classList.add("dplayer-subtitles-box-open"), this.player.template.mask.classList.add("dplayer-mask-show"), this.player.controller.disableAutoHide = true;
            }
          }, {
            key: "adaptiveHeight",
            value: function() {
              var n4 = 30 * this.player.template.subtitlesItem.length + 14, e4 = 0.8 * this.player.template.videoWrap.offsetHeight;
              n4 >= e4 - 50 ? (this.player.template.subtitlesBox.style.bottom = "8px", this.player.template.subtitlesBox.style["max-height"] = e4 - 8 + "px") : (this.player.template.subtitlesBox.style.bottom = "50px", this.player.template.subtitlesBox.style["max-height"] = e4 - 50 + "px");
            }
          }]) && _t(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const Zt = Kt;
        function Vt(n3) {
          return Vt = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Vt(n3);
        }
        function Xt(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== Vt(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== Vt(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === Vt(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Jt = function() {
          function n3(e4) {
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.elements = {}, this.elements.volume = e4.volumeBar, this.elements.played = e4.playedBar, this.elements.loaded = e4.loadedBar, this.elements.danmaku = e4.danmakuOpacityBar;
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "set",
            value: function(n4, e4, t4) {
              e4 = Math.max(e4, 0), e4 = Math.min(e4, 1), this.elements[n4].style[t4] = 100 * e4 + "%";
            }
          }, {
            key: "get",
            value: function(n4) {
              return parseFloat(this.elements[n4].style.width) / 100;
            }
          }]) && Xt(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const Gt = Jt;
        function $t(n3) {
          return $t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, $t(n3);
        }
        function na(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== $t(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== $t(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === $t(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var ea = function() {
          function n3(e4) {
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.player = e4, window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(n4) {
              window.setTimeout(n4, 1e3 / 60);
            }, this.types = ["loading", "info", "fps"], this.init();
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "init",
            value: function() {
              var n4 = this;
              this.types.map(function(e4) {
                return "fps" !== e4 && n4["init".concat(e4, "Checker")](), e4;
              });
            }
          }, {
            key: "initloadingChecker",
            value: function() {
              var n4 = this, e4 = 0, t4 = 0, a2 = false;
              this.loadingChecker = setInterval(function() {
                n4.enableloadingChecker && (t4 = n4.player.video.currentTime, a2 || t4 !== e4 || n4.player.video.paused || (n4.player.container.classList.add("dplayer-loading"), a2 = true), a2 && t4 > e4 && !n4.player.video.paused && (n4.player.container.classList.remove("dplayer-loading"), a2 = false), e4 = t4);
              }, 100);
            }
          }, {
            key: "initfpsChecker",
            value: function() {
              var n4 = this;
              window.requestAnimationFrame(function() {
                if (n4.enablefpsChecker) {
                  if (n4.initfpsChecker(), n4.fpsStart) {
                    n4.fpsIndex++;
                    var e4 = /* @__PURE__ */ new Date();
                    e4 - n4.fpsStart > 1e3 && (n4.player.infoPanel.fps(n4.fpsIndex / (e4 - n4.fpsStart) * 1e3), n4.fpsStart = /* @__PURE__ */ new Date(), n4.fpsIndex = 0);
                  } else n4.fpsStart = /* @__PURE__ */ new Date(), n4.fpsIndex = 0;
                } else n4.fpsStart = 0, n4.fpsIndex = 0;
              });
            }
          }, {
            key: "initinfoChecker",
            value: function() {
              var n4 = this;
              this.infoChecker = setInterval(function() {
                n4.enableinfoChecker && n4.player.infoPanel.update();
              }, 1e3);
            }
          }, {
            key: "enable",
            value: function(n4) {
              this["enable".concat(n4, "Checker")] = true, "fps" === n4 && this.initfpsChecker();
            }
          }, {
            key: "disable",
            value: function(n4) {
              this["enable".concat(n4, "Checker")] = false;
            }
          }, {
            key: "destroy",
            value: function() {
              var n4 = this;
              this.types.map(function(e4) {
                return n4["enable".concat(e4, "Checker")] = false, n4["".concat(e4, "Checker")] && clearInterval(n4["".concat(e4, "Checker")]), e4;
              });
            }
          }]) && na(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const ta = ea;
        function aa(n3) {
          return aa = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, aa(n3);
        }
        function oa(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== aa(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== aa(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === aa(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        const ra = function() {
          function n3(e4) {
            var t4 = this;
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.container = e4, this.container.addEventListener("animationend", function() {
              t4.container.classList.remove("dplayer-bezel-transition");
            });
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "switch",
            value: function(n4) {
              this.container.innerHTML = n4, this.container.classList.add("dplayer-bezel-transition");
            }
          }]) && oa(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        function ia(n3) {
          return ia = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, ia(n3);
        }
        function la(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== ia(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== ia(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === ia(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var sa = function() {
          function n3(e4) {
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.container = e4.container, this.barWidth = e4.barWidth, this.container.style.backgroundImage = "url('".concat(e4.url, "')"), this.events = e4.events;
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "resize",
            value: function(n4, e4, t4) {
              this.container.style.width = "".concat(n4, "px"), this.container.style.height = "".concat(e4, "px"), this.container.style.top = "".concat(2 - e4, "px"), this.barWidth = t4;
            }
          }, {
            key: "show",
            value: function() {
              this.container.style.display = "block", this.events && this.events.trigger("thumbnails_show");
            }
          }, {
            key: "move",
            value: function(n4) {
              this.container.style.backgroundPosition = "-".concat(160 * (Math.ceil(n4 / this.barWidth * 100) - 1), "px 0"), this.container.style.left = "".concat(Math.min(Math.max(n4 - this.container.offsetWidth / 2, -10), this.barWidth - 150), "px");
            }
          }, {
            key: "hide",
            value: function() {
              this.container.style.display = "none", this.events && this.events.trigger("thumbnails_hide");
            }
          }]) && la(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const pa = sa;
        function da(n3) {
          return da = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, da(n3);
        }
        function ca(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== da(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== da(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === da(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Aa, ua = true, ya = false, ma = function() {
          function n3(e4) {
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.player = e4, this.autoHideTimer = 0, T.isMobile || (this.setAutoHideHandler = this.setAutoHide.bind(this), this.player.container.addEventListener("mousemove", this.setAutoHideHandler), this.player.container.addEventListener("click", this.setAutoHideHandler), this.player.on("play", this.setAutoHideHandler), this.player.on("pause", this.setAutoHideHandler)), this.initPlayButton(), this.initThumbnails(), this.initPlayedBar(), this.initFullButton(), this.initQualityButton(), this.initScreenshotButton(), this.player.options.subtitle && "string" == typeof this.player.options.subtitle.url && this.initSubtitleButton(), this.initHighlights(), this.initAirplayButton(), this.initChromecastButton(), T.isMobile || this.initVolumeButton();
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "initPlayButton",
            value: function() {
              var n4 = this;
              this.player.template.playButton.addEventListener("click", function() {
                n4.player.toggle();
              }), this.player.template.mobilePlayButton.addEventListener("click", function() {
                n4.player.toggle();
              }), T.isMobile ? (this.player.template.videoWrap.addEventListener("click", function() {
                n4.toggle();
              }), this.player.template.controllerMask.addEventListener("click", function() {
                n4.toggle();
              })) : this.player.options.preventClickToggle || (this.player.template.videoWrap.addEventListener("click", function() {
                n4.player.toggle();
              }), this.player.template.controllerMask.addEventListener("click", function() {
                n4.player.toggle();
              }));
            }
          }, {
            key: "initHighlights",
            value: function() {
              var n4 = this;
              this.player.on("durationchange", function() {
                if (1 !== n4.player.video.duration && n4.player.video.duration !== 1 / 0 && n4.player.options.highlight) {
                  var e4 = n4.player.template.playedBarWrap.querySelectorAll(".dplayer-highlight");
                  [].slice.call(e4, 0).forEach(function(e5) {
                    n4.player.template.playedBarWrap.removeChild(e5);
                  });
                  for (var t4 = 0; t4 < n4.player.options.highlight.length; t4++) if (n4.player.options.highlight[t4].text && n4.player.options.highlight[t4].time) {
                    var a2 = document.createElement("div");
                    a2.classList.add("dplayer-highlight"), a2.style.left = n4.player.options.highlight[t4].time / n4.player.video.duration * 100 + "%", a2.innerHTML = '<span class="dplayer-highlight-text">' + n4.player.options.highlight[t4].text + "</span>", n4.player.template.playedBarWrap.insertBefore(a2, n4.player.template.playedBarTime);
                  }
                }
              });
            }
          }, {
            key: "initThumbnails",
            value: function() {
              var n4 = this;
              this.player.options.video.thumbnails && (this.thumbnails = new pa({
                container: this.player.template.barPreview,
                barWidth: this.player.template.barWrap.offsetWidth,
                url: this.player.options.video.thumbnails,
                events: this.player.events
              }), this.player.on("loadedmetadata", function() {
                n4.thumbnails.resize(160, n4.player.video.videoHeight / n4.player.video.videoWidth * 160, n4.player.template.barWrap.offsetWidth);
              }));
            }
          }, {
            key: "initPlayedBar",
            value: function() {
              var n4 = this, e4 = function(e5) {
                var t5 = ((e5.clientX || e5.changedTouches[0].clientX) - T.getBoundingClientRectViewLeft(n4.player.template.playedBarWrap)) / n4.player.template.playedBarWrap.clientWidth;
                t5 = Math.max(t5, 0), t5 = Math.min(t5, 1), n4.player.bar.set("played", t5, "width"), n4.player.template.ptime.innerHTML = T.secondToTime(t5 * n4.player.video.duration);
              }, t4 = function t5(a2) {
                document.removeEventListener(T.nameMap.dragEnd, t5), document.removeEventListener(T.nameMap.dragMove, e4);
                var o2 = ((a2.clientX || a2.changedTouches[0].clientX) - T.getBoundingClientRectViewLeft(n4.player.template.playedBarWrap)) / n4.player.template.playedBarWrap.clientWidth;
                o2 = Math.max(o2, 0), o2 = Math.min(o2, 1), n4.player.bar.set("played", o2, "width"), n4.player.seek(n4.player.bar.get("played") * n4.player.video.duration), n4.player.timer.enable("progress");
              };
              this.player.template.playedBarWrap.addEventListener(T.nameMap.dragStart, function() {
                n4.player.timer.disable("progress"), document.addEventListener(T.nameMap.dragMove, e4), document.addEventListener(T.nameMap.dragEnd, t4);
              }), this.player.template.playedBarWrap.addEventListener(T.nameMap.dragMove, function(e5) {
                if (n4.player.video.duration) {
                  var t5 = n4.player.template.playedBarWrap.getBoundingClientRect().left, a2 = (e5.clientX || e5.changedTouches[0].clientX) - t5;
                  if (a2 < 0 || a2 > n4.player.template.playedBarWrap.offsetWidth) return;
                  var o2 = n4.player.video.duration * (a2 / n4.player.template.playedBarWrap.offsetWidth);
                  T.isMobile && n4.thumbnails && n4.thumbnails.show(), n4.thumbnails && n4.thumbnails.move(a2), n4.player.template.playedBarTime.style.left = "".concat(a2 - (o2 >= 3600 ? 25 : 20), "px"), n4.player.template.playedBarTime.innerText = T.secondToTime(o2), n4.player.template.playedBarTime.classList.remove("hidden");
                }
              }), this.player.template.playedBarWrap.addEventListener(T.nameMap.dragEnd, function() {
                T.isMobile && n4.thumbnails && n4.thumbnails.hide();
              }), T.isMobile || (this.player.template.playedBarWrap.addEventListener("mouseenter", function() {
                n4.player.video.duration && (n4.thumbnails && n4.thumbnails.show(), n4.player.template.playedBarTime.classList.remove("hidden"));
              }), this.player.template.playedBarWrap.addEventListener("mouseleave", function() {
                n4.player.video.duration && (n4.thumbnails && n4.thumbnails.hide(), n4.player.template.playedBarTime.classList.add("hidden"));
              }));
            }
          }, {
            key: "initFullButton",
            value: function() {
              var n4 = this;
              this.player.template.browserFullButton.addEventListener("click", function() {
                n4.player.fullScreen.toggle("browser");
              }), this.player.template.webFullButton.addEventListener("click", function() {
                n4.player.fullScreen.toggle("web");
              });
            }
          }, {
            key: "initVolumeButton",
            value: function() {
              var n4 = this, e4 = function(e5) {
                var t5 = e5 || window.event, a2 = ((t5.clientX || t5.changedTouches[0].clientX) - T.getBoundingClientRectViewLeft(n4.player.template.volumeBarWrap) - 5.5) / 35;
                n4.player.volume(a2);
              }, t4 = function t5() {
                document.removeEventListener(T.nameMap.dragEnd, t5), document.removeEventListener(T.nameMap.dragMove, e4), n4.player.template.volumeButton.classList.remove("dplayer-volume-active");
              };
              this.player.template.volumeBarWrapWrap.addEventListener("click", function(e5) {
                var t5 = e5 || window.event, a2 = ((t5.clientX || t5.changedTouches[0].clientX) - T.getBoundingClientRectViewLeft(n4.player.template.volumeBarWrap) - 5.5) / 35;
                n4.player.volume(a2);
              }), this.player.template.volumeBarWrapWrap.addEventListener(T.nameMap.dragStart, function() {
                document.addEventListener(T.nameMap.dragMove, e4), document.addEventListener(T.nameMap.dragEnd, t4), n4.player.template.volumeButton.classList.add("dplayer-volume-active");
              }), this.player.template.volumeButtonIcon.addEventListener("click", function() {
                n4.player.video.muted ? (n4.player.video.muted = false, n4.player.switchVolumeIcon(), n4.player.bar.set("volume", n4.player.volume(), "width")) : (n4.player.video.muted = true, n4.player.template.volumeIcon.innerHTML = gt.volumeOff, n4.player.bar.set("volume", 0, "width"));
              });
            }
          }, {
            key: "initQualityButton",
            value: function() {
              var n4 = this;
              this.player.options.video.quality && this.player.template.qualityList.addEventListener("click", function(e4) {
                e4.target.classList.contains("dplayer-quality-item") && n4.player.switchQuality(e4.target.dataset.index);
              });
            }
          }, {
            key: "initScreenshotButton",
            value: function() {
              var n4 = this;
              this.player.options.screenshot && this.player.template.camareButton.addEventListener("click", function() {
                var e4, t4 = document.createElement("canvas");
                t4.width = n4.player.video.videoWidth, t4.height = n4.player.video.videoHeight, t4.getContext("2d").drawImage(n4.player.video, 0, 0, t4.width, t4.height), t4.toBlob(function(t5) {
                  e4 = URL.createObjectURL(t5);
                  var a2 = document.createElement("a");
                  a2.href = e4, a2.download = "DPlayer.png", a2.style.display = "none", document.body.appendChild(a2), a2.click(), document.body.removeChild(a2), URL.revokeObjectURL(e4), n4.player.events.trigger("screenshot", e4);
                });
              });
            }
          }, {
            key: "initAirplayButton",
            value: function() {
              this.player.options.airplay && (window.WebKitPlaybackTargetAvailabilityEvent ? this.player.video.addEventListener("webkitplaybacktargetavailabilitychanged", function(n4) {
                "available" === n4.availability ? this.template.airplayButton.disable = false : this.template.airplayButton.disable = true, this.template.airplayButton.addEventListener("click", function() {
                  this.video.webkitShowPlaybackTargetPicker();
                }.bind(this));
              }.bind(this.player)) : this.player.template.airplayButton.style.display = "none");
            }
          }, {
            key: "initChromecast",
            value: function() {
              var n4 = window.document.createElement("script");
              n4.setAttribute("type", "text/javascript"), n4.setAttribute("src", "/cast_sender.js?loadCastFramework=1"), window.document.body.appendChild(n4), window.__onGCastApiAvailable = function(n5) {
                if (n5) {
                  var e4 = new (Aa = window.chrome.cast).SessionRequest(Aa.media.DEFAULT_MEDIA_RECEIVER_APP_ID), t4 = new Aa.ApiConfig(e4, function() {
                  }, function(n6) {
                    n6 === Aa.ReceiverAvailability.AVAILABLE && console.log("chromecast: ", n6);
                  });
                  Aa.initialize(t4, function() {
                  });
                }
              };
            }
          }, {
            key: "initChromecastButton",
            value: function() {
              var n4 = this;
              if (this.player.options.chromecast) {
                ua && (ua = false, this.initChromecast());
                var e4 = function(e5, t5) {
                  n4.currentMedia = t5;
                }, t4 = function(n5) {
                  console.error("Error launching media", n5);
                };
                this.player.template.chromecastButton.addEventListener("click", function() {
                  ya ? (ya = false, n4.currentMedia.stop(), n4.session.stop(), n4.initChromecast()) : (ya = true, Aa.requestSession(function(a2) {
                    var o2, r3, i2;
                    n4.session = a2, o2 = n4.player.options.video.url, r3 = new Aa.media.MediaInfo(o2), i2 = new Aa.media.LoadRequest(r3), n4.session ? n4.session.loadMedia(i2, e4.bind(n4, "loadMedia"), t4).play() : window.open(o2);
                  }, function(e5) {
                    "cancel" === e5.code ? n4.session = void 0 : console.error("Error selecting a cast device", e5);
                  }));
                });
              }
            }
          }, {
            key: "initSubtitleButton",
            value: function() {
              var n4 = this;
              this.player.events.on("subtitle_show", function() {
                n4.player.template.subtitleButton.dataset.balloon = n4.player.tran("hide-subs"), n4.player.template.subtitleButtonInner.style.opacity = "", n4.player.user.set("subtitle", 1);
              }), this.player.events.on("subtitle_hide", function() {
                n4.player.template.subtitleButton.dataset.balloon = n4.player.tran("show-subs"), n4.player.template.subtitleButtonInner.style.opacity = "0.4", n4.player.user.set("subtitle", 0);
              }), this.player.template.subtitleButton.addEventListener("click", function() {
                n4.player.subtitle.toggle();
              });
            }
          }, {
            key: "setAutoHide",
            value: function() {
              var n4 = this;
              this.show(), clearTimeout(this.autoHideTimer), this.autoHideTimer = setTimeout(function() {
                !n4.player.video.played.length || n4.player.paused || n4.disableAutoHide || n4.hide();
              }, 3e3);
            }
          }, {
            key: "show",
            value: function() {
              this.player.container.classList.remove("dplayer-hide-controller");
            }
          }, {
            key: "hide",
            value: function() {
              this.player.container.classList.add("dplayer-hide-controller"), this.player.setting.hide(), this.player.comment && this.player.comment.hide();
            }
          }, {
            key: "isShow",
            value: function() {
              return !this.player.container.classList.contains("dplayer-hide-controller");
            }
          }, {
            key: "toggle",
            value: function() {
              this.isShow() ? this.hide() : this.show();
            }
          }, {
            key: "destroy",
            value: function() {
              T.isMobile || (this.player.container.removeEventListener("mousemove", this.setAutoHideHandler), this.player.container.removeEventListener("click", this.setAutoHideHandler)), clearTimeout(this.autoHideTimer);
            }
          }]) && ca(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const ha = ma;
        function fa(n3) {
          return fa = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, fa(n3);
        }
        function ba(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== fa(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== fa(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === fa(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var ga = function() {
          function n3(e4) {
            var t4 = this;
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.player = e4, this.player.template.mask.addEventListener("click", function() {
              t4.hide();
            }), this.player.template.settingButton.addEventListener("click", function() {
              t4.show();
            }), this.loop = this.player.options.loop, this.player.template.loopToggle.checked = this.loop, this.player.template.loop.addEventListener("click", function() {
              t4.player.template.loopToggle.checked = !t4.player.template.loopToggle.checked, t4.player.template.loopToggle.checked ? t4.loop = true : t4.loop = false, t4.hide();
            }), this.showDanmaku = this.player.user.get("danmaku"), this.showDanmaku || this.player.danmaku && this.player.danmaku.hide(), this.player.template.showDanmakuToggle.checked = this.showDanmaku, this.player.template.showDanmaku.addEventListener("click", function() {
              t4.player.template.showDanmakuToggle.checked = !t4.player.template.showDanmakuToggle.checked, t4.player.template.showDanmakuToggle.checked ? (t4.showDanmaku = true, t4.player.danmaku.show()) : (t4.showDanmaku = false, t4.player.danmaku.hide()), t4.player.user.set("danmaku", t4.showDanmaku ? 1 : 0), t4.hide();
            }), this.unlimitDanmaku = this.player.user.get("unlimited"), this.player.template.unlimitDanmakuToggle.checked = this.unlimitDanmaku, this.player.template.unlimitDanmaku.addEventListener("click", function() {
              t4.player.template.unlimitDanmakuToggle.checked = !t4.player.template.unlimitDanmakuToggle.checked, t4.player.template.unlimitDanmakuToggle.checked ? (t4.unlimitDanmaku = true, t4.player.danmaku.unlimit(true)) : (t4.unlimitDanmaku = false, t4.player.danmaku.unlimit(false)), t4.player.user.set("unlimited", t4.unlimitDanmaku ? 1 : 0), t4.hide();
            }), this.player.template.speed.addEventListener("click", function() {
              t4.player.template.settingBox.classList.add("dplayer-setting-box-narrow"), t4.player.template.settingBox.classList.add("dplayer-setting-box-speed");
            });
            for (var a2 = function(n4) {
              t4.player.template.speedItem[n4].addEventListener("click", function() {
                t4.player.speed(t4.player.template.speedItem[n4].dataset.speed), t4.hide();
              });
            }, o2 = 0; o2 < this.player.template.speedItem.length; o2++) a2(o2);
            if (this.player.danmaku) {
              this.player.on("danmaku_opacity", function(n4) {
                t4.player.bar.set("danmaku", n4, "width"), t4.player.user.set("opacity", n4);
              }), this.player.danmaku.opacity(this.player.user.get("opacity"));
              var r3 = function(n4) {
                var e5 = n4 || window.event, a3 = ((e5.clientX || e5.changedTouches[0].clientX) - T.getBoundingClientRectViewLeft(t4.player.template.danmakuOpacityBarWrap)) / 130;
                a3 = Math.max(a3, 0), a3 = Math.min(a3, 1), t4.player.danmaku.opacity(a3);
              }, i2 = function n4() {
                document.removeEventListener(T.nameMap.dragEnd, n4), document.removeEventListener(T.nameMap.dragMove, r3), t4.player.template.danmakuOpacityBox.classList.remove("dplayer-setting-danmaku-active");
              };
              this.player.template.danmakuOpacityBarWrapWrap.addEventListener("click", function(n4) {
                var e5 = n4 || window.event, a3 = ((e5.clientX || e5.changedTouches[0].clientX) - T.getBoundingClientRectViewLeft(t4.player.template.danmakuOpacityBarWrap)) / 130;
                a3 = Math.max(a3, 0), a3 = Math.min(a3, 1), t4.player.danmaku.opacity(a3);
              }), this.player.template.danmakuOpacityBarWrapWrap.addEventListener(T.nameMap.dragStart, function() {
                document.addEventListener(T.nameMap.dragMove, r3), document.addEventListener(T.nameMap.dragEnd, i2), t4.player.template.danmakuOpacityBox.classList.add("dplayer-setting-danmaku-active");
              });
            }
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "hide",
            value: function() {
              var n4 = this;
              this.player.template.settingBox.classList.remove("dplayer-setting-box-open"), this.player.template.mask.classList.remove("dplayer-mask-show"), setTimeout(function() {
                n4.player.template.settingBox.classList.remove("dplayer-setting-box-narrow"), n4.player.template.settingBox.classList.remove("dplayer-setting-box-speed");
              }, 300), this.player.controller.disableAutoHide = false;
            }
          }, {
            key: "show",
            value: function() {
              this.player.template.settingBox.classList.add("dplayer-setting-box-open"), this.player.template.mask.classList.add("dplayer-mask-show"), this.player.controller.disableAutoHide = true;
            }
          }]) && ba(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const va = ga;
        function xa(n3) {
          return xa = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, xa(n3);
        }
        function Ea(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== xa(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== xa(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === xa(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var wa = function() {
          function n3(e4) {
            var t4 = this;
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.player = e4, this.player.template.mask.addEventListener("click", function() {
              t4.hide();
            }), this.player.template.commentButton.addEventListener("click", function() {
              t4.show();
            }), this.player.template.commentSettingButton.addEventListener("click", function() {
              t4.toggleSetting();
            }), this.player.template.commentColorSettingBox.addEventListener("click", function() {
              if (t4.player.template.commentColorSettingBox.querySelector("input:checked+span")) {
                var n4 = t4.player.template.commentColorSettingBox.querySelector("input:checked").value;
                t4.player.template.commentSettingFill.style.fill = n4, t4.player.template.commentInput.style.color = n4, t4.player.template.commentSendFill.style.fill = n4;
              }
            }), this.player.template.commentInput.addEventListener("click", function() {
              t4.hideSetting();
            }), this.player.template.commentInput.addEventListener("keydown", function(n4) {
              13 === (n4 || window.event).keyCode && t4.send();
            }), this.player.template.commentSendButton.addEventListener("click", function() {
              t4.send();
            });
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "show",
            value: function() {
              this.player.controller.disableAutoHide = true, this.player.template.controller.classList.add("dplayer-controller-comment"), this.player.template.mask.classList.add("dplayer-mask-show"), this.player.container.classList.add("dplayer-show-controller"), this.player.template.commentInput.focus();
            }
          }, {
            key: "hide",
            value: function() {
              this.player.template.controller.classList.remove("dplayer-controller-comment"), this.player.template.mask.classList.remove("dplayer-mask-show"), this.player.container.classList.remove("dplayer-show-controller"), this.player.controller.disableAutoHide = false, this.hideSetting();
            }
          }, {
            key: "showSetting",
            value: function() {
              this.player.template.commentSettingBox.classList.add("dplayer-comment-setting-open");
            }
          }, {
            key: "hideSetting",
            value: function() {
              this.player.template.commentSettingBox.classList.remove("dplayer-comment-setting-open");
            }
          }, {
            key: "toggleSetting",
            value: function() {
              this.player.template.commentSettingBox.classList.contains("dplayer-comment-setting-open") ? this.hideSetting() : this.showSetting();
            }
          }, {
            key: "send",
            value: function() {
              var n4 = this;
              this.player.template.commentInput.blur(), this.player.template.commentInput.value.replace(/^\s+|\s+$/g, "") ? this.player.danmaku.send({
                text: this.player.template.commentInput.value,
                color: T.color2Number(this.player.container.querySelector(".dplayer-comment-setting-color input:checked").value),
                type: parseInt(this.player.container.querySelector(".dplayer-comment-setting-type input:checked").value)
              }, function() {
                n4.player.template.commentInput.value = "", n4.hide();
              }) : this.player.notice(this.player.tran("please-input-danmaku"));
            }
          }]) && Ea(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const Ca = wa;
        function ka(n3) {
          return ka = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, ka(n3);
        }
        function Ba(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== ka(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== ka(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === ka(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Sa = function() {
          function n3(e4) {
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.player = e4, this.doHotKeyHandler = this.doHotKey.bind(this), this.cancelFullScreenHandler = this.cancelFullScreen.bind(this), this.player.options.hotkey && document.addEventListener("keydown", this.doHotKeyHandler), document.addEventListener("keydown", this.cancelFullScreenHandler);
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "doHotKey",
            value: function(n4) {
              if (this.player.focus) {
                var e4 = document.activeElement.tagName.toUpperCase(), t4 = document.activeElement.getAttribute("contenteditable");
                if ("INPUT" !== e4 && "TEXTAREA" !== e4 && "" !== t4 && "true" !== t4) {
                  var a2, o2 = n4 || window.event;
                  switch (o2.keyCode) {
                    case 32:
                      o2.preventDefault(), this.player.toggle();
                      break;
                    case 37:
                      if (o2.preventDefault(), this.player.options.live) break;
                      this.player.seek(this.player.video.currentTime - 5), this.player.controller.setAutoHide();
                      break;
                    case 39:
                      if (o2.preventDefault(), this.player.options.live) break;
                      this.player.seek(this.player.video.currentTime + 5), this.player.controller.setAutoHide();
                      break;
                    case 38:
                      o2.preventDefault(), a2 = this.player.volume() + 0.1, this.player.volume(a2);
                      break;
                    case 40:
                      o2.preventDefault(), a2 = this.player.volume() - 0.1, this.player.volume(a2);
                  }
                }
              }
            }
          }, {
            key: "cancelFullScreen",
            value: function(n4) {
              27 === (n4 || window.event).keyCode && this.player.fullScreen.isFullScreen("web") && this.player.fullScreen.cancel("web");
            }
          }, {
            key: "destroy",
            value: function() {
              this.player.options.hotkey && document.removeEventListener("keydown", this.doHotKeyHandler), document.removeEventListener("keydown", this.cancelFullScreenHandler);
            }
          }]) && Ba(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const Ia = Sa;
        function La(n3) {
          return La = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, La(n3);
        }
        function za(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== La(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== La(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === La(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Ta = function() {
          function n3(e4) {
            var t4 = this;
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.player = e4, this.shown = false, Array.prototype.slice.call(this.player.template.menuItem).forEach(function(n4, e5) {
              t4.player.options.contextmenu[e5].click && n4.addEventListener("click", function() {
                t4.player.options.contextmenu[e5].click(t4.player), t4.hide();
              });
            }), this.contextmenuHandler = function(n4) {
              if (t4.shown) t4.hide();
              else {
                var e5 = n4 || window.event;
                e5.preventDefault();
                var a2 = t4.player.container.getBoundingClientRect();
                t4.show(e5.clientX - a2.left, e5.clientY - a2.top), t4.player.template.mask.addEventListener("click", function() {
                  t4.hide();
                });
              }
            }, this.player.container.addEventListener("contextmenu", this.contextmenuHandler);
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "show",
            value: function(n4, e4) {
              this.player.template.menu.classList.add("dplayer-menu-show");
              var t4 = this.player.container.getBoundingClientRect();
              n4 + this.player.template.menu.offsetWidth >= t4.width ? (this.player.template.menu.style.right = t4.width - n4 + "px", this.player.template.menu.style.left = "initial") : (this.player.template.menu.style.left = n4 + "px", this.player.template.menu.style.right = "initial"), e4 + this.player.template.menu.offsetHeight >= t4.height ? (this.player.template.menu.style.bottom = t4.height - e4 + "px", this.player.template.menu.style.top = "initial") : (this.player.template.menu.style.top = e4 + "px", this.player.template.menu.style.bottom = "initial"), this.player.template.mask.classList.add("dplayer-mask-show"), this.shown = true, this.player.events.trigger("contextmenu_show");
            }
          }, {
            key: "hide",
            value: function() {
              this.player.template.mask.classList.remove("dplayer-mask-show"), this.player.template.menu.classList.remove("dplayer-menu-show"), this.shown = false, this.player.events.trigger("contextmenu_hide");
            }
          }, {
            key: "destroy",
            value: function() {
              this.player.container.removeEventListener("contextmenu", this.contextmenuHandler);
            }
          }]) && za(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const qa = Ta;
        function Oa(n3) {
          return Oa = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Oa(n3);
        }
        function ja(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, (void 0, o2 = function(n4, e4) {
              if ("object" !== Oa(n4) || null === n4) return n4;
              var t4 = n4[Symbol.toPrimitive];
              if (void 0 !== t4) {
                var a3 = t4.call(n4, "string");
                if ("object" !== Oa(a3)) return a3;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(n4);
            }(a2.key), "symbol" === Oa(o2) ? o2 : String(o2)), a2);
          }
          var o2;
        }
        var Da = function() {
          function n3(e4) {
            var t4 = this;
            !function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            }(this, n3), this.container = e4.template.infoPanel, this.template = e4.template, this.video = e4.video, this.player = e4, this.template.infoPanelClose.addEventListener("click", function() {
              t4.hide();
            });
          }
          var e3, t3;
          return e3 = n3, (t3 = [{
            key: "show",
            value: function() {
              this.beginTime = Date.now(), this.update(), this.player.timer.enable("info"), this.player.timer.enable("fps"), this.container.classList.remove("dplayer-info-panel-hide");
            }
          }, {
            key: "hide",
            value: function() {
              this.player.timer.disable("info"), this.player.timer.disable("fps"), this.container.classList.add("dplayer-info-panel-hide");
            }
          }, {
            key: "triggle",
            value: function() {
              this.container.classList.contains("dplayer-info-panel-hide") ? this.show() : this.hide();
            }
          }, {
            key: "update",
            value: function() {
              this.template.infoVersion.innerHTML = "v".concat("1.27.1", " ").concat("v1.27.0-12-g4f61091"), this.template.infoType.innerHTML = this.player.type, this.template.infoUrl.innerHTML = this.player.options.video.url, this.template.infoResolution.innerHTML = "".concat(this.player.video.videoWidth, " x ").concat(this.player.video.videoHeight), this.template.infoDuration.innerHTML = this.player.video.duration, this.player.options.danmaku && (this.template.infoDanmakuId.innerHTML = this.player.options.danmaku.id, this.template.infoDanmakuApi.innerHTML = this.player.options.danmaku.api, this.template.infoDanmakuAmount.innerHTML = this.player.danmaku.dan.length);
            }
          }, {
            key: "fps",
            value: function(n4) {
              this.template.infoFPS.innerHTML = "".concat(n4.toFixed(1));
            }
          }]) && ja(e3.prototype, t3), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const Pa = Da;
        var Ra = t2(568), Ya = t2.n(Ra);
        function Ma(n3) {
          return Ma = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(n4) {
            return typeof n4;
          } : function(n4) {
            return n4 && "function" == typeof Symbol && n4.constructor === Symbol && n4 !== Symbol.prototype ? "symbol" : typeof n4;
          }, Ma(n3);
        }
        function Fa(n3, e3) {
          var t3 = Object.keys(n3);
          if (Object.getOwnPropertySymbols) {
            var a2 = Object.getOwnPropertySymbols(n3);
            e3 && (a2 = a2.filter(function(e4) {
              return Object.getOwnPropertyDescriptor(n3, e4).enumerable;
            })), t3.push.apply(t3, a2);
          }
          return t3;
        }
        function Wa(n3, e3, t3) {
          return (e3 = Na(e3)) in n3 ? Object.defineProperty(n3, e3, {
            value: t3,
            enumerable: true,
            configurable: true,
            writable: true
          }) : n3[e3] = t3, n3;
        }
        function Ua(n3, e3) {
          for (var t3 = 0; t3 < e3.length; t3++) {
            var a2 = e3[t3];
            a2.enumerable = a2.enumerable || false, a2.configurable = true, "value" in a2 && (a2.writable = true), Object.defineProperty(n3, Na(a2.key), a2);
          }
        }
        function Na(n3) {
          var e3 = function(n4, e4) {
            if ("object" !== Ma(n4) || null === n4) return n4;
            var t3 = n4[Symbol.toPrimitive];
            if (void 0 !== t3) {
              var a2 = t3.call(n4, "string");
              if ("object" !== Ma(a2)) return a2;
              throw new TypeError("@@toPrimitive must return a primitive value.");
            }
            return String(n4);
          }(n3);
          return "symbol" === Ma(e3) ? e3 : String(e3);
        }
        var Qa = 0, Ha = [], _a = function() {
          function n3(e4) {
            var t4 = this;
            (function(n4, e5) {
              if (!(n4 instanceof e5)) throw new TypeError("Cannot call a class as a function");
            })(this, n3), this.options = function(n4) {
              var e5 = {
                container: n4.element || document.getElementsByClassName("dplayer")[0],
                live: false,
                autoplay: false,
                theme: "#b7daff",
                loop: false,
                lang: (navigator.language || navigator.browserLanguage).toLowerCase(),
                screenshot: false,
                airplay: true,
                chromecast: false,
                hotkey: true,
                preload: "metadata",
                volume: 0.7,
                playbackSpeed: [0.5, 0.75, 1, 1.25, 1.5, 2],
                apiBackend: qe,
                video: {},
                contextmenu: [],
                mutex: true,
                pluginOptions: {
                  hls: {},
                  flv: {},
                  dash: {},
                  webtorrent: {}
                },
                preventClickToggle: false
              };
              for (var t5 in e5) e5.hasOwnProperty(t5) && !n4.hasOwnProperty(t5) && (n4[t5] = e5[t5]);
              return n4.video && !n4.video.type && (n4.video.type = "auto"), "object" === Oe(n4.danmaku) && n4.danmaku && !n4.danmaku.user && (n4.danmaku.user = "DIYgod"), n4.subtitle && (!n4.subtitle.type && (n4.subtitle.type = "webvtt"), !n4.subtitle.fontSize && (n4.subtitle.fontSize = "20px"), !n4.subtitle.bottom && (n4.subtitle.bottom = "40px"), !n4.subtitle.color && (n4.subtitle.color = "#fff")), n4.video.quality && (n4.video.url = n4.video.quality[n4.video.defaultQuality].url), n4.lang && (n4.lang = n4.lang.toLowerCase()), n4.contextmenu = n4.contextmenu.concat([{
                key: "video-info",
                click: function(n5) {
                  n5.infoPanel.triggle();
                }
              }, {
                key: "about-author",
                link: "https://diygod.me"
              }, {
                text: "DPlayer v".concat("1.27.1"),
                link: "https://github.com/MoePlayer/DPlayer"
              }]), n4;
            }(function(n4) {
              for (var e5 = 1; e5 < arguments.length; e5++) {
                var t5 = null != arguments[e5] ? arguments[e5] : {};
                e5 % 2 ? Fa(Object(t5), true).forEach(function(e6) {
                  Wa(n4, e6, t5[e6]);
                }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(n4, Object.getOwnPropertyDescriptors(t5)) : Fa(Object(t5)).forEach(function(e6) {
                  Object.defineProperty(n4, e6, Object.getOwnPropertyDescriptor(t5, e6));
                });
              }
              return n4;
            }({
              preload: "webtorrent" === e4.video.type ? "none" : "metadata"
            }, e4)), this.options.video.quality && (this.qualityIndex = this.options.video.defaultQuality, this.quality = this.options.video.quality[this.options.video.defaultQuality]), this.tran = new je(this.options.lang).tran, this.events = new qt(), this.user = new Ft(this), this.container = this.options.container, this.noticeList = {}, this.container.classList.add("dplayer"), this.options.danmaku || this.container.classList.add("dplayer-no-danmaku"), this.options.live ? this.container.classList.add("dplayer-live") : this.container.classList.remove("dplayer-live"), T.isMobile && this.container.classList.add("dplayer-mobile"), this.arrow = this.container.offsetWidth <= 500, this.arrow && this.container.classList.add("dplayer-arrow"), this.options.subtitle && Array.isArray(this.options.subtitle.url) && (this.options.subtitle.url.push({
              subtitle: "",
              lang: "off"
            }), this.options.subtitle.defaultSubtitle && ("string" == typeof this.options.subtitle.defaultSubtitle ? this.options.subtitle.index = this.options.subtitle.url.findIndex(function(n4) {
              return n4.lang === t4.options.subtitle.defaultSubtitle || n4.name === t4.options.subtitle.defaultSubtitle;
            }) : "number" == typeof this.options.subtitle.defaultSubtitle && (this.options.subtitle.index = this.options.subtitle.defaultSubtitle)), (-1 === this.options.subtitle.index || !this.options.subtitle.index || this.options.subtitle.index > this.options.subtitle.url.length - 1) && (this.options.subtitle.index = this.options.subtitle.url.findIndex(function(n4) {
              return n4.lang === t4.options.lang;
            })), -1 === this.options.subtitle.index && (this.options.subtitle.index = this.options.subtitle.url.length - 1)), this.template = new kt({
              container: this.container,
              options: this.options,
              index: Qa,
              tran: this.tran
            }), this.video = this.template.video, this.bar = new Gt(this.template), this.bezel = new ra(this.template.bezel), this.fullScreen = new Pt(this), this.controller = new ha(this), this.options.danmaku && (this.danmaku = new Lt({
              player: this,
              container: this.template.danmaku,
              opacity: this.user.get("opacity"),
              callback: function() {
                setTimeout(function() {
                  t4.template.danmakuLoading.style.display = "none", t4.options.autoplay && t4.play();
                }, 0);
              },
              error: function(n4) {
                t4.notice(n4);
              },
              apiBackend: this.options.apiBackend,
              borderColor: this.options.theme,
              height: this.arrow ? 24 : 30,
              time: function() {
                return t4.video.currentTime;
              },
              unlimited: this.user.get("unlimited"),
              api: {
                id: this.options.danmaku.id,
                address: this.options.danmaku.api,
                token: this.options.danmaku.token,
                maximum: this.options.danmaku.maximum,
                addition: this.options.danmaku.addition,
                user: this.options.danmaku.user,
                speedRate: this.options.danmaku.speedRate
              },
              events: this.events,
              tran: function(n4) {
                return t4.tran(n4);
              }
            }), this.comment = new Ca(this)), this.setting = new va(this), this.plugins = {}, this.docClickFun = function() {
              t4.focus = false;
            }, this.containerClickFun = function() {
              t4.focus = true;
            }, document.addEventListener("click", this.docClickFun, true), this.container.addEventListener("click", this.containerClickFun, true), this.paused = true, this.timer = new ta(this), this.hotkey = new Ia(this), this.contextmenu = new qa(this), this.initVideo(this.video, this.quality && this.quality.type || this.options.video.type), this.infoPanel = new Pa(this), !this.danmaku && this.options.autoplay && this.play(), Qa++, Ha.push(this);
          }
          var e3, t3, a2;
          return e3 = n3, t3 = [{
            key: "seek",
            value: function(n4) {
              n4 = Math.max(n4, 0), this.video.duration && (n4 = Math.min(n4, this.video.duration)), this.video.currentTime < n4 ? this.notice("".concat(this.tran("ff").replace("%s", (n4 - this.video.currentTime).toFixed(0)))) : this.video.currentTime > n4 && this.notice("".concat(this.tran("rew").replace("%s", (this.video.currentTime - n4).toFixed(0)))), this.video.currentTime = n4, this.danmaku && this.danmaku.seek(), this.bar.set("played", n4 / this.video.duration, "width"), this.template.ptime.innerHTML = T.secondToTime(n4);
            }
          }, {
            key: "play",
            value: function(n4) {
              var e4 = this;
              if (this.paused = false, this.video.paused && !T.isMobile && this.bezel.switch(gt.play), this.template.playButton.innerHTML = gt.pause, this.template.mobilePlayButton.innerHTML = gt.pause, n4 || L.resolve(this.video.play()).catch(function() {
                e4.pause();
              }).then(function() {
              }), this.timer.enable("loading"), this.container.classList.remove("dplayer-paused"), this.container.classList.add("dplayer-playing"), this.danmaku && this.danmaku.play(), this.options.mutex) for (var t4 = 0; t4 < Ha.length; t4++) this !== Ha[t4] && Ha[t4].pause();
            }
          }, {
            key: "pause",
            value: function(n4) {
              this.paused = true, this.container.classList.remove("dplayer-loading"), this.video.paused || T.isMobile || this.bezel.switch(gt.pause), this.template.playButton.innerHTML = gt.play, this.template.mobilePlayButton.innerHTML = gt.play, n4 || this.video.pause(), this.timer.disable("loading"), this.container.classList.remove("dplayer-playing"), this.container.classList.add("dplayer-paused"), this.danmaku && this.danmaku.pause();
            }
          }, {
            key: "switchVolumeIcon",
            value: function() {
              this.volume() >= 0.95 ? this.template.volumeIcon.innerHTML = gt.volumeUp : this.volume() > 0 ? this.template.volumeIcon.innerHTML = gt.volumeDown : this.template.volumeIcon.innerHTML = gt.volumeOff;
            }
          }, {
            key: "volume",
            value: function(n4, e4, t4) {
              if (n4 = parseFloat(n4), !isNaN(n4)) {
                n4 = Math.max(n4, 0), n4 = Math.min(n4, 1), this.bar.set("volume", n4, "width");
                var a3 = "".concat((100 * n4).toFixed(0), "%");
                this.template.volumeBarWrapWrap.dataset.balloon = a3, e4 || this.user.set("volume", n4), t4 || this.notice("".concat(this.tran("volume"), " ").concat((100 * n4).toFixed(0), "%"), void 0, void 0, "volume"), this.video.volume = n4, this.video.muted && (this.video.muted = false), this.switchVolumeIcon();
              }
              return this.video.volume;
            }
          }, {
            key: "toggle",
            value: function() {
              this.video.paused ? this.play() : this.pause();
            }
          }, {
            key: "on",
            value: function(n4, e4) {
              this.events.on(n4, e4);
            }
          }, {
            key: "switchVideo",
            value: function(n4, e4) {
              this.pause(), this.video.poster = n4.pic ? n4.pic : "", this.video.src = n4.url, this.initMSE(this.video, n4.type || "auto"), e4 && (this.template.danmakuLoading.style.display = "block", this.bar.set("played", 0, "width"), this.bar.set("loaded", 0, "width"), this.template.ptime.innerHTML = "00:00", this.template.danmaku.innerHTML = "", this.danmaku && this.danmaku.reload({
                id: e4.id,
                address: e4.api,
                token: e4.token,
                maximum: e4.maximum,
                addition: e4.addition,
                user: e4.user
              }));
            }
          }, {
            key: "initMSE",
            value: function(n4, e4) {
              var t4 = this;
              if (this.type = e4, this.options.video.customType && this.options.video.customType[e4]) "[object Function]" === Object.prototype.toString.call(this.options.video.customType[e4]) ? this.options.video.customType[e4](this.video, this) : console.error("Illegal customType: ".concat(e4));
              else switch ("auto" === this.type && (/m3u8(#|\?|$)/i.exec(n4.src) ? this.type = "hls" : /.flv(#|\?|$)/i.exec(n4.src) ? this.type = "flv" : /.mpd(#|\?|$)/i.exec(n4.src) ? this.type = "dash" : this.type = "normal"), "hls" === this.type && (n4.canPlayType("application/x-mpegURL") || n4.canPlayType("application/vnd.apple.mpegURL")) && (this.type = "normal"), this.type) {
                case "hls":
                  if (window.Hls) {
                    if (window.Hls.isSupported()) {
                      var a3 = this.options.pluginOptions.hls, o2 = new window.Hls(a3);
                      this.plugins.hls = o2, o2.loadSource(n4.src), o2.attachMedia(n4), this.events.on("destroy", function() {
                        o2.destroy(), delete t4.plugins.hls;
                      });
                    } else this.notice("Error: Hls is not supported.");
                  } else this.notice("Error: Can't find Hls.");
                  break;
                case "flv":
                  if (window.flvjs) {
                    if (window.flvjs.isSupported()) {
                      var r3 = window.flvjs.createPlayer(Object.assign(this.options.pluginOptions.flv.mediaDataSource || {}, {
                        type: "flv",
                        url: n4.src
                      }), this.options.pluginOptions.flv.config);
                      this.plugins.flvjs = r3, r3.attachMediaElement(n4), r3.load(), this.events.on("destroy", function() {
                        r3.unload(), r3.detachMediaElement(), r3.destroy(), delete t4.plugins.flvjs;
                      });
                    } else this.notice("Error: flvjs is not supported.");
                  } else this.notice("Error: Can't find flvjs.");
                  break;
                case "dash":
                  if (window.dashjs) {
                    var i2 = window.dashjs.MediaPlayer().create().initialize(n4, n4.src, false), l2 = this.options.pluginOptions.dash;
                    i2.updateSettings(l2), this.plugins.dash = i2, this.events.on("destroy", function() {
                      window.dashjs.MediaPlayer().reset(), delete t4.plugins.dash;
                    });
                  } else this.notice("Error: Can't find dashjs.");
                  break;
                case "webtorrent":
                  if (window.WebTorrent) {
                    if (window.WebTorrent.WEBRTC_SUPPORT) {
                      this.container.classList.add("dplayer-loading");
                      var s2 = this.options.pluginOptions.webtorrent, p2 = new window.WebTorrent(s2);
                      this.plugins.webtorrent = p2;
                      var d3 = n4.src;
                      n4.src = "", n4.preload = "metadata", n4.addEventListener("durationchange", function() {
                        return t4.container.classList.remove("dplayer-loading");
                      }, {
                        once: true
                      }), p2.add(d3, function(n5) {
                        n5.files.find(function(n6) {
                          return n6.name.endsWith(".mp4");
                        }).renderTo(t4.video, {
                          autoplay: t4.options.autoplay,
                          controls: false
                        });
                      }), this.events.on("destroy", function() {
                        p2.remove(d3), p2.destroy(), delete t4.plugins.webtorrent;
                      });
                    } else this.notice("Error: Webtorrent is not supported.");
                  } else this.notice("Error: Can't find Webtorrent.");
              }
            }
          }, {
            key: "initVideo",
            value: function(n4, e4) {
              var t4 = this;
              this.initMSE(n4, e4), this.on("durationchange", function() {
                1 !== n4.duration && n4.duration !== 1 / 0 && (t4.template.dtime.innerHTML = T.secondToTime(n4.duration));
              }), this.on("progress", function() {
                var e5 = n4.buffered.length ? n4.buffered.end(n4.buffered.length - 1) / n4.duration : 0;
                t4.bar.set("loaded", e5, "width");
              }), this.on("error", function() {
                t4.video.error && t4.tran && t4.notice && "webtorrent" !== t4.type && t4.notice(t4.tran("video-failed"));
              }), this.on("ended", function() {
                t4.bar.set("played", 1, "width"), t4.setting.loop ? (t4.seek(0), t4.play()) : t4.pause(), t4.danmaku && (t4.danmaku.danIndex = 0);
              }), this.on("play", function() {
                t4.paused && t4.play(true);
              }), this.on("pause", function() {
                t4.paused || t4.pause(true);
              }), this.on("timeupdate", function() {
                t4.bar.set("played", t4.video.currentTime / t4.video.duration, "width");
                var n5 = T.secondToTime(t4.video.currentTime);
                t4.template.ptime.innerHTML !== n5 && (t4.template.ptime.innerHTML = n5);
              });
              for (var a3 = function(e5) {
                n4.addEventListener(t4.events.videoEvents[e5], function(n5) {
                  t4.events.trigger(t4.events.videoEvents[e5], n5);
                });
              }, o2 = 0; o2 < this.events.videoEvents.length; o2++) a3(o2);
              this.volume(this.user.get("volume"), true, true), this.options.subtitle && (this.subtitle = new Qt(this.template.subtitle, this.video, this.options.subtitle, this.events), Array.isArray(this.options.subtitle.url) && (this.subtitles = new Zt(this)), this.user.get("subtitle") || this.subtitle.hide());
            }
          }, {
            key: "switchQuality",
            value: function(n4) {
              var e4 = this;
              if (n4 = "string" == typeof n4 ? parseInt(n4) : n4, this.qualityIndex !== n4 && !this.switchingQuality) {
                this.prevIndex = this.qualityIndex, this.qualityIndex = n4, this.switchingQuality = true, this.quality = this.options.video.quality[n4], this.template.qualityButton.innerHTML = this.quality.name;
                var t4 = this.video.paused;
                this.video.pause();
                var a3 = Ya()({
                  current: false,
                  pic: null,
                  screenshot: this.options.screenshot,
                  preload: "auto",
                  url: this.quality.url,
                  subtitle: this.options.subtitle
                }), o2 = new DOMParser().parseFromString(a3, "text/html").body.firstChild;
                this.template.videoWrap.insertBefore(o2, this.template.videoWrap.getElementsByTagName("div")[0]), this.prevVideo = this.video, this.video = o2, this.initVideo(this.video, this.quality.type || this.options.video.type), this.seek(this.prevVideo.currentTime), this.notice("".concat(this.tran("switching-quality").replace("%q", this.quality.name)), -1, void 0, "switch-quality"), this.events.trigger("quality_start", this.quality), this.on("canplay", function() {
                  if (e4.prevVideo) {
                    if (e4.video.currentTime !== e4.prevVideo.currentTime) return void e4.seek(e4.prevVideo.currentTime);
                    e4.template.videoWrap.removeChild(e4.prevVideo), e4.video.classList.add("dplayer-video-current"), t4 || e4.video.play(), e4.prevVideo = null, e4.notice("".concat(e4.tran("switched-quality").replace("%q", e4.quality.name)), void 0, void 0, "switch-quality"), e4.switchingQuality = false, e4.events.trigger("quality_end");
                  }
                }), this.on("error", function() {
                  e4.video.error && e4.prevVideo && (e4.template.videoWrap.removeChild(e4.video), e4.video = e4.prevVideo, t4 || e4.video.play(), e4.qualityIndex = e4.prevIndex, e4.quality = e4.options.video.quality[e4.qualityIndex], e4.noticeTime = setTimeout(function() {
                    e4.template.notice.style.opacity = 0, e4.events.trigger("notice_hide");
                  }, 3e3), e4.prevVideo = null, e4.switchingQuality = false);
                });
              }
            }
          }, {
            key: "notice",
            value: function(n4) {
              var e4, t4, a3, o2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 2e3, r3 = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0.8, i2 = arguments.length > 3 ? arguments[3] : void 0;
              if (i2 && ((e4 = document.getElementById("dplayer-notice-".concat(i2))) && (e4.innerHTML = n4), this.noticeList[i2] && (clearTimeout(this.noticeList[i2]), this.noticeList[i2] = null)), !e4) {
                var l2 = kt.NewNotice(n4, r3, i2);
                this.template.noticeList.appendChild(l2), e4 = l2;
              }
              this.events.trigger("notice_show", e4), o2 > 0 && (this.noticeList[i2] = setTimeout((t4 = e4, a3 = this, function() {
                t4.addEventListener("animationend", function() {
                  a3.template.noticeList.removeChild(t4);
                }), t4.classList.add("remove-notice"), a3.events.trigger("notice_hide"), a3.noticeList[i2] = null;
              }), o2));
            }
          }, {
            key: "resize",
            value: function() {
              this.danmaku && this.danmaku.resize(), this.controller.thumbnails && this.controller.thumbnails.resize(160, this.video.videoHeight / this.video.videoWidth * 160, this.template.barWrap.offsetWidth), this.events.trigger("resize");
            }
          }, {
            key: "speed",
            value: function(n4) {
              this.video.playbackRate = n4;
            }
          }, {
            key: "destroy",
            value: function() {
              Ha.splice(Ha.indexOf(this), 1), this.pause(), document.removeEventListener("click", this.docClickFun, true), this.container.removeEventListener("click", this.containerClickFun, true), this.fullScreen.destroy(), this.hotkey.destroy(), this.contextmenu.destroy(), this.controller.destroy(), this.timer.destroy(), this.video.src = "", this.container.innerHTML = "", this.events.trigger("destroy");
            }
          }], a2 = [{
            key: "version",
            get: function() {
              return "1.27.1";
            }
          }], t3 && Ua(e3.prototype, t3), a2 && Ua(e3, a2), Object.defineProperty(e3, "prototype", {
            writable: false
          }), n3;
        }();
        const Ka = _a;
        console.log("\n".concat(" %c DPlayer v", "1.27.1", " ").concat("v1.27.0-12-g4f61091", " %c https://dplayer.diygod.dev ", "\n", "\n"), "color: #fadfa3; background: #030307; padding:5px 0;", "background: #fadfa3; padding:5px 0;");
        const Za = Ka;
      })(), a.default;
    })());
  }
});

// node_modules/.pnpm/shaka-player@4.15.10/node_modules/shaka-player/dist/shaka-player.ui.js
var require_shaka_player_ui = __commonJS({
  "node_modules/.pnpm/shaka-player@4.15.10/node_modules/shaka-player/dist/shaka-player.ui.js"(exports) {
    (function() {
      var innerGlobal = typeof window != "undefined" ? window : global;
      var exportTo = {};
      (function(window7, global2, module2) {
        var p, ba = typeof Object.create == "function" ? Object.create : function(a) {
          function b() {
          }
          b.prototype = a;
          return new b();
        }, ca = typeof Object.defineProperties == "function" ? Object.defineProperty : function(a, b, c) {
          if (a == Array.prototype || a == Object.prototype) return a;
          a[b] = c.value;
          return a;
        };
        function da(a) {
          a = ["object" == typeof globalThis && globalThis, a, "object" == typeof window7 && window7, "object" == typeof self && self, "object" == typeof global2 && global2];
          for (var b = 0; b < a.length; ++b) {
            var c = a[b];
            if (c && c.Math == Math) return c;
          }
          throw Error("Cannot find global object");
        }
        var ea = da(this);
        function fa(a, b) {
          if (b) a: {
            var c = ea;
            a = a.split(".");
            for (var d2 = 0; d2 < a.length - 1; d2++) {
              var e = a[d2];
              if (!(e in c)) break a;
              c = c[e];
            }
            a = a[a.length - 1];
            d2 = c[a];
            b = b(d2);
            b != d2 && b != null && ca(c, a, {
              configurable: true,
              writable: true,
              value: b
            });
          }
        }
        var ha;
        if (typeof Object.setPrototypeOf == "function") ha = Object.setPrototypeOf;
        else {
          var ia;
          a: {
            var ja = {
              a: true
            }, ka = {};
            try {
              ka.__proto__ = ja;
              ia = ka.a;
              break a;
            } catch (a) {
            }
            ia = false;
          }
          ha = ia ? function(a, b) {
            a.__proto__ = b;
            if (a.__proto__ !== b) throw new TypeError(a + " is not extensible");
            return a;
          } : null;
        }
        var la = ha;
        function ma(a, b) {
          a.prototype = ba(b.prototype);
          a.prototype.constructor = a;
          if (la) la(a, b);
          else for (var c in b) if (c != "prototype") if (Object.defineProperties) {
            var d2 = Object.getOwnPropertyDescriptor(b, c);
            d2 && Object.defineProperty(a, c, d2);
          } else a[c] = b[c];
          a.Un = b.prototype;
        }
        function na(a) {
          var b = 0;
          return function() {
            return b < a.length ? {
              done: false,
              value: a[b++]
            } : {
              done: true
            };
          };
        }
        function t2(a) {
          var b = typeof Symbol != "undefined" && Symbol.iterator && a[Symbol.iterator];
          if (b) return b.call(a);
          if (typeof a.length == "number") return {
            next: na(a)
          };
          throw Error(String(a) + " is not an iterable or ArrayLike");
        }
        function x(a) {
          if (!(a instanceof Array)) {
            a = t2(a);
            for (var b, c = []; !(b = a.next()).done; ) c.push(b.value);
            a = c;
          }
          return a;
        }
        fa("Symbol", function(a) {
          function b(f) {
            if (this instanceof b) throw new TypeError("Symbol is not a constructor");
            return new c(d2 + (f || "") + "_" + e++, f);
          }
          function c(f, g) {
            this.g = f;
            ca(this, "description", {
              configurable: true,
              writable: true,
              value: g
            });
          }
          if (a) return a;
          c.prototype.toString = function() {
            return this.g;
          };
          var d2 = "jscomp_symbol_" + (Math.random() * 1e9 >>> 0) + "_", e = 0;
          return b;
        });
        fa("Symbol.iterator", function(a) {
          if (a) return a;
          a = Symbol("Symbol.iterator");
          for (var b = "Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "), c = 0; c < b.length; c++) {
            var d2 = ea[b[c]];
            typeof d2 === "function" && typeof d2.prototype[a] != "function" && ca(d2.prototype, a, {
              configurable: true,
              writable: true,
              value: function() {
                return oa(na(this));
              }
            });
          }
          return a;
        });
        function oa(a) {
          a = {
            next: a
          };
          a[Symbol.iterator] = function() {
            return this;
          };
          return a;
        }
        function pa() {
          this.u = false;
          this.l = null;
          this.h = void 0;
          this.g = 1;
          this.j = this.m = 0;
          this.C = this.i = null;
        }
        function qa(a) {
          if (a.u) throw new TypeError("Generator is already running");
          a.u = true;
        }
        pa.prototype.A = function(a) {
          this.h = a;
        };
        function ra(a, b) {
          a.i = {
            Ui: b,
            fj: true
          };
          a.g = a.m || a.j;
        }
        pa.prototype.return = function(a) {
          this.i = {
            return: a
          };
          this.g = this.j;
        };
        function G(a, b, c) {
          a.g = c;
          return {
            value: b
          };
        }
        pa.prototype.B = function(a) {
          this.g = a;
        };
        function H(a) {
          a.g = 0;
        }
        function sa(a, b, c) {
          a.m = b;
          c != void 0 && (a.j = c);
        }
        function ta(a, b) {
          a.m = 0;
          a.j = b || 0;
        }
        function ua(a, b, c) {
          a.g = b;
          a.m = c || 0;
        }
        function va(a, b) {
          a.m = b || 0;
          b = a.i.Ui;
          a.i = null;
          return b;
        }
        function wa(a) {
          a.C = [a.i];
          a.m = 0;
          a.j = 0;
        }
        function xa(a, b) {
          var c = a.C.splice(0)[0];
          (c = a.i = a.i || c) ? c.fj ? a.g = a.m || a.j : c.B != void 0 && a.j < c.B ? (a.g = c.B, a.i = null) : a.g = a.j : a.g = b;
        }
        function Aa(a) {
          this.g = new pa();
          this.h = a;
        }
        function Ga(a, b) {
          qa(a.g);
          var c = a.g.l;
          if (c) return Ha(a, "return" in c ? c["return"] : function(d2) {
            return {
              value: d2,
              done: true
            };
          }, b, a.g.return);
          a.g.return(b);
          return Ia(a);
        }
        function Ha(a, b, c, d2) {
          try {
            var e = b.call(a.g.l, c);
            if (!(e instanceof Object)) throw new TypeError("Iterator result " + e + " is not an object");
            if (!e.done) return a.g.u = false, e;
            var f = e.value;
          } catch (g) {
            return a.g.l = null, ra(a.g, g), Ia(a);
          }
          a.g.l = null;
          d2.call(a.g, f);
          return Ia(a);
        }
        function Ia(a) {
          for (; a.g.g; ) try {
            var b = a.h(a.g);
            if (b) return a.g.u = false, {
              value: b.value,
              done: false
            };
          } catch (c) {
            a.g.h = void 0, ra(a.g, c);
          }
          a.g.u = false;
          if (a.g.i) {
            b = a.g.i;
            a.g.i = null;
            if (b.fj) throw b.Ui;
            return {
              value: b.return,
              done: true
            };
          }
          return {
            value: void 0,
            done: true
          };
        }
        function Ka(a) {
          this.next = function(b) {
            qa(a.g);
            a.g.l ? b = Ha(a, a.g.l.next, b, a.g.A) : (a.g.A(b), b = Ia(a));
            return b;
          };
          this.throw = function(b) {
            qa(a.g);
            a.g.l ? b = Ha(a, a.g.l["throw"], b, a.g.A) : (ra(a.g, b), b = Ia(a));
            return b;
          };
          this.return = function(b) {
            return Ga(a, b);
          };
          this[Symbol.iterator] = function() {
            return this;
          };
        }
        function Ma(a) {
          function b(d2) {
            return a.next(d2);
          }
          function c(d2) {
            return a.throw(d2);
          }
          return new Promise(function(d2, e) {
            function f(g) {
              g.done ? d2(g.value) : Promise.resolve(g.value).then(b, c).then(f, e);
            }
            f(a.next());
          });
        }
        function P(a) {
          return Ma(new Ka(new Aa(a)));
        }
        function Na() {
          for (var a = Number(this), b = [], c = a; c < arguments.length; c++) b[c - a] = arguments[c];
          return b;
        }
        fa("Promise", function(a) {
          function b(g) {
            this.h = 0;
            this.i = void 0;
            this.g = [];
            this.u = false;
            var h = this.j();
            try {
              g(h.resolve, h.reject);
            } catch (k2) {
              h.reject(k2);
            }
          }
          function c() {
            this.g = null;
          }
          function d2(g) {
            return g instanceof b ? g : new b(function(h) {
              h(g);
            });
          }
          if (a) return a;
          c.prototype.h = function(g) {
            if (this.g == null) {
              this.g = [];
              var h = this;
              this.i(function() {
                h.l();
              });
            }
            this.g.push(g);
          };
          var e = ea.setTimeout;
          c.prototype.i = function(g) {
            e(g, 0);
          };
          c.prototype.l = function() {
            for (; this.g && this.g.length; ) {
              var g = this.g;
              this.g = [];
              for (var h = 0; h < g.length; ++h) {
                var k2 = g[h];
                g[h] = null;
                try {
                  k2();
                } catch (l) {
                  this.j(l);
                }
              }
            }
            this.g = null;
          };
          c.prototype.j = function(g) {
            this.i(function() {
              throw g;
            });
          };
          b.prototype.j = function() {
            function g(l) {
              return function(m) {
                k2 || (k2 = true, l.call(h, m));
              };
            }
            var h = this, k2 = false;
            return {
              resolve: g(this.G),
              reject: g(this.l)
            };
          };
          b.prototype.G = function(g) {
            if (g === this) this.l(new TypeError("A Promise cannot resolve to itself"));
            else if (g instanceof b) this.I(g);
            else {
              a: switch (typeof g) {
                case "object":
                  var h = g != null;
                  break a;
                case "function":
                  h = true;
                  break a;
                default:
                  h = false;
              }
              h ? this.F(g) : this.m(g);
            }
          };
          b.prototype.F = function(g) {
            var h = void 0;
            try {
              h = g.then;
            } catch (k2) {
              this.l(k2);
              return;
            }
            typeof h == "function" ? this.J(h, g) : this.m(g);
          };
          b.prototype.l = function(g) {
            this.A(2, g);
          };
          b.prototype.m = function(g) {
            this.A(1, g);
          };
          b.prototype.A = function(g, h) {
            if (this.h != 0) throw Error("Cannot settle(" + g + ", " + h + "): Promise already settled in state" + this.h);
            this.h = g;
            this.i = h;
            this.h === 2 && this.H();
            this.C();
          };
          b.prototype.H = function() {
            var g = this;
            e(function() {
              if (g.D()) {
                var h = ea.console;
                typeof h !== "undefined" && h.error(g.i);
              }
            }, 1);
          };
          b.prototype.D = function() {
            if (this.u) return false;
            var g = ea.CustomEvent, h = ea.Event, k2 = ea.dispatchEvent;
            if (typeof k2 === "undefined") return true;
            typeof g === "function" ? g = new g("unhandledrejection", {
              cancelable: true
            }) : typeof h === "function" ? g = new h("unhandledrejection", {
              cancelable: true
            }) : (g = ea.document.createEvent("CustomEvent"), g.initCustomEvent("unhandledrejection", false, true, g));
            g.promise = this;
            g.reason = this.i;
            return k2(g);
          };
          b.prototype.C = function() {
            if (this.g != null) {
              for (var g = 0; g < this.g.length; ++g) f.h(this.g[g]);
              this.g = null;
            }
          };
          var f = new c();
          b.prototype.I = function(g) {
            var h = this.j();
            g.hf(h.resolve, h.reject);
          };
          b.prototype.J = function(g, h) {
            var k2 = this.j();
            try {
              g.call(h, k2.resolve, k2.reject);
            } catch (l) {
              k2.reject(l);
            }
          };
          b.prototype.then = function(g, h) {
            function k2(q, r2) {
              return typeof q == "function" ? function(u) {
                try {
                  l(q(u));
                } catch (w) {
                  m(w);
                }
              } : r2;
            }
            var l, m, n = new b(function(q, r2) {
              l = q;
              m = r2;
            });
            this.hf(k2(g, l), k2(h, m));
            return n;
          };
          b.prototype.catch = function(g) {
            return this.then(void 0, g);
          };
          b.prototype.hf = function(g, h) {
            function k2() {
              switch (l.h) {
                case 1:
                  g(l.i);
                  break;
                case 2:
                  h(l.i);
                  break;
                default:
                  throw Error("Unexpected state: " + l.h);
              }
            }
            var l = this;
            this.g == null ? f.h(k2) : this.g.push(k2);
            this.u = true;
          };
          b.resolve = d2;
          b.reject = function(g) {
            return new b(function(h, k2) {
              k2(g);
            });
          };
          b.race = function(g) {
            return new b(function(h, k2) {
              for (var l = t2(g), m = l.next(); !m.done; m = l.next()) d2(m.value).hf(h, k2);
            });
          };
          b.all = function(g) {
            var h = t2(g), k2 = h.next();
            return k2.done ? d2([]) : new b(function(l, m) {
              function n(u) {
                return function(w) {
                  q[u] = w;
                  r2--;
                  r2 == 0 && l(q);
                };
              }
              var q = [], r2 = 0;
              do
                q.push(void 0), r2++, d2(k2.value).hf(n(q.length - 1), m), k2 = h.next();
              while (!k2.done);
            });
          };
          return b;
        });
        function Pa(a, b) {
          return Object.prototype.hasOwnProperty.call(a, b);
        }
        fa("WeakMap", function(a) {
          function b(k2) {
            this.g = (h += Math.random() + 1).toString();
            if (k2) {
              k2 = t2(k2);
              for (var l; !(l = k2.next()).done; ) l = l.value, this.set(l[0], l[1]);
            }
          }
          function c() {
          }
          function d2(k2) {
            var l = typeof k2;
            return l === "object" && k2 !== null || l === "function";
          }
          function e(k2) {
            if (!Pa(k2, g)) {
              var l = new c();
              ca(k2, g, {
                value: l
              });
            }
          }
          function f(k2) {
            var l = Object[k2];
            l && (Object[k2] = function(m) {
              if (m instanceof c) return m;
              Object.isExtensible(m) && e(m);
              return l(m);
            });
          }
          if (function() {
            if (!a || !Object.seal) return false;
            try {
              var k2 = Object.seal({}), l = Object.seal({}), m = new a([[k2, 2], [l, 3]]);
              if (m.get(k2) != 2 || m.get(l) != 3) return false;
              m.delete(k2);
              m.set(l, 4);
              return !m.has(k2) && m.get(l) == 4;
            } catch (n) {
              return false;
            }
          }()) return a;
          var g = "$jscomp_hidden_" + Math.random();
          f("freeze");
          f("preventExtensions");
          f("seal");
          var h = 0;
          b.prototype.set = function(k2, l) {
            if (!d2(k2)) throw Error("Invalid WeakMap key");
            e(k2);
            if (!Pa(k2, g)) throw Error("WeakMap key fail: " + k2);
            k2[g][this.g] = l;
            return this;
          };
          b.prototype.get = function(k2) {
            return d2(k2) && Pa(k2, g) ? k2[g][this.g] : void 0;
          };
          b.prototype.has = function(k2) {
            return d2(k2) && Pa(k2, g) && Pa(k2[g], this.g);
          };
          b.prototype.delete = function(k2) {
            return d2(k2) && Pa(k2, g) && Pa(k2[g], this.g) ? delete k2[g][this.g] : false;
          };
          return b;
        });
        fa("Map", function(a) {
          function b() {
            var h = {};
            return h.Dc = h.next = h.head = h;
          }
          function c(h, k2) {
            var l = h[1];
            return oa(function() {
              if (l) {
                for (; l.head != h[1]; ) l = l.Dc;
                for (; l.next != l.head; ) return l = l.next, {
                  done: false,
                  value: k2(l)
                };
                l = null;
              }
              return {
                done: true,
                value: void 0
              };
            });
          }
          function d2(h, k2) {
            var l = k2 && typeof k2;
            l == "object" || l == "function" ? f.has(k2) ? l = f.get(k2) : (l = "" + ++g, f.set(k2, l)) : l = "p_" + k2;
            var m = h[0][l];
            if (m && Pa(h[0], l)) for (h = 0; h < m.length; h++) {
              var n = m[h];
              if (k2 !== k2 && n.key !== n.key || k2 === n.key) return {
                id: l,
                list: m,
                index: h,
                entry: n
              };
            }
            return {
              id: l,
              list: m,
              index: -1,
              entry: void 0
            };
          }
          function e(h) {
            this[0] = {};
            this[1] = b();
            this.size = 0;
            if (h) {
              h = t2(h);
              for (var k2; !(k2 = h.next()).done; ) k2 = k2.value, this.set(k2[0], k2[1]);
            }
          }
          if (function() {
            if (!a || typeof a != "function" || !a.prototype.entries || typeof Object.seal != "function") return false;
            try {
              var h = Object.seal({
                x: 4
              }), k2 = new a(t2([[h, "s"]]));
              if (k2.get(h) != "s" || k2.size != 1 || k2.get({
                x: 4
              }) || k2.set({
                x: 4
              }, "t") != k2 || k2.size != 2) return false;
              var l = k2.entries(), m = l.next();
              if (m.done || m.value[0] != h || m.value[1] != "s") return false;
              m = l.next();
              return m.done || m.value[0].x != 4 || m.value[1] != "t" || !l.next().done ? false : true;
            } catch (n) {
              return false;
            }
          }()) return a;
          var f = /* @__PURE__ */ new WeakMap();
          e.prototype.set = function(h, k2) {
            h = h === 0 ? 0 : h;
            var l = d2(this, h);
            l.list || (l.list = this[0][l.id] = []);
            l.entry ? l.entry.value = k2 : (l.entry = {
              next: this[1],
              Dc: this[1].Dc,
              head: this[1],
              key: h,
              value: k2
            }, l.list.push(l.entry), this[1].Dc.next = l.entry, this[1].Dc = l.entry, this.size++);
            return this;
          };
          e.prototype.delete = function(h) {
            h = d2(this, h);
            return h.entry && h.list ? (h.list.splice(h.index, 1), h.list.length || delete this[0][h.id], h.entry.Dc.next = h.entry.next, h.entry.next.Dc = h.entry.Dc, h.entry.head = null, this.size--, true) : false;
          };
          e.prototype.clear = function() {
            this[0] = {};
            this[1] = this[1].Dc = b();
            this.size = 0;
          };
          e.prototype.has = function(h) {
            return !!d2(this, h).entry;
          };
          e.prototype.get = function(h) {
            return (h = d2(this, h).entry) && h.value;
          };
          e.prototype.entries = function() {
            return c(this, function(h) {
              return [h.key, h.value];
            });
          };
          e.prototype.keys = function() {
            return c(this, function(h) {
              return h.key;
            });
          };
          e.prototype.values = function() {
            return c(this, function(h) {
              return h.value;
            });
          };
          e.prototype.forEach = function(h, k2) {
            for (var l = this.entries(), m; !(m = l.next()).done; ) m = m.value, h.call(k2, m[1], m[0], this);
          };
          e.prototype[Symbol.iterator] = e.prototype.entries;
          var g = 0;
          return e;
        });
        function Qa(a, b) {
          a instanceof String && (a += "");
          var c = 0, d2 = false, e = {
            next: function() {
              if (!d2 && c < a.length) {
                var f = c++;
                return {
                  value: b(f, a[f]),
                  done: false
                };
              }
              d2 = true;
              return {
                done: true,
                value: void 0
              };
            }
          };
          e[Symbol.iterator] = function() {
            return e;
          };
          return e;
        }
        fa("Array.prototype.keys", function(a) {
          return a ? a : function() {
            return Qa(this, function(b) {
              return b;
            });
          };
        });
        fa("Set", function(a) {
          function b(c) {
            this.g = /* @__PURE__ */ new Map();
            if (c) {
              c = t2(c);
              for (var d2; !(d2 = c.next()).done; ) this.add(d2.value);
            }
            this.size = this.g.size;
          }
          if (function() {
            if (!a || typeof a != "function" || !a.prototype.entries || typeof Object.seal != "function") return false;
            try {
              var c = Object.seal({
                x: 4
              }), d2 = new a(t2([c]));
              if (!d2.has(c) || d2.size != 1 || d2.add(c) != d2 || d2.size != 1 || d2.add({
                x: 4
              }) != d2 || d2.size != 2) return false;
              var e = d2.entries(), f = e.next();
              if (f.done || f.value[0] != c || f.value[1] != c) return false;
              f = e.next();
              return f.done || f.value[0] == c || f.value[0].x != 4 || f.value[1] != f.value[0] ? false : e.next().done;
            } catch (g) {
              return false;
            }
          }()) return a;
          b.prototype.add = function(c) {
            c = c === 0 ? 0 : c;
            this.g.set(c, c);
            this.size = this.g.size;
            return this;
          };
          b.prototype.delete = function(c) {
            c = this.g.delete(c);
            this.size = this.g.size;
            return c;
          };
          b.prototype.clear = function() {
            this.g.clear();
            this.size = 0;
          };
          b.prototype.has = function(c) {
            return this.g.has(c);
          };
          b.prototype.entries = function() {
            return this.g.entries();
          };
          b.prototype.values = function() {
            return this.g.values();
          };
          b.prototype.keys = b.prototype.values;
          b.prototype[Symbol.iterator] = b.prototype.values;
          b.prototype.forEach = function(c, d2) {
            var e = this;
            this.g.forEach(function(f) {
              return c.call(d2, f, f, e);
            });
          };
          return b;
        });
        fa("Array.prototype.values", function(a) {
          return a ? a : function() {
            return Qa(this, function(b, c) {
              return c;
            });
          };
        });
        fa("Array.from", function(a) {
          return a ? a : function(b, c, d2) {
            c = c != null ? c : function(h) {
              return h;
            };
            var e = [], f = typeof Symbol != "undefined" && Symbol.iterator && b[Symbol.iterator];
            if (typeof f == "function") {
              b = f.call(b);
              for (var g = 0; !(f = b.next()).done; ) e.push(c.call(d2, f.value, g++));
            } else for (f = b.length, g = 0; g < f; g++) e.push(c.call(d2, b[g], g));
            return e;
          };
        });
        fa("Object.is", function(a) {
          return a ? a : function(b, c) {
            return b === c ? b !== 0 || 1 / b === 1 / c : b !== b && c !== c;
          };
        });
        fa("Array.prototype.includes", function(a) {
          return a ? a : function(b, c) {
            var d2 = this;
            d2 instanceof String && (d2 = String(d2));
            var e = d2.length;
            c = c || 0;
            for (c < 0 && (c = Math.max(c + e, 0)); c < e; c++) {
              var f = d2[c];
              if (f === b || Object.is(f, b)) return true;
            }
            return false;
          };
        });
        function Ra(a, b, c) {
          if (a == null) throw new TypeError("The 'this' value for String.prototype." + c + " must not be null or undefined");
          if (b instanceof RegExp) throw new TypeError("First argument to String.prototype." + c + " must not be a regular expression");
          return a + "";
        }
        fa("String.prototype.includes", function(a) {
          return a ? a : function(b, c) {
            return Ra(this, b, "includes").indexOf(b, c || 0) !== -1;
          };
        });
        fa("String.fromCodePoint", function(a) {
          return a ? a : function(b) {
            for (var c = "", d2 = 0; d2 < arguments.length; d2++) {
              var e = Number(arguments[d2]);
              if (e < 0 || e > 1114111 || e !== Math.floor(e)) throw new RangeError("invalid_code_point " + e);
              e <= 65535 ? c += String.fromCharCode(e) : (e -= 65536, c += String.fromCharCode(e >>> 10 & 1023 | 55296), c += String.fromCharCode(e & 1023 | 56320));
            }
            return c;
          };
        });
        function Sa(a, b, c) {
          a instanceof String && (a = String(a));
          for (var d2 = a.length, e = 0; e < d2; e++) {
            var f = a[e];
            if (b.call(c, f, e, a)) return {
              cj: e,
              v: f
            };
          }
          return {
            cj: -1,
            v: void 0
          };
        }
        fa("Array.prototype.findIndex", function(a) {
          return a ? a : function(b, c) {
            return Sa(this, b, c).cj;
          };
        });
        fa("WeakSet", function(a) {
          function b(c) {
            this.g = /* @__PURE__ */ new WeakMap();
            if (c) {
              c = t2(c);
              for (var d2; !(d2 = c.next()).done; ) this.add(d2.value);
            }
          }
          if (function() {
            if (!a || !Object.seal) return false;
            try {
              var c = Object.seal({}), d2 = Object.seal({}), e = new a([c]);
              if (!e.has(c) || e.has(d2)) return false;
              e.delete(c);
              e.add(d2);
              return !e.has(c) && e.has(d2);
            } catch (f) {
              return false;
            }
          }()) return a;
          b.prototype.add = function(c) {
            this.g.set(c, true);
            return this;
          };
          b.prototype.has = function(c) {
            return this.g.has(c);
          };
          b.prototype.delete = function(c) {
            return this.g.delete(c);
          };
          return b;
        });
        fa("Array.prototype.find", function(a) {
          return a ? a : function(b, c) {
            return Sa(this, b, c).v;
          };
        });
        fa("String.prototype.startsWith", function(a) {
          return a ? a : function(b, c) {
            var d2 = Ra(this, b, "startsWith"), e = d2.length, f = b.length;
            c = Math.max(0, Math.min(c | 0, d2.length));
            for (var g = 0; g < f && c < e; ) if (d2[c++] != b[g++]) return false;
            return g >= f;
          };
        });
        fa("Object.entries", function(a) {
          return a ? a : function(b) {
            var c = [], d2;
            for (d2 in b) Pa(b, d2) && c.push([d2, b[d2]]);
            return c;
          };
        });
        var Ta = typeof Object.assign == "function" ? Object.assign : function(a, b) {
          for (var c = 1; c < arguments.length; c++) {
            var d2 = arguments[c];
            if (d2) for (var e in d2) Pa(d2, e) && (a[e] = d2[e]);
          }
          return a;
        };
        fa("Object.assign", function(a) {
          return a || Ta;
        });
        fa("Promise.prototype.finally", function(a) {
          return a ? a : function(b) {
            return this.then(function(c) {
              return Promise.resolve(b()).then(function() {
                return c;
              });
            }, function(c) {
              return Promise.resolve(b()).then(function() {
                throw c;
              });
            });
          };
        });
        fa("Array.prototype.entries", function(a) {
          return a ? a : function() {
            return Qa(this, function(b, c) {
              return [b, c];
            });
          };
        });
        fa("Number.isNaN", function(a) {
          return a ? a : function(b) {
            return typeof b === "number" && isNaN(b);
          };
        });
        fa("String.prototype.repeat", function(a) {
          return a ? a : function(b) {
            var c = Ra(this, null, "repeat");
            if (b < 0 || b > 1342177279) throw new RangeError("Invalid count value");
            b |= 0;
            for (var d2 = ""; b; ) if (b & 1 && (d2 += c), b >>>= 1) c += c;
            return d2;
          };
        });
        fa("Number.EPSILON", function() {
          return 2220446049250313e-31;
        });
        fa("Number.MAX_SAFE_INTEGER", function() {
          return 9007199254740991;
        });
        fa("Number.isFinite", function(a) {
          return a ? a : function(b) {
            return typeof b !== "number" ? false : !isNaN(b) && b !== Infinity && b !== -Infinity;
          };
        });
        fa("Object.values", function(a) {
          return a ? a : function(b) {
            var c = [], d2;
            for (d2 in b) Pa(b, d2) && c.push(b[d2]);
            return c;
          };
        });
        fa("Math.log2", function(a) {
          return a ? a : function(b) {
            return Math.log(b) / Math.LN2;
          };
        });
        fa("String.prototype.endsWith", function(a) {
          return a ? a : function(b, c) {
            var d2 = Ra(this, b, "endsWith");
            c === void 0 && (c = d2.length);
            c = Math.max(0, Math.min(c | 0, d2.length));
            for (var e = b.length; e > 0 && c > 0; ) if (d2[--c] != b[--e]) return false;
            return e <= 0;
          };
        });
        fa("Math.trunc", function(a) {
          return a ? a : function(b) {
            b = Number(b);
            if (isNaN(b) || b === Infinity || b === -Infinity || b === 0) return b;
            var c = Math.floor(Math.abs(b));
            return b < 0 ? -c : c;
          };
        });
        function Ua(a) {
          a = Math.trunc(a) || 0;
          a < 0 && (a += this.length);
          if (!(a < 0 || a >= this.length)) return this[a];
        }
        fa("Array.prototype.at", function(a) {
          return a ? a : Ua;
        });
        function Wa(a) {
          return a ? a : Ua;
        }
        fa("Int8Array.prototype.at", Wa);
        fa("Uint8Array.prototype.at", Wa);
        fa("Uint8ClampedArray.prototype.at", Wa);
        fa("Int16Array.prototype.at", Wa);
        fa("Uint16Array.prototype.at", Wa);
        fa("Int32Array.prototype.at", Wa);
        fa("Uint32Array.prototype.at", Wa);
        fa("Float32Array.prototype.at", Wa);
        fa("Float64Array.prototype.at", Wa);
        fa("String.prototype.at", function(a) {
          return a ? a : Ua;
        });
        var Xa = this || self;
        function S(a, b) {
          a = a.split(".");
          var c = Xa;
          a[0] in c || typeof c.execScript == "undefined" || c.execScript("var " + a[0]);
          for (var d2; a.length && (d2 = a.shift()); ) a.length || b === void 0 ? c[d2] && c[d2] !== Object.prototype[d2] ? c = c[d2] : c = c[d2] = {} : c[d2] = b;
        }
        ;
        function T(a, b) {
          if (b) if (b instanceof Map) for (var c = t2(b.keys()), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, Object.defineProperty(this, d2, {
            value: b.get(d2),
            writable: true,
            enumerable: true
          });
          else for (c in b) Object.defineProperty(this, c, {
            value: b[c],
            writable: true,
            enumerable: true
          });
          this.defaultPrevented = this.cancelable = this.bubbles = false;
          this.timeStamp = window7.performance && window7.performance.now ? window7.performance.now() : Date.now();
          this.type = a;
          this.isTrusted = false;
          this.target = this.currentTarget = null;
          this.g = false;
        }
        function Ya(a) {
          var b = new T(a.type), c;
          for (c in a) Object.defineProperty(b, c, {
            value: a[c],
            writable: true,
            enumerable: true
          });
          return b;
        }
        T.prototype.preventDefault = function() {
          this.cancelable && (this.defaultPrevented = true);
        };
        T.prototype.stopImmediatePropagation = function() {
          this.g = true;
        };
        T.prototype.stopPropagation = function() {
        };
        S("shaka.util.FakeEvent", T);
        var Za = {
          Gm: "abrstatuschanged",
          Hm: "adaptation",
          Im: "audiotrackchanged",
          Jm: "audiotrackschanged",
          Km: "boundarycrossed",
          Lm: "buffering",
          Mm: "canupdatestarttime",
          Nm: "complete",
          Om: "currentitemchanged",
          Pm: "downloadcompleted",
          Qm: "downloadfailed",
          Rm: "downloadheadersreceived",
          Sm: "drmsessionupdate",
          Um: "emsg",
          $m: "itemsinserted",
          an: "itemsremoved",
          un: "prft",
          Error: "error",
          Vm: "expirationupdated",
          Wm: "firstquartile",
          Xm: "gapjumped",
          cn: "keystatuschanged",
          hn: "loaded",
          jn: "loading",
          mn: "manifestparsed",
          nn: "manifestupdated",
          on: "mediaqualitychanged",
          pn: "mediasourcerecovered",
          qn: "metadataadded",
          Metadata: "metadata",
          rn: "midpoint",
          sn: "nospatialvideoinfo",
          tn: "onstatechange",
          vn: "ratechange",
          yn: "segmentappended",
          zn: "sessiondata",
          An: "spatialvideoinfo",
          Bn: "stalldetected",
          Cn: "started",
          Dn: "statechanged",
          En: "streaming",
          Fn: "textchanged",
          Gn: "texttrackvisibility",
          Hn: "thirdquartile",
          In: "timelineregionadded",
          Jn: "timelineregionenter",
          Kn: "timelineregionexit",
          Ln: "trackschanged",
          Nn: "unloading",
          Pn: "variantchanged"
        };
        function $a() {
        }
        function ab() {
        }
        function bb() {
        }
        function cb(a) {
          var b = Na.apply(1, arguments);
          db.has(a) || (db.add(a), bb.apply($a, x(b)));
        }
        function eb() {
        }
        function gb() {
        }
        function jb() {
        }
        var db = /* @__PURE__ */ new Set();
        window7.console && ((/* @__PURE__ */ new Map()).set(1, function() {
          return console.error.apply(console, x(Na.apply(0, arguments)));
        }).set(2, function() {
          return console.warn.apply(console, x(Na.apply(0, arguments)));
        }).set(3, function() {
          return console.info.apply(console, x(Na.apply(0, arguments)));
        }).set(4, function() {
          return console.log.apply(console, x(Na.apply(0, arguments)));
        }).set(5, function() {
          return console.debug.apply(console, x(Na.apply(0, arguments)));
        }).set(6, function() {
          return console.debug.apply(console, x(Na.apply(0, arguments)));
        }), bb = function() {
          return console.warn.apply(console, x(Na.apply(0, arguments)));
        }, ab = function() {
          console.error.apply(console, x(Na.apply(0, arguments)));
        });
        function kb() {
          this.g = /* @__PURE__ */ new Map();
        }
        p = kb.prototype;
        p.push = function(a, b) {
          this.g.has(a) ? this.g.get(a).push(b) : this.g.set(a, [b]);
        };
        p.get = function(a) {
          return this.g.has(a) ? this.g.get(a).slice() : null;
        };
        p.remove = function(a, b) {
          if (this.g.has(a)) {
            var c = this.g.get(a).filter(function(d2) {
              return d2 != b;
            });
            this.g.set(a, c);
            c.length || this.g.delete(a);
          }
        };
        p.forEach = function(a) {
          this.g.forEach(function(b, c) {
            a(c, b);
          });
        };
        p.size = function() {
          return this.g.size;
        };
        p.keys = function() {
          return Array.from(this.g.keys());
        };
        function lb() {
          this.hb = new kb();
          this.Ue = this;
        }
        lb.prototype.addEventListener = function(a, b) {
          this.hb && this.hb.push(a, b);
        };
        lb.prototype.removeEventListener = function(a, b) {
          this.hb && this.hb.remove(a, b);
        };
        lb.prototype.dispatchEvent = function(a) {
          if (!this.hb) return true;
          var b = this.hb.get(a.type) || [], c = this.hb.get("All");
          c && (b = b.concat(c));
          b = t2(b);
          for (c = b.next(); !c.done; c = b.next()) {
            c = c.value;
            a.target = this.Ue;
            a.currentTarget = this.Ue;
            try {
              c.handleEvent ? c.handleEvent(a) : c.call(this, a);
            } catch (d2) {
            }
            if (a.g) break;
          }
          return a.defaultPrevented;
        };
        lb.prototype.release = function() {
          this.hb = null;
        };
        function mb(a, b) {
          var c = [];
          a = t2(a);
          for (var d2 = a.next(); !d2.done; d2 = a.next()) c.push(b(d2.value));
          return c;
        }
        function nb(a, b) {
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) if (!b(c.value)) return false;
          return true;
        }
        function ob(a, b) {
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) if (b(c.value)) return true;
          return false;
        }
        function pb(a, b) {
          var c = [];
          a = t2(a);
          for (var d2 = a.next(); !d2.done; d2 = a.next()) d2 = d2.value, b(d2) && c.push(d2);
          return c;
        }
        ;
        var qb = RegExp("^(?:([^:/?#.]+):)?(?://(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#(.*))?$");
        function rb(a) {
          var b;
          a instanceof rb ? (sb(this, a.lc), this.wd = a.wd, tb(this, a.Ib), ub(this, a.Od), this.xb = a.xb, wb(this, a.g.clone()), this.cd = a.cd) : a && (b = String(a).match(qb)) ? (sb(this, b[1] || "", true), this.wd = yb(b[2] || ""), tb(this, b[3] || "", true), ub(this, b[4]), this.xb = yb(b[5] || "", true), wb(this, b[6] || "", true), this.cd = yb(b[7] || "")) : this.g = new zb(null);
        }
        p = rb.prototype;
        p.lc = "";
        p.wd = "";
        p.Ib = "";
        p.Od = null;
        p.xb = "";
        p.cd = "";
        p.toString = function() {
          var a = [], b = this.lc;
          b && a.push(Ab(b, Bb, true), ":");
          if (b = this.Ib) {
            a.push("//");
            var c = this.wd;
            c && a.push(Ab(c, Bb, true), "@");
            a.push(encodeURIComponent(b).replace(/%25([0-9a-fA-F]{2})/g, "%$1"));
            b = this.Od;
            b != null && a.push(":", String(b));
          }
          if (b = this.xb) this.Ib && b.charAt(0) != "/" && a.push("/"), a.push(Ab(b, b.charAt(0) == "/" ? Cb : Db, true));
          (b = this.g.toString()) && a.push("?", b);
          (b = this.cd) && a.push("#", Ab(b, Eb));
          return a.join("");
        };
        p.resolve = function(a) {
          var b = this.clone();
          b.lc === "data" && (b = new rb());
          var c = !!a.lc;
          c ? sb(b, a.lc) : c = !!a.wd;
          c ? b.wd = a.wd : c = !!a.Ib;
          c ? tb(b, a.Ib) : c = a.Od != null;
          var d2 = a.xb;
          if (c) ub(b, a.Od);
          else if (c = !!a.xb) {
            if (d2.charAt(0) != "/") if (this.Ib && !this.xb) d2 = "/" + d2;
            else {
              var e = b.xb.lastIndexOf("/");
              e != -1 && (d2 = b.xb.substr(0, e + 1) + d2);
            }
            if (d2 == ".." || d2 == ".") d2 = "";
            else if (d2.indexOf("./") != -1 || d2.indexOf("/.") != -1) {
              e = d2.lastIndexOf("/", 0) == 0;
              d2 = d2.split("/");
              for (var f = [], g = 0; g < d2.length; ) {
                var h = d2[g++];
                h == "." ? e && g == d2.length && f.push("") : h == ".." ? ((f.length > 1 || f.length == 1 && f[0] != "") && f.pop(), e && g == d2.length && f.push("")) : (f.push(h), e = true);
              }
              d2 = f.join("/");
            }
          }
          c ? b.xb = d2 : c = a.g.toString() !== "";
          c ? wb(b, a.g.clone()) : c = !!a.cd;
          c && (b.cd = a.cd);
          return b;
        };
        p.clone = function() {
          return new rb(this);
        };
        function sb(a, b, c) {
          a.lc = c ? yb(b, true) : b;
          a.lc && (a.lc = a.lc.replace(/:$/, ""));
        }
        function tb(a, b, c) {
          a.Ib = c ? yb(b, true) : b;
        }
        function ub(a, b) {
          if (b) {
            b = Number(b);
            if (isNaN(b) || b < 0) throw Error("Bad port number " + b);
            a.Od = b;
          } else a.Od = null;
        }
        function wb(a, b, c) {
          b instanceof zb ? a.g = b : (c || (b = Ab(b, Fb)), a.g = new zb(b));
        }
        function yb(a, b) {
          return a ? b ? decodeURI(a) : decodeURIComponent(a) : "";
        }
        function Ab(a, b, c) {
          return a != null ? (a = encodeURI(a).replace(b, Gb), c && (a = a.replace(/%25([0-9a-fA-F]{2})/g, "%$1")), a) : null;
        }
        function Gb(a) {
          a = a.charCodeAt(0);
          return "%" + (a >> 4 & 15).toString(16) + (a & 15).toString(16);
        }
        var Bb = /[#\/\?@]/g, Db = /[#\?:]/g, Cb = /[#\?]/g, Fb = /[#\?@]/g, Eb = /#/g;
        function zb(a) {
          this.g = a || null;
        }
        function Hb(a) {
          if (!a.mb && (a.mb = /* @__PURE__ */ new Map(), a.fe = 0, a.g)) for (var b = a.g.split("&"), c = 0; c < b.length; c++) {
            var d2 = b[c].indexOf("="), e = null;
            if (d2 >= 0) {
              var f = b[c].substring(0, d2);
              e = b[c].substring(d2 + 1);
            } else f = b[c];
            f = decodeURIComponent(f);
            e = e || "";
            a.add(f, decodeURIComponent(e));
          }
        }
        p = zb.prototype;
        p.mb = null;
        p.fe = null;
        function Ib(a) {
          Hb(a);
          return a.fe;
        }
        p.add = function(a, b) {
          Hb(this);
          this.g = null;
          var c = this.mb.has(a) ? this.mb.get(a) : null;
          c || this.mb.set(a, c = []);
          c.push(b);
          this.fe++;
          return this;
        };
        p.set = function(a, b) {
          Hb(this);
          this.g = null;
          this.mb.has(a) ? this.mb.set(a, [b]) : this.add(a, b);
          return this;
        };
        p.get = function(a) {
          Hb(this);
          return this.mb.get(a) || [];
        };
        p.toString = function() {
          if (this.g) return this.g;
          if (!this.mb || !this.mb.size) return "";
          for (var a = [], b = t2(this.mb.keys()), c = b.next(); !c.done; c = b.next()) {
            var d2 = c.value;
            c = encodeURIComponent(d2);
            d2 = this.mb.get(d2);
            for (var e = 0; e < d2.length; e++) {
              var f = c;
              d2[e] !== "" && (f += "=" + encodeURIComponent(d2[e]));
              a.push(f);
            }
          }
          return this.g = a.join("&");
        };
        p.clone = function() {
          var a = new zb();
          a.g = this.g;
          if (this.mb) {
            for (var b = /* @__PURE__ */ new Map(), c = t2(this.mb), d2 = c.next(); !d2.done; d2 = c.next()) {
              var e = t2(d2.value);
              d2 = e.next().value;
              e = e.next().value;
              b.set(d2, e.concat());
            }
            a.mb = b;
            a.fe = this.fe;
          }
          return a;
        };
        function Jb() {
        }
        function Kb(a, b) {
          if (!a && !b) return true;
          if (!a || !b || a.byteLength != b.byteLength) return false;
          if ((ArrayBuffer.isView(a) ? a.buffer : a) == (ArrayBuffer.isView(b) ? b.buffer : b) && (a.byteOffset || 0) == (b.byteOffset || 0)) return true;
          var c = Lb(a);
          b = Lb(b);
          for (var d2 = 0; d2 < a.byteLength; d2++) if (c[d2] != b[d2]) return false;
          return true;
        }
        function Mb(a) {
          return ArrayBuffer.isView(a) ? a.byteOffset == 0 && a.byteLength == a.buffer.byteLength ? a.buffer : new Uint8Array(a).buffer : a;
        }
        function Lb(a, b, c) {
          c = c === void 0 ? Infinity : c;
          return Nb(a, b === void 0 ? 0 : b, c, Uint8Array);
        }
        function Ob(a, b, c) {
          c = c === void 0 ? Infinity : c;
          return Nb(a, b === void 0 ? 0 : b, c, Uint16Array);
        }
        function Pb(a, b, c) {
          c = c === void 0 ? Infinity : c;
          return Nb(a, b === void 0 ? 0 : b, c, DataView);
        }
        function Nb(a, b, c, d2) {
          var e = ArrayBuffer.isView(a) ? a.buffer : a, f = 1;
          "BYTES_PER_ELEMENT" in d2 && (f = d2.BYTES_PER_ELEMENT);
          var g = ((a.byteOffset || 0) + a.byteLength) / f;
          a = Math.floor(Math.max(0, Math.min(((a.byteOffset || 0) + b) / f, g)));
          return new d2(e, a, Math.floor(Math.min(a + Math.max(c, 0), g)) - a);
        }
        S("shaka.util.BufferUtils", Jb);
        Jb.toDataView = Pb;
        Jb.toUint16 = Ob;
        Jb.toUint8 = Lb;
        Jb.toArrayBuffer = Mb;
        Jb.equal = Kb;
        function U(a, b, c) {
          var d2 = Na.apply(3, arguments);
          this.severity = a;
          this.category = b;
          this.code = c;
          this.data = d2;
          this.handled = false;
          this.message = "Shaka Error " + this.code;
          if (Qb) try {
            throw Error(this.message || "Shaka Error");
          } catch (e) {
            this.stack = e.stack;
          }
        }
        U.prototype.toString = function() {
          return "shaka.util.Error " + JSON.stringify(this, null, "  ");
        };
        S("shaka.util.Error", U);
        var Qb = true;
        U.Severity = {
          RECOVERABLE: 1,
          CRITICAL: 2
        };
        U.Category = {
          NETWORK: 1,
          TEXT: 2,
          MEDIA: 3,
          MANIFEST: 4,
          STREAMING: 5,
          DRM: 6,
          PLAYER: 7,
          CAST: 8,
          STORAGE: 9,
          ADS: 10
        };
        U.Code = {
          UNSUPPORTED_SCHEME: 1e3,
          BAD_HTTP_STATUS: 1001,
          HTTP_ERROR: 1002,
          TIMEOUT: 1003,
          MALFORMED_DATA_URI: 1004,
          REQUEST_FILTER_ERROR: 1006,
          RESPONSE_FILTER_ERROR: 1007,
          MALFORMED_TEST_URI: 1008,
          UNEXPECTED_TEST_REQUEST: 1009,
          ATTEMPTS_EXHAUSTED: 1010,
          SEGMENT_MISSING: 1011,
          INVALID_TEXT_HEADER: 2e3,
          INVALID_TEXT_CUE: 2001,
          UNABLE_TO_DETECT_ENCODING: 2003,
          BAD_ENCODING: 2004,
          INVALID_XML: 2005,
          INVALID_MP4_TTML: 2007,
          INVALID_MP4_VTT: 2008,
          UNABLE_TO_EXTRACT_CUE_START_TIME: 2009,
          INVALID_MP4_CEA: 2010,
          TEXT_COULD_NOT_GUESS_MIME_TYPE: 2011,
          CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS: 2012,
          TEXT_ONLY_WEBVTT_SRC_EQUALS: 2013,
          MISSING_TEXT_PLUGIN: 2014,
          UNSUPPORTED_EXTERNAL_THUMBNAILS_URI: 2017,
          BUFFER_READ_OUT_OF_BOUNDS: 3e3,
          JS_INTEGER_OVERFLOW: 3001,
          EBML_OVERFLOW: 3002,
          EBML_BAD_FLOATING_POINT_SIZE: 3003,
          MP4_SIDX_WRONG_BOX_TYPE: 3004,
          MP4_SIDX_INVALID_TIMESCALE: 3005,
          MP4_SIDX_TYPE_NOT_SUPPORTED: 3006,
          WEBM_CUES_ELEMENT_MISSING: 3007,
          WEBM_EBML_HEADER_ELEMENT_MISSING: 3008,
          WEBM_SEGMENT_ELEMENT_MISSING: 3009,
          WEBM_INFO_ELEMENT_MISSING: 3010,
          WEBM_DURATION_ELEMENT_MISSING: 3011,
          WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING: 3012,
          WEBM_CUE_TIME_ELEMENT_MISSING: 3013,
          MEDIA_SOURCE_OPERATION_FAILED: 3014,
          MEDIA_SOURCE_OPERATION_THREW: 3015,
          VIDEO_ERROR: 3016,
          QUOTA_EXCEEDED_ERROR: 3017,
          TRANSMUXING_FAILED: 3018,
          CONTENT_TRANSFORMATION_FAILED: 3019,
          MSS_MISSING_DATA_FOR_TRANSMUXING: 3020,
          MSS_TRANSMUXING_FAILED: 3022,
          TRANSMUXING_NO_VIDEO_DATA: 3023,
          STREAMING_NOT_ALLOWED: 3024,
          UNABLE_TO_GUESS_MANIFEST_TYPE: 4e3,
          DASH_INVALID_XML: 4001,
          DASH_NO_SEGMENT_INFO: 4002,
          DASH_EMPTY_ADAPTATION_SET: 4003,
          DASH_EMPTY_PERIOD: 4004,
          DASH_WEBM_MISSING_INIT: 4005,
          DASH_UNSUPPORTED_CONTAINER: 4006,
          DASH_PSSH_BAD_ENCODING: 4007,
          DASH_NO_COMMON_KEY_SYSTEM: 4008,
          DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED: 4009,
          DASH_CONFLICTING_KEY_IDS: 4010,
          RESTRICTIONS_CANNOT_BE_MET: 4012,
          HLS_PLAYLIST_HEADER_MISSING: 4015,
          INVALID_HLS_TAG: 4016,
          HLS_INVALID_PLAYLIST_HIERARCHY: 4017,
          DASH_DUPLICATE_REPRESENTATION_ID: 4018,
          HLS_MULTIPLE_MEDIA_INIT_SECTIONS_FOUND: 4020,
          HLS_REQUIRED_ATTRIBUTE_MISSING: 4023,
          HLS_REQUIRED_TAG_MISSING: 4024,
          HLS_COULD_NOT_GUESS_CODECS: 4025,
          HLS_KEYFORMATS_NOT_SUPPORTED: 4026,
          DASH_UNSUPPORTED_XLINK_ACTUATE: 4027,
          DASH_XLINK_DEPTH_LIMIT: 4028,
          CONTENT_UNSUPPORTED_BY_BROWSER: 4032,
          CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM: 4033,
          NO_VARIANTS: 4036,
          PERIOD_FLATTENING_FAILED: 4037,
          INCONSISTENT_DRM_ACROSS_PERIODS: 4038,
          HLS_VARIABLE_NOT_FOUND: 4039,
          HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED: 4040,
          HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED: 4041,
          NO_WEB_CRYPTO_API: 4042,
          CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM: 4045,
          MSS_INVALID_XML: 4046,
          MSS_LIVE_CONTENT_NOT_SUPPORTED: 4047,
          AES_128_INVALID_IV_LENGTH: 4048,
          AES_128_INVALID_KEY_LENGTH: 4049,
          DASH_CONFLICTING_AES_128: 4050,
          DASH_UNSUPPORTED_AES_128: 4051,
          DASH_INVALID_PATCH: 4052,
          HLS_EMPTY_MEDIA_PLAYLIST: 4053,
          DASH_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED: 4054,
          CANNOT_ADD_EXTERNAL_CHAPTERS_TO_LIVE_STREAM: 4054,
          STREAMING_ENGINE_STARTUP_INVALID_STATE: 5006,
          NO_RECOGNIZED_KEY_SYSTEMS: 6e3,
          REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE: 6001,
          FAILED_TO_CREATE_CDM: 6002,
          FAILED_TO_ATTACH_TO_VIDEO: 6003,
          INVALID_SERVER_CERTIFICATE: 6004,
          FAILED_TO_CREATE_SESSION: 6005,
          FAILED_TO_GENERATE_LICENSE_REQUEST: 6006,
          LICENSE_REQUEST_FAILED: 6007,
          LICENSE_RESPONSE_REJECTED: 6008,
          ENCRYPTED_CONTENT_WITHOUT_DRM_INFO: 6010,
          NO_LICENSE_SERVER_GIVEN: 6012,
          OFFLINE_SESSION_REMOVED: 6013,
          EXPIRED: 6014,
          SERVER_CERTIFICATE_REQUIRED: 6015,
          INIT_DATA_TRANSFORM_ERROR: 6016,
          SERVER_CERTIFICATE_REQUEST_FAILED: 6017,
          MIN_HDCP_VERSION_NOT_MATCH: 6018,
          ERROR_CHECKING_HDCP_VERSION: 6019,
          MISSING_EME_SUPPORT: 6020,
          LOAD_INTERRUPTED: 7e3,
          OPERATION_ABORTED: 7001,
          NO_VIDEO_ELEMENT: 7002,
          OBJECT_DESTROYED: 7003,
          CONTENT_NOT_LOADED: 7004,
          SRC_EQUALS_PRELOAD_NOT_SUPPORTED: 7005,
          PRELOAD_DESTROYED: 7006,
          QUEUE_INDEX_OUT_OF_BOUNDS: 7007,
          CAST_API_UNAVAILABLE: 8e3,
          NO_CAST_RECEIVERS: 8001,
          ALREADY_CASTING: 8002,
          UNEXPECTED_CAST_ERROR: 8003,
          CAST_CANCELED_BY_USER: 8004,
          CAST_CONNECTION_TIMED_OUT: 8005,
          CAST_RECEIVER_APP_UNAVAILABLE: 8006,
          STORAGE_NOT_SUPPORTED: 9e3,
          INDEXED_DB_ERROR: 9001,
          DEPRECATED_OPERATION_ABORTED: 9002,
          REQUESTED_ITEM_NOT_FOUND: 9003,
          MALFORMED_OFFLINE_URI: 9004,
          CANNOT_STORE_LIVE_OFFLINE: 9005,
          NO_INIT_DATA_FOR_OFFLINE: 9007,
          LOCAL_PLAYER_INSTANCE_REQUIRED: 9008,
          NEW_KEY_OPERATION_NOT_SUPPORTED: 9011,
          KEY_NOT_FOUND: 9012,
          MISSING_STORAGE_CELL: 9013,
          STORAGE_LIMIT_REACHED: 9014,
          DOWNLOAD_SIZE_CALLBACK_ERROR: 9015,
          MODIFY_OPERATION_NOT_SUPPORTED: 9016,
          INDEXED_DB_INIT_TIMED_OUT: 9017,
          CS_IMA_SDK_MISSING: 1e4,
          CS_AD_MANAGER_NOT_INITIALIZED: 10001,
          SS_IMA_SDK_MISSING: 10002,
          SS_AD_MANAGER_NOT_INITIALIZED: 10003,
          CURRENT_DAI_REQUEST_NOT_FINISHED: 10004,
          MT_AD_MANAGER_NOT_INITIALIZED: 10005,
          INTERSTITIAL_AD_MANAGER_NOT_INITIALIZED: 10006,
          VAST_INVALID_XML: 10007
        };
        function Rb(a) {
          this.h = a;
          this.g = void 0;
        }
        Rb.prototype.value = function() {
          this.g === void 0 && (this.g = this.h());
          return this.g;
        };
        function Sb() {
          return Tb.value();
        }
        var Ub = null, Vb = null, Tb = new Rb(function() {
          var a = void 0;
          Ub && (a = Ub());
          !a && Vb && (a = Vb());
          return a;
        });
        function Wb() {
        }
        function Xb(a) {
          if (!a) return "";
          a = Lb(a);
          a[0] == 239 && a[1] == 187 && a[2] == 191 && (a = a.subarray(3));
          if (window7.TextDecoder && !Sb().ki()) return a = new TextDecoder().decode(a), a.includes("\uFFFD") && ab('Decoded string contains an "unknown character" codepoint.  That probably means the UTF8 encoding was incorrect!'), a;
          for (var b = "", c = 0; c < a.length; ++c) {
            var d2 = 65533;
            (a[c] & 128) == 0 ? d2 = a[c] : a.length >= c + 2 && (a[c] & 224) == 192 && (a[c + 1] & 192) == 128 ? (d2 = (a[c] & 31) << 6 | a[c + 1] & 63, c += 1) : a.length >= c + 3 && (a[c] & 240) == 224 && (a[c + 1] & 192) == 128 && (a[c + 2] & 192) == 128 ? (d2 = (a[c] & 15) << 12 | (a[c + 1] & 63) << 6 | a[c + 2] & 63, c += 2) : a.length >= c + 4 && (a[c] & 241) == 240 && (a[c + 1] & 192) == 128 && (a[c + 2] & 192) == 128 && (a[c + 3] & 192) == 128 && (d2 = (a[c] & 7) << 18 | (a[c + 1] & 63) << 12 | (a[c + 2] & 63) << 6 | a[c + 3] & 63, c += 3);
            if (d2 <= 65535) b += String.fromCharCode(d2);
            else {
              d2 -= 65536;
              var e = d2 & 1023;
              b += String.fromCharCode(55296 + (d2 >> 10));
              b += String.fromCharCode(56320 + e);
            }
          }
          return b;
        }
        function Yb(a, b, c) {
          if (!a) return "";
          if (!c && a.byteLength % 2 != 0) throw new U(2, 2, 2004);
          c = Math.floor(a.byteLength / 2);
          var d2 = new Uint16Array(c);
          a = Pb(a);
          for (var e = 0; e < c; e++) d2[e] = a.getUint16(e * 2, b);
          return Zb(d2);
        }
        function $b(a) {
          function b(d2) {
            return c.byteLength <= d2 || c[d2] >= 9 && c[d2] <= 126;
          }
          if (!a) return "";
          var c = Lb(a);
          if (c[0] == 239 && c[1] == 187 && c[2] == 191) return Xb(c);
          if (c[0] == 254 && c[1] == 255) return Yb(c.subarray(2), false);
          if (c[0] == 255 && c[1] == 254) return Yb(c.subarray(2), true);
          if (c[0] == 0 && c[2] == 0) return Yb(a, false);
          if (c[1] == 0 && c[3] == 0) return Yb(a, true);
          if (b(0) && b(1) && b(2) && b(3)) return Xb(a);
          throw new U(2, 2, 2003);
        }
        function ac(a) {
          if (window7.TextEncoder && !Sb().ki()) {
            var b = new TextEncoder();
            return Mb(b.encode(a));
          }
          a = encodeURIComponent(a);
          a = unescape(a);
          b = new Uint8Array(a.length);
          for (var c = 0; c < a.length; c++) b[c] = a[c].charCodeAt(0);
          return Mb(b);
        }
        function bc(a, b) {
          for (var c = new ArrayBuffer(a.length * 2), d2 = new DataView(c), e = 0; e < a.length; ++e) d2.setUint16(e * 2, a.charCodeAt(e), b);
          return c;
        }
        function Zb(a) {
          return cc.value()(a);
        }
        function dc(a) {
          var b = {
            "&amp;": "&",
            "&lt;": "<",
            "&gt;": ">",
            "&quot;": '"',
            "&apos;": "'",
            "&nbsp;": "\xA0",
            "&lrm;": "\u200E",
            "&rlm;": "\u200F"
          }, c = /&(?:amp|lt|gt|quot|apos|nbsp|lrm|rlm|#[xX]?[0-9a-fA-F]+);/g, d2 = RegExp(c.source);
          return a && d2.test(a) ? a.replace(c, function(e) {
            return e[1] == "#" ? (e = e[2] == "x" || e[2] == "X" ? parseInt(e.substring(3), 16) : parseInt(e.substring(2), 10), e >= 0 && e <= 1114111 ? String.fromCodePoint(e) : "") : b[e] || "'";
          }) : a || "";
        }
        S("shaka.util.StringUtils", Wb);
        Wb.resetFromCharCode = function() {
          cc.g = void 0;
        };
        Wb.toUTF16 = bc;
        Wb.toUTF8 = ac;
        Wb.fromBytesAutoDetect = $b;
        Wb.fromUTF16 = Yb;
        Wb.fromUTF8 = Xb;
        var cc = new Rb(function() {
          function a(c) {
            try {
              var d2 = new Uint8Array(c);
              return String.fromCharCode.apply(null, d2).length > 0;
            } catch (e) {
              return false;
            }
          }
          for (var b = {
            Uc: 65536
          }; b.Uc > 0; b = {
            Uc: b.Uc
          }, b.Uc /= 2) if (a(b.Uc)) return /* @__PURE__ */ function(c) {
            return function(d2) {
              for (var e = "", f = 0; f < d2.length; f += c.Uc) e += String.fromCharCode.apply(null, d2.subarray(f, f + c.Uc));
              return e;
            };
          }(b);
          return null;
        });
        function ec() {
        }
        function hc(a) {
          a = Zb(Lb(a));
          return btoa(a);
        }
        function ic(a, b) {
          b = b == void 0 ? true : b;
          a = hc(a).replace(/\+/g, "-").replace(/\//g, "_");
          return b ? a : a.replace(/[=]*$/, "");
        }
        function jc(a) {
          a = window7.atob(a.replace(/-/g, "+").replace(/_/g, "/"));
          for (var b = new Uint8Array(a.length), c = 0; c < a.length; ++c) b[c] = a.charCodeAt(c);
          return b;
        }
        function kc(a) {
          for (var b = a.length / 2, c = new Uint8Array(b), d2 = 0; d2 < b; d2++) c[d2] = window7.parseInt(a.substr(d2 * 2, 2), 16);
          return c;
        }
        function lc(a) {
          var b = Lb(a);
          a = "";
          b = t2(b);
          for (var c = b.next(); !c.done; c = b.next()) c = c.value, c = c.toString(16), c.length == 1 && (c = "0" + c), a += c;
          return a;
        }
        function mc() {
          for (var a = Na.apply(0, arguments), b = 0, c = 0; c < a.length; ++c) b += a[c].byteLength;
          b = new Uint8Array(b);
          for (var d2 = c = 0; d2 < a.length; ++d2) {
            var e = a[d2];
            ArrayBuffer.isView(e) && e.BYTES_PER_ELEMENT === 1 ? b.set(e, c) : b.set(Lb(e), c);
            c += e.byteLength;
          }
          return b;
        }
        S("shaka.util.Uint8ArrayUtils", ec);
        ec.concat = mc;
        ec.toHex = lc;
        ec.fromHex = kc;
        ec.fromBase64 = jc;
        ec.toBase64 = ic;
        ec.toStandardBase64 = hc;
        function nc(a, b, c) {
          c = c === void 0 ? "" : c;
          if (b.length == 0) return a;
          if (a.length == 1 && b.length == 1) {
            var d2 = new rb(a[0]);
            b = new rb(b[0]);
            b = d2.resolve(b);
            c && wb(b, c);
            return [b.toString()];
          }
          b = b.map(function(h) {
            return new rb(h);
          });
          d2 = [];
          a = t2(a);
          for (var e = a.next(); !e.done; e = a.next()) {
            e = new rb(e.value);
            for (var f = t2(b), g = f.next(); !g.done; g = f.next()) g = e.resolve(g.value), c && wb(g, c), d2.push(g.toString());
          }
          return d2;
        }
        function oc(a, b, c, d2) {
          a = {
            keySystem: a,
            encryptionScheme: b,
            licenseServerUri: "",
            distinctiveIdentifierRequired: false,
            persistentStateRequired: false,
            audioRobustness: "",
            videoRobustness: "",
            serverCertificate: null,
            serverCertificateUri: "",
            sessionType: "",
            initData: c || [],
            keyIds: /* @__PURE__ */ new Set()
          };
          d2 && (a.keySystemUris = /* @__PURE__ */ new Set([d2]));
          return a;
        }
        function pc(a, b) {
          b = b === void 0 ? "cenc" : b;
          var c = [], d2 = [], e = [];
          a.forEach(function(g, h) {
            var k2 = h;
            k2.length != 22 && (k2 = ic(kc(h), false));
            var l = g;
            l.length != 22 && (l = ic(kc(g), false));
            g = {
              kty: "oct",
              kid: k2,
              k: l
            };
            c.push(g);
            d2.push(g.kid);
            e.push(h);
          });
          a = JSON.stringify({
            keys: c
          });
          var f = JSON.stringify({
            kids: d2
          });
          f = [{
            initData: Lb(ac(f)),
            initDataType: "keyids"
          }];
          return {
            keySystem: "org.w3.clearkey",
            encryptionScheme: b,
            licenseServerUri: "data:application/json;base64," + window7.btoa(a),
            distinctiveIdentifierRequired: false,
            persistentStateRequired: false,
            audioRobustness: "",
            videoRobustness: "",
            serverCertificate: null,
            serverCertificateUri: "",
            sessionType: "",
            initData: f,
            keyIds: new Set(e)
          };
        }
        function qc(a, b) {
          if (b.length == 1) return b[0];
          a = rc(a, b);
          if (a != null) return a;
          throw new U(2, 4, 4025, b);
        }
        function rc(a, b) {
          var c = sc.get(a);
          c = t2(c);
          for (var d2 = c.next(); !d2.done; d2 = c.next()) {
            d2 = d2.value;
            for (var e = t2(b), f = e.next(); !f.done; f = e.next()) if (f = f.value, d2.test(f.trim())) return f.trim();
          }
          return a == tc ? "" : null;
        }
        function uc(a, b) {
          var c = [];
          a = sc.get(a);
          a = t2(a);
          for (var d2 = a.next(); !d2.done; d2 = a.next()) {
            d2 = d2.value;
            for (var e = t2(b), f = e.next(); !f.done; f = e.next()) f = f.value, d2.test(f.trim()) && c.push(f.trim());
          }
          return c;
        }
        var tc = "text", vc = {
          Ja: "video",
          na: "audio",
          ab: tc,
          yg: "image",
          Em: "application"
        }, wc = 1 / 15, sc = (/* @__PURE__ */ new Map()).set("audio", [/^vorbis$/, /^Opus$/, /^opus$/, /^fLaC$/, /^flac$/, /^mp4a/, /^[ae]c-3$/, /^ac-4/, /^dts[cex]$/, /^iamf/, /^mhm[12]/, /^ac3$/, /^eac3$/, /^apac$/]).set("video", [/^avc/, /^hev/, /^hvc/, /^vvc/, /^vvi/, /^vp0?[89]/, /^av01/, /^dvh/, /^dva/, /^dav/]).set("text", [/^vtt$/, /^wvtt/, /^stpp/]);
        function xc() {
        }
        function yc(a, b) {
          a = zc(a);
          b = zc(b);
          return a.split("-")[0] == b.split("-")[0];
        }
        function Ac(a, b) {
          a = zc(a);
          b = zc(b);
          a = a.split("-");
          b = b.split("-");
          return a[0] == b[0] && a.length == 1 && b.length == 2;
        }
        function Bc(a, b) {
          a = zc(a);
          b = zc(b);
          a = a.split("-");
          b = b.split("-");
          return a.length == 2 && b.length == 2 && a[0] == b[0];
        }
        function zc(a) {
          a = t2(a.split("-x-"));
          var b = a.next().value;
          b = b === void 0 ? "" : b;
          a = a.next().value;
          a = a === void 0 ? "" : a;
          var c = t2(b.split("-"));
          b = c.next().value;
          b = b === void 0 ? "" : b;
          c = c.next().value;
          c = c === void 0 ? "" : c;
          a = a ? "x-" + a : "";
          b = b.toLowerCase();
          b = Cc.get(b) || b;
          c = c.toUpperCase();
          return (c ? b + "-" + c : b) + (a ? "-" + a : "");
        }
        function Dc(a, b) {
          var c = Ec(a), d2 = Ec(b);
          return a != c && b != d2 && c == d2;
        }
        function Fc(a, b) {
          a = zc(a);
          b = zc(b);
          return b == a ? 4 : Ac(b, a) ? 3 : Bc(b, a) ? 2 : Ac(a, b) ? 1 : 0;
        }
        function Ec(a) {
          var b = a.indexOf("-");
          a = b >= 0 ? a.substring(0, b) : a;
          a = a.toLowerCase();
          return a = Cc.get(a) || a;
        }
        function Gc(a) {
          return a.language ? zc(a.language) : a.audio && a.audio.language ? zc(a.audio.language) : a.video && a.video.language ? zc(a.video.language) : "und";
        }
        function Hc(a, b) {
          a = zc(a);
          var c = /* @__PURE__ */ new Set();
          b = t2(b);
          for (var d2 = b.next(); !d2.done; d2 = b.next()) c.add(zc(d2.value));
          b = t2(c);
          for (d2 = b.next(); !d2.done; d2 = b.next()) if (d2 = d2.value, d2 == a) return d2;
          b = t2(c);
          for (d2 = b.next(); !d2.done; d2 = b.next()) if (d2 = d2.value, Ac(d2, a)) return d2;
          b = t2(c);
          for (d2 = b.next(); !d2.done; d2 = b.next()) if (d2 = d2.value, Bc(d2, a)) return d2;
          c = t2(c);
          for (b = c.next(); !b.done; b = c.next()) if (b = b.value, Ac(a, b)) return b;
          return null;
        }
        S("shaka.util.LanguageUtils", xc);
        xc.findClosestLocale = Hc;
        xc.getLocaleForVariant = Gc;
        xc.getLocaleForText = function(a) {
          return zc(a.language || "und");
        };
        xc.getBase = Ec;
        xc.relatedness = Fc;
        xc.areSiblings = Dc;
        xc.normalize = zc;
        xc.isSiblingOf = Bc;
        xc.isParentOf = Ac;
        xc.areLanguageCompatible = yc;
        xc.areLocaleCompatible = function(a, b) {
          a = zc(a);
          b = zc(b);
          return a == b;
        };
        var Cc = /* @__PURE__ */ new Map([["aar", "aa"], ["abk", "ab"], ["afr", "af"], ["aka", "ak"], ["alb", "sq"], ["amh", "am"], ["ara", "ar"], ["arg", "an"], ["arm", "hy"], ["asm", "as"], ["ava", "av"], ["ave", "ae"], ["aym", "ay"], ["aze", "az"], ["bak", "ba"], ["bam", "bm"], ["baq", "eu"], ["bel", "be"], ["ben", "bn"], ["bih", "bh"], ["bis", "bi"], ["bod", "bo"], ["bos", "bs"], ["bre", "br"], ["bul", "bg"], ["bur", "my"], ["cat", "ca"], ["ces", "cs"], ["cha", "ch"], ["che", "ce"], ["chi", "zh"], ["chu", "cu"], ["chv", "cv"], ["cor", "kw"], ["cos", "co"], ["cre", "cr"], ["cym", "cy"], ["cze", "cs"], ["dan", "da"], ["deu", "de"], ["div", "dv"], ["dut", "nl"], ["dzo", "dz"], ["ell", "el"], ["eng", "en"], ["epo", "eo"], ["est", "et"], ["eus", "eu"], ["ewe", "ee"], ["fao", "fo"], ["fas", "fa"], ["fij", "fj"], ["fin", "fi"], ["fra", "fr"], ["fre", "fr"], ["fry", "fy"], ["ful", "ff"], ["geo", "ka"], ["ger", "de"], ["gla", "gd"], ["gle", "ga"], ["glg", "gl"], ["glv", "gv"], ["gre", "el"], ["grn", "gn"], ["guj", "gu"], ["hat", "ht"], ["hau", "ha"], ["heb", "he"], ["her", "hz"], ["hin", "hi"], ["hmo", "ho"], ["hrv", "hr"], ["hun", "hu"], ["hye", "hy"], ["ibo", "ig"], ["ice", "is"], ["ido", "io"], ["iii", "ii"], ["iku", "iu"], ["ile", "ie"], ["ina", "ia"], ["ind", "id"], ["ipk", "ik"], ["isl", "is"], ["ita", "it"], ["jav", "jv"], ["jpn", "ja"], ["kal", "kl"], ["kan", "kn"], ["kas", "ks"], ["kat", "ka"], ["kau", "kr"], ["kaz", "kk"], ["khm", "km"], ["kik", "ki"], ["kin", "rw"], ["kir", "ky"], ["kom", "kv"], ["kon", "kg"], ["kor", "ko"], ["kua", "kj"], ["kur", "ku"], ["lao", "lo"], ["lat", "la"], ["lav", "lv"], ["lim", "li"], ["lin", "ln"], ["lit", "lt"], ["ltz", "lb"], ["lub", "lu"], ["lug", "lg"], ["mac", "mk"], ["mah", "mh"], ["mal", "ml"], ["mao", "mi"], ["mar", "mr"], ["may", "ms"], ["mkd", "mk"], ["mlg", "mg"], ["mlt", "mt"], ["mon", "mn"], ["mri", "mi"], ["msa", "ms"], ["mya", "my"], ["nau", "na"], ["nav", "nv"], ["nbl", "nr"], ["nde", "nd"], ["ndo", "ng"], ["nep", "ne"], ["nld", "nl"], ["nno", "nn"], ["nob", "nb"], ["nor", "no"], ["nya", "ny"], ["oci", "oc"], ["oji", "oj"], ["ori", "or"], ["orm", "om"], ["oss", "os"], ["pan", "pa"], ["per", "fa"], ["pli", "pi"], ["pol", "pl"], ["por", "pt"], ["pus", "ps"], ["que", "qu"], ["roh", "rm"], ["ron", "ro"], ["rum", "ro"], ["run", "rn"], ["rus", "ru"], ["sag", "sg"], ["san", "sa"], ["sin", "si"], ["slk", "sk"], ["slo", "sk"], ["slv", "sl"], ["sme", "se"], ["smo", "sm"], ["sna", "sn"], ["snd", "sd"], ["som", "so"], ["sot", "st"], ["spa", "es"], ["sqi", "sq"], ["srd", "sc"], ["srp", "sr"], ["ssw", "ss"], ["sun", "su"], ["swa", "sw"], ["swe", "sv"], ["tah", "ty"], ["tam", "ta"], ["tat", "tt"], ["tel", "te"], ["tgk", "tg"], ["tgl", "tl"], ["tha", "th"], ["tib", "bo"], ["tir", "ti"], ["ton", "to"], ["tsn", "tn"], ["tso", "ts"], ["tuk", "tk"], ["tur", "tr"], ["twi", "tw"], ["uig", "ug"], ["ukr", "uk"], ["urd", "ur"], ["uzb", "uz"], ["ven", "ve"], ["vie", "vi"], ["vol", "vo"], ["wel", "cy"], ["wln", "wa"], ["wol", "wo"], ["xho", "xh"], ["yid", "yi"], ["yor", "yo"], ["zha", "za"], ["zho", "zh"], ["zul", "zu"]]);
        function Ic(a) {
          lb.call(this);
          this.j = zc(a);
          this.i = /* @__PURE__ */ new Map();
          this.g = /* @__PURE__ */ new Set();
          this.h = /* @__PURE__ */ new Map();
        }
        ma(Ic, lb);
        p = Ic.prototype;
        p.release = function() {
          lb.prototype.release.call(this);
        };
        p.Li = function(a) {
          var b = this;
          this.g.clear();
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) this.g.add(zc(c.value));
          Jc(this);
          a = pb(this.g, function(d2) {
            return !b.h.has(d2);
          });
          a.length && this.dispatchEvent(new T("unknown-locales", (/* @__PURE__ */ new Map()).set("locales", a)));
          a = pb(this.g, function(d2) {
            return b.h.has(d2);
          });
          a = (/* @__PURE__ */ new Map()).set("locales", a.length ? a : [this.j]);
          this.dispatchEvent(new T("locale-changed", a));
        };
        p.Wa = function(a, b, c) {
          a = zc(a);
          c === void 0 && (c = Kc);
          var d2 = this.h.get(a) || /* @__PURE__ */ new Map();
          b.forEach(function(e, f) {
            d2.has(f) && c != Kc || d2.set(f, e);
          });
          this.h.set(a, d2);
          Jc(this);
          this.dispatchEvent(new T("locale-updated"));
          return this;
        };
        p.hm = function(a) {
          for (var b = t2(a.keys()), c = b.next(); !c.done; c = b.next()) c = c.value, a.set(c, this.resolve(c));
        };
        p.resolve = function(a) {
          var b = this.i.get(a);
          if (b) return b;
          a = (/* @__PURE__ */ new Map()).set("locales", Array.from(this.g)).set("missing", a);
          this.dispatchEvent(new T("unknown-localization", a));
          return "";
        };
        p.Kk = function() {
          return this.g;
        };
        function Jc(a) {
          for (var b = a.h, c = a.j, d2 = a.g, e = /* @__PURE__ */ new Set(), f = t2(d2), g = f.next(), h = {}; !g.done; h = {
            ve: void 0
          }, g = f.next()) {
            h.ve = g.value;
            e.add(h.ve);
            e.add(Ec(h.ve));
            g = pb(b.keys(), /* @__PURE__ */ function(l) {
              return function(m) {
                return Dc(m, l.ve);
              };
            }(h));
            g.sort();
            g = t2(g);
            for (var k2 = g.next(); !k2.done; k2 = g.next()) e.add(k2.value);
            h = pb(b.keys(), /* @__PURE__ */ function(l) {
              return function(m) {
                return Ec(m) == l.ve;
              };
            }(h));
            h.sort();
            h = t2(h);
            for (g = h.next(); !g.done; g = h.next()) e.add(g.value);
          }
          e.add(c);
          c = [];
          e = t2(e);
          for (f = e.next(); !f.done; f = e.next()) (f = b.get(f.value)) && c.push(f);
          c.reverse();
          a.i.clear();
          b = t2(c);
          for (e = b.next(); !e.done; e = b.next()) e.value.forEach(function(l, m) {
            a.i.set(m, l);
          });
          b = a.i.keys();
          e = /* @__PURE__ */ new Set();
          c = t2(a.g);
          for (f = c.next(); !f.done; f = c.next()) f = a.h.get(f.value) || /* @__PURE__ */ new Map(), Mc(f, b, e);
          e.size > 0 && (d2 = (/* @__PURE__ */ new Map()).set("locales", Array.from(d2)).set("missing", Array.from(e)), a.dispatchEvent(new T("missing-localizations", d2)));
        }
        function Mc(a, b, c) {
          b = t2(b);
          for (var d2 = b.next(); !d2.done; d2 = b.next()) d2 = d2.value, a.get(d2) || c.add(d2);
        }
        S("shaka.ui.Localization", Ic);
        Ic.prototype.getCurrentLocales = Ic.prototype.Kk;
        Ic.prototype.resolve = Ic.prototype.resolve;
        Ic.prototype.resolveDictionary = Ic.prototype.hm;
        Ic.prototype.insert = Ic.prototype.Wa;
        Ic.prototype.changeLocale = Ic.prototype.Li;
        Ic.prototype.release = Ic.prototype.release;
        var Kc = 1;
        Ic.ConflictResolution = {
          USE_OLD: 0,
          USE_NEW: Kc
        };
        Ic.UNKNOWN_LOCALES = "unknown-locales";
        Ic.UNKNOWN_LOCALIZATION = "unknown-localization";
        Ic.MISSING_LOCALIZATIONS = "missing-localizations";
        Ic.LOCALE_CHANGED = "locale-changed";
        Ic.LOCALE_UPDATED = "locale-updated";
        function Nc(a) {
          this.g = Math.exp(Math.log(0.5) / a);
          this.i = this.h = 0;
        }
        Nc.prototype.sample = function(a, b) {
          var c = Math.pow(this.g, a);
          b = b * (1 - c) + c * this.h;
          isNaN(b) || (this.h = b, this.i += a);
        };
        function Oc(a) {
          return a.h / (1 - Math.pow(a.g, a.i));
        }
        ;
        function Pc() {
          this.h = new Nc(2);
          this.j = new Nc(5);
          this.g = 0;
          this.i = 128e3;
          this.l = 16e3;
        }
        Pc.prototype.configure = function(a) {
          this.i = a.minTotalBytes;
          this.l = a.minBytes;
          this.h.g = Math.exp(Math.log(0.5) / a.fastHalfLife);
          this.j.g = Math.exp(Math.log(0.5) / a.slowHalfLife);
        };
        Pc.prototype.sample = function(a, b) {
          if (!(b < this.l)) {
            var c = 8e3 * b / a;
            a /= 1e3;
            this.g += b;
            this.h.sample(a, c);
            this.j.sample(a, c);
          }
        };
        Pc.prototype.getBandwidthEstimate = function(a) {
          return this.g < this.i ? a : Math.min(Oc(this.h), Oc(this.j));
        };
        function Qc() {
          this.g = new kb();
        }
        p = Qc.prototype;
        p.release = function() {
          this.Ta();
          this.g = null;
        };
        p.o = function(a, b, c, d2) {
          this.g && (a = new Rc(a, b, c, d2), this.g.push(b, a));
        };
        p.qa = function(a, b, c, d2) {
          function e(g) {
            f.Ea(a, b, e);
            c(g);
          }
          var f = this;
          this.o(a, b, e, d2);
        };
        p.Ea = function(a, b, c) {
          if (this.g) {
            var d2 = this.g.get(b) || [];
            d2 = t2(d2);
            for (var e = d2.next(); !e.done; e = d2.next()) e = e.value, e.target != a || c != e.listener && c || (e.Ea(), this.g.remove(b, e));
          }
        };
        p.Ta = function() {
          if (this.g) {
            for (var a = [], b = t2(this.g.g.values()), c = b.next(); !c.done; c = b.next()) a.push.apply(a, x(c.value));
            a = t2(a);
            for (b = a.next(); !b.done; b = a.next()) b.value.Ea();
            this.g.g.clear();
          }
        };
        S("shaka.util.EventManager", Qc);
        Qc.prototype.removeAll = Qc.prototype.Ta;
        Qc.prototype.unlisten = Qc.prototype.Ea;
        Qc.prototype.listenOnce = Qc.prototype.qa;
        Qc.prototype.listen = Qc.prototype.o;
        Qc.prototype.release = Qc.prototype.release;
        function Rc(a, b, c, d2) {
          this.target = a;
          this.type = b;
          this.listener = c;
          this.g = Sc(a, d2);
          this.target.addEventListener(b, c, this.g);
        }
        Rc.prototype.Ea = function() {
          this.target.removeEventListener(this.type, this.listener, this.g);
          this.listener = this.target = null;
          this.g = false;
        };
        function Sc(a, b) {
          if (b == void 0) return false;
          if (typeof b == "boolean") return b;
          var c = /* @__PURE__ */ new Set(["passive", "capture"]);
          Object.keys(b).filter(function(d2) {
            return !c.has(d2);
          });
          return Tc(a) ? b : b.capture || false;
        }
        function Tc(a) {
          var b = Uc;
          if (b == void 0) {
            b = false;
            try {
              var c = {}, d2 = {
                get: function() {
                  b = true;
                  return false;
                }
              };
              Object.defineProperty(c, "passive", d2);
              Object.defineProperty(c, "capture", d2);
              d2 = function() {
              };
              a.addEventListener("test", d2, c);
              a.removeEventListener("test", d2, c);
            } catch (e) {
              b = false;
            }
            Uc = b;
          }
          return b || false;
        }
        var Uc = void 0;
        S("shaka.config.AutoShowText", {
          NEVER: 0,
          ALWAYS: 1,
          IF_PREFERRED_TEXT_LANGUAGE: 2,
          IF_SUBTITLES_MAY_BE_NEEDED: 3
        });
        function Vc(a, b) {
          this.g = a;
          this.h = b;
        }
        Vc.prototype.toString = function() {
          return "v" + this.g + "." + this.h;
        };
        function Wc(a, b) {
          var c = new Vc(5, 0), d2 = Xc, e = d2.g, f = c.h - e.h;
          ((c.g - e.g || f) > 0 ? d2.i : d2.h)(d2.g, c, a, b);
        }
        function Yc(a, b, c, d2) {
          bb([c, "has been deprecated and will be removed in", b, ". We are currently at version", a, ". Additional information:", d2].join(" "));
        }
        function Zc(a, b, c, d2) {
          ab([c, "has been deprecated and has been removed in", b, ". We are now at version", a, ". Additional information:", d2].join(" "));
        }
        var Xc = null;
        function $c(a, b, c, d2) {
          this.g = null;
          this.l = a;
          this.i = b;
          this.m = c;
          this.u = d2;
          this.j = false;
          a: {
            typeof libDPIModule === "undefined" && bb("Could not find LCEVC Library dependencies on this page");
            if (typeof LCEVCdec !== "undefined") this.h = LCEVCdec;
            else if (typeof LcevcDil !== "undefined") this.h = LcevcDil, this.j = true, Wc("LcevcDil", "lcevc_dil.js is deprecated, please use lcevc_dec.js instead");
            else {
              bb("Could not find LCEVC Library on this page");
              a = false;
              break a;
            }
            typeof this.h.SupportObject === "undefined" ? (bb("Could not find LCEVC Library on this page"), a = false) : (this.h.SupportObject.SupportStatus || bb(this.h.SupportObject.SupportError), a = typeof this.h !== "undefined" && typeof libDPIModule !== "undefined" && this.i instanceof HTMLCanvasElement && this.h.SupportObject.SupportStatus);
          }
          a && !this.g && this.h.SupportObject.webGLSupport(this.i) && (this.i.classList.remove("shaka-hidden"), this.g = this.j ? new this.h.LcevcDil(this.l, this.i, this.m) : new this.h.LCEVCdec(this.l, this.i, this.m));
        }
        function ad(a, b, c, d2) {
          d2.type !== "video" || a.u && !d2.baseOriginalId || a.g && a.g.appendBuffer(b, "video", d2.id, -c, !a.u);
        }
        function bd(a) {
          a.g && a.i.classList.add("shaka-hidden");
        }
        $c.prototype.release = function() {
          this.g && (this.g.close(), this.g = null);
        };
        function cd(a) {
          return a && typeof LCEVCdec !== "undefined" ? a.codecs == "lvc1" : false;
        }
        S("shaka.lcevc.Dec", $c);
        $c.prototype.release = $c.prototype.release;
        function dd(a) {
          if (ed.has(a)) return ed.get(a);
          var b = window7.ManagedMediaSource || window7.MediaSource;
          return b ? (b = b.isTypeSupported(a), ed.set(a, b), b) : false;
        }
        function fd() {
          var a = window7.ManagedSourceBuffer || window7.SourceBuffer;
          return !!a && !!a.prototype && !!a.prototype.changeType;
        }
        function hd() {
          var a = window7.ManagedMediaSource || window7.MediaSource;
          return a && a.prototype ? !!a.prototype.setLiveSeekableRange && !!a.prototype.clearLiveSeekableRange : false;
        }
        var ed = /* @__PURE__ */ new Map();
        function id() {
        }
        id.prototype.extract = function() {
        };
        id.prototype.decode = function() {
          return [];
        };
        id.prototype.clear = function() {
        };
        id.prototype.getStreams = function() {
          return [];
        };
        function jd() {
        }
        jd.prototype.init = function() {
        };
        jd.prototype.parse = function() {
          return [];
        };
        function kd() {
        }
        p = kd.prototype;
        p.init = function() {
        };
        p.Tf = function() {
        };
        p.$d = function() {
        };
        p.remove = function() {
        };
        p.zg = function() {
        };
        S("shaka.media.IClosedCaptionParser", kd);
        function ld(a) {
          this.h = /* @__PURE__ */ new Map();
          this.i = 0;
          this.j = new jd();
          if (a = md(a.toLowerCase())) this.j = a();
          this.g = new id();
          if (a = nd) this.g = a(), this.h.set(this.i, this.g);
        }
        p = ld.prototype;
        p.init = function(a, b, c) {
          b = b === void 0 ? false : b;
          c = c === void 0 ? -1 : c;
          if (c != -1 && this.i != c) {
            b = c;
            var d2 = this.h.get(b);
            this.h.set(this.i, this.g);
            if (d2) this.g = d2;
            else {
              if (d2 = nd) this.g = d2();
              this.h.set(b, this.g);
            }
          } else b || this.$d();
          this.j.init(a);
          c != -1 && (this.i = c);
        };
        p.Tf = function(a) {
          a = this.j.parse(a);
          a = t2(a);
          for (var b = a.next(); !b.done; b = a.next()) {
            b = b.value;
            var c = Lb(b.packet);
            c.length > 0 && this.g.extract(c, b.pts);
          }
          return this.g.decode();
        };
        p.$d = function() {
          this.g.clear();
        };
        p.remove = function(a) {
          a = a === void 0 ? [] : a;
          a = new Set(a);
          for (var b = t2(this.h.keys()), c = b.next(); !c.done; c = b.next()) if (c = c.value, !a.has(c)) {
            var d2 = this.h.get(c);
            d2 && d2.clear();
            this.h.delete(c);
          }
        };
        p.zg = function() {
          return this.g.getStreams();
        };
        function od(a, b) {
          pd.set(a, b);
        }
        function md(a) {
          return pd.get(a);
        }
        S("shaka.media.ClosedCaptionParser", ld);
        ld.findDecoder = function() {
          return nd;
        };
        ld.unregisterDecoder = function() {
          nd = null;
        };
        ld.registerDecoder = function(a) {
          nd = a;
        };
        ld.findParser = md;
        ld.unregisterParser = function(a) {
          pd.delete(a);
        };
        ld.registerParser = od;
        var pd = /* @__PURE__ */ new Map(), nd = null;
        function qd() {
          this.id = "";
          this.regionAnchorY = this.regionAnchorX = this.viewportAnchorY = this.viewportAnchorX = 0;
          this.height = this.width = 100;
          this.viewportAnchorUnits = this.widthUnits = this.heightUnits = rd;
          this.scroll = sd;
        }
        S("shaka.text.CueRegion", qd);
        var rd = 1;
        qd.units = {
          PX: 0,
          PERCENTAGE: rd,
          LINES: 2
        };
        var sd = "";
        qd.scrollMode = {
          NONE: sd,
          UP: "up"
        };
        function td(a, b) {
          return typeof a === "number" && typeof b === "number" && isNaN(a) && isNaN(b) ? true : a === b;
        }
        function ud(a, b) {
          b = a.indexOf(b);
          b > -1 && a.splice(b, 1);
        }
        function vd(a, b, c) {
          c || (c = td);
          if (a.length != b.length) return false;
          b = b.slice();
          a = t2(a);
          for (var d2 = a.next(), e = {}; !d2.done; e = {
            gj: void 0
          }, d2 = a.next()) {
            e.gj = d2.value;
            d2 = b.findIndex(/* @__PURE__ */ function(f) {
              return function(g) {
                return c(f.gj, g);
              };
            }(e));
            if (d2 == -1) return false;
            b[d2] = b[b.length - 1];
            b.pop();
          }
          return b.length == 0;
        }
        function wd(a, b, c) {
          if (a === b) return true;
          if (!a || !b) return a == b;
          c || (c = td);
          if (a.length != b.length) return false;
          for (var d2 = 0; d2 < a.length; d2++) if (!c(a[d2], b[d2])) return false;
          return true;
        }
        ;
        function xd(a) {
          this.h = a || "";
          this.g = 0;
        }
        function yd(a) {
          zd(a, /[ \t]+/gm);
        }
        function zd(a, b) {
          b.lastIndex = a.g;
          b = b.exec(a.h);
          b = b == null ? null : {
            position: b.index,
            length: b[0].length,
            results: b
          };
          if (a.g == a.h.length || b == null || b.position != a.g) return null;
          a.g += b.length;
          return b.results;
        }
        function Bd(a) {
          return a.g == a.h.length ? null : (a = zd(a, /[^ \t\n]*/gm)) ? a[0] : null;
        }
        function Dd(a) {
          a = zd(a, Ed);
          if (a == null) return null;
          var b = Number(a[2]), c = Number(a[3]);
          return b > 59 || c > 59 ? null : (Number(a[6]) || 0) / 1e3 + c + b * 60 + (Number(a[1]) || 0) * 3600;
        }
        function Fd(a) {
          return a ? Dd(new xd(a)) : null;
        }
        var Ed = /(?:(\d{1,}):)?(\d{2}):(\d{2})((\.(\d{1,3})))?/g;
        function Gd() {
        }
        function Hd(a) {
          function b(d2) {
            switch (typeof d2) {
              case "undefined":
              case "boolean":
              case "number":
              case "string":
              case "symbol":
              case "function":
                return d2;
              default:
                if (!d2 || ArrayBuffer.isView(d2)) return d2;
                if (c.has(d2)) return null;
                var e = Array.isArray(d2);
                if (d2.constructor != Object && !e) return null;
                c.add(d2);
                var f = e ? [] : {}, g;
                for (g in d2) f[g] = b(d2[g]);
                e && (f.length = d2.length);
                return f;
            }
          }
          var c = /* @__PURE__ */ new WeakSet();
          return b(a);
        }
        function Id(a) {
          var b = {}, c;
          for (c in a) b[c] = a[c];
          return b;
        }
        function Jd(a) {
          if (Array.isArray(a)) {
            for (var b = [], c = 0; c < a.length; c++) {
              var d2 = c.toString(), e = a[c];
              e !== void 0 && (e = Jd(e)) && b.push(d2 + ":" + e);
            }
            a = "[" + b.join(",") + "]";
          } else if (typeof a == "function") a = "";
          else if (a instanceof Object) {
            c = Object.keys(a);
            c.sort();
            b = [];
            c = t2(c);
            for (d2 = c.next(); !d2.done; d2 = c.next()) e = d2.value, d2 = JSON.stringify(e), e = a[e], e !== void 0 && (e = Jd(e)) && b.push(d2 + ":" + e);
            a = "{" + b.join(",") + "}";
          } else a = JSON.stringify(a);
          return a;
        }
        S("shaka.util.ObjectUtils", Gd);
        Gd.alphabeticalKeyOrderStringify = Jd;
        Gd.shallowCloneObject = Id;
        Gd.cloneObject = Hd;
        function Kd(a, b) {
          var c = c === void 0 ? false : c;
          a = $b(a);
          return Ld(a, b, c);
        }
        function Ld(a, b, c) {
          a = Md(a, c === void 0 ? false : c);
          return !b && a.length ? a[0] : (a = a.find(function(d2) {
            return b.split(",").includes(d2.tagName);
          })) ? a : null;
        }
        function Nd(a) {
          return Od.has(a) ? Od.get(a) : "";
        }
        function Md(a, b) {
          function c(f, g) {
            g = g === void 0 ? false : g;
            for (var h = []; a[e]; ) if (a.charCodeAt(e) == 60) {
              if (a.charCodeAt(e + 1) === 47) {
                g = e + 2;
                e = a.indexOf(">", e);
                g = a.substring(g, e);
                var k2 = g.indexOf(f);
                if (k2 == -1) {
                  var l = f.indexOf(".");
                  l > 0 && (k2 = g.indexOf(f.substring(0, l)));
                }
                if (k2 == -1) throw f = a.substring(0, e).split("\n"), Error("Unexpected close tag\nLine: " + (f.length - 1) + "\nColumn: " + (f[f.length - 1].length + 1) + "\nChar: " + a[e]);
                e + 1 && (e += 1);
                break;
              } else if (a.charCodeAt(e + 1) === 33) {
                if (a.charCodeAt(e + 2) == 45) {
                  for (; e !== -1 && (a.charCodeAt(e) !== 62 || a.charCodeAt(e - 1) != 45 || a.charCodeAt(e - 2) != 45 || e == -1); ) e = a.indexOf(">", e + 1);
                  e === -1 && (e = a.length);
                } else if (a.charCodeAt(e + 2) === 91 && a.charCodeAt(e + 8) === 91 && a.substr(e + 3, 5).toLowerCase() === "cdata") {
                  k2 = a.indexOf("]]>", e);
                  k2 == -1 ? (h.push(a.substr(e + 9)), e = a.length) : (h.push(a.substring(e + 9, k2)), e = k2 + 3);
                  continue;
                }
                e++;
                continue;
              }
              a: {
                l = g;
                e++;
                var m = d2(), n = {};
                for (k2 = []; a.charCodeAt(e) !== 62 && a[e]; ) {
                  var q = a.charCodeAt(e);
                  if (q > 64 && q < 91 || q > 96 && q < 123) {
                    q = d2();
                    for (var r2 = a.charCodeAt(e); r2 && r2 !== 39 && r2 !== 34 && !(r2 > 64 && r2 < 91 || r2 > 96 && r2 < 123) && r2 !== 62; ) e++, r2 = a.charCodeAt(e);
                    var u = e + 1;
                    e = a.indexOf(a[e], u);
                    u = a.slice(u, e);
                    if (r2 === 39 || r2 === 34) {
                      if (e === -1) {
                        l = {
                          tagName: m,
                          attributes: n,
                          children: k2,
                          parent: null
                        };
                        if (b) for (m = 0; m < k2.length; m++) typeof k2[m] !== "string" && (k2[m].parent = l);
                        k2 = l;
                        break a;
                      }
                    } else u = null, e--;
                    if (q.startsWith("xmlns:")) {
                      r2 = u;
                      var w = q.split(":")[1];
                      Od.set(r2, w);
                      Pd.set(w, r2);
                    }
                    m === "tt" && q === "xml:space" && u === "preserve" && (l = true);
                    n[q] = u;
                  }
                  e++;
                }
                a.charCodeAt(e - 1) !== 47 ? (e++, k2 = c(m, l)) : e++;
                l = {
                  tagName: m,
                  attributes: n,
                  children: k2,
                  parent: null
                };
                m = k2.length;
                for (n = 0; n < m; n++) q = k2[n], typeof q !== "string" ? b && (q.parent = l) : n == m - 1 && q == "\n" && k2.pop();
                k2 = l;
              }
              h.push(k2);
              if (typeof k2 === "string") break;
              k2.tagName[0] === "?" && k2.children && (h.push.apply(h, x(k2.children)), k2.children = []);
            } else k2 = e, e = a.indexOf("<", e) - 1, e === -2 && (e = a.length), k2 = a.slice(k2, e + 1), g ? k2.length > 0 && h.push(k2) : h.length && k2.length == 1 && k2[0] == "\n" ? h.push(k2) : k2.trim().length > 0 && h.push(k2), e++;
            return h;
          }
          function d2() {
            for (var f = e; "\r\n	>/= ".indexOf(a[e]) === -1 && a[e]; ) e++;
            return a.slice(f, e);
          }
          var e = 0;
          return c("");
        }
        function Qd(a) {
          return typeof a === "string";
        }
        function Rd(a) {
          var b = [];
          if (!a.children) return [];
          a = t2(a.children);
          for (var c = a.next(); !c.done; c = a.next()) c = c.value, typeof c !== "string" && b.push(c);
          return b;
        }
        function Sd(a, b) {
          var c = [];
          if (!a.children) return [];
          a = t2(a.children);
          for (var d2 = a.next(); !d2.done; d2 = a.next()) d2 = d2.value, d2.tagName === b && c.push(d2);
          return c;
        }
        function Td(a) {
          if (typeof a === "string") return dc(a);
          a = a.children.reduce(function(b, c) {
            return typeof c === "string" ? b + c : b;
          }, "");
          return a === "" ? null : dc(a);
        }
        function Ud(a) {
          if (!Array.from(a.children).every(function(b) {
            return typeof b === "string";
          })) return null;
          (a = Td(a)) && (a = a.trim());
          return a;
        }
        function Vd(a, b, c) {
          c = c === void 0 ? [] : c;
          a.tagName === b && c.push(a);
          if (a.children) {
            a = t2(a.children);
            for (var d2 = a.next(); !d2.done; d2 = a.next()) Vd(d2.value, b, c);
          }
          return c;
        }
        function Xd(a, b) {
          a = Sd(a, b);
          return a.length != 1 ? null : a[0];
        }
        function Yd(a, b, c) {
          a = Zd(a, b, c);
          return a.length != 1 ? null : a[0];
        }
        function $d(a, b, c, d2) {
          d2 = d2 === void 0 ? null : d2;
          var e = null;
          a = a.attributes[b];
          a != null && (e = c(a));
          return e == null ? d2 : e;
        }
        function ae(a, b, c) {
          b = Nd(b);
          return a.attributes[b + ":" + c] || null;
        }
        function Zd(a, b, c) {
          var d2 = Nd(b);
          b = [];
          if (a.children) for (c = d2 ? d2 + ":" + c : c, a = t2(a.children), d2 = a.next(); !d2.done; d2 = a.next()) (d2 = d2.value) && d2.tagName === c && b.push(d2);
          return b;
        }
        function be(a, b, c) {
          b = t2(b);
          for (var d2 = b.next(); !d2.done; d2 = b.next()) if (d2 = ae(a, d2.value, c)) return d2;
          return null;
        }
        function ce(a) {
          if (!a) return null;
          /^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(a) && (a += "Z");
          a = Date.parse(a);
          return isNaN(a) ? null : a / 1e3;
        }
        function de(a) {
          if (!a) return null;
          a = RegExp("^P(?:([0-9]*)Y)?(?:([0-9]*)M)?(?:([0-9]*)D)?(?:T(?:([0-9]*)H)?(?:([0-9]*)M)?(?:([0-9.]*)S)?)?$", "i").exec(a);
          if (!a) return null;
          a = 31536e3 * Number(a[1] || null) + 2592e3 * Number(a[2] || null) + 86400 * Number(a[3] || null) + 3600 * Number(a[4] || null) + 60 * Number(a[5] || null) + Number(a[6] || null);
          return isFinite(a) ? a : null;
        }
        function ee(a) {
          var b = /([0-9]+)-([0-9]+)/.exec(a);
          if (!b) return null;
          a = Number(b[1]);
          if (!isFinite(a)) return null;
          b = Number(b[2]);
          return isFinite(b) ? {
            start: a,
            end: b
          } : null;
        }
        function fe(a) {
          a = Number(a);
          return a % 1 === 0 ? a : null;
        }
        function ge(a) {
          a = Number(a);
          return a % 1 === 0 && a > 0 ? a : null;
        }
        function he(a) {
          a = Number(a);
          return a % 1 === 0 && a >= 0 ? a : null;
        }
        function je(a) {
          a = Number(a);
          return isNaN(a) ? null : a;
        }
        function ke(a) {
          return a ? a.toLowerCase() === "true" : false;
        }
        function le(a) {
          var b;
          var c = (b = a.match(/^(\d+)\/(\d+)$/)) ? Number(b[1]) / Number(b[2]) : Number(a);
          return isNaN(c) ? null : c;
        }
        function me(a) {
          var b = [];
          a = dc(a).split(/\/+(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/);
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) {
            c = c.value;
            var d2 = c.match(/^([\w]+)/);
            if (d2) {
              var e = c.match(/(@id='(.*?)')/), f = c.match(/(@t='(\d+)')/), g = c.match(/(@n='(\d+)')/), h = c.match(/\[(\d+)\]/);
              b.push({
                name: d2[0],
                id: e ? e[0].match(/'(.*?)'/)[0].replace(/'/gm, "") : null,
                t: f ? Number(f[0].match(/'(.*?)'/)[0].replace(/'/gm, "")) : null,
                n: g ? Number(g[0].match(/'(.*?)'/)[0].replace(/'/gm, "")) : null,
                position: h ? Number(h[1]) - 1 : null,
                Ic: c.split("/@")[1] || null
              });
            } else c.startsWith("@") && b.length && (b[b.length - 1].Ic = c.slice(1));
          }
          return b;
        }
        function ne(a, b) {
          var c = me(b.attributes.sel || "");
          if (c.length) {
            var d2 = c[c.length - 1], e = b.attributes.pos || null;
            c = d2.position;
            c == null && (d2.t !== null && (c = oe(a, "t", d2.t)), d2.n !== null && (c = oe(a, "n", d2.n)));
            c === null ? c = e === "prepend" ? 0 : a.length : e === "prepend" ? --c : e === "after" && ++c;
            e = b.tagName;
            (d2 = d2.Ic) && a[c] ? pe(a[c], e, d2, Ud(b) || "") : (e !== "remove" && e !== "replace" || a.splice(c, 1), e !== "add" && e !== "replace" || a.splice.apply(a, [c, 0].concat(x(b.children))));
          }
        }
        function oe(a, b, c) {
          var d2 = 0;
          a = t2(a);
          for (var e = a.next(); !e.done; e = a.next()) {
            if (Number(e.value.attributes[b]) === c) return d2;
            d2++;
          }
          return null;
        }
        function pe(a, b, c, d2) {
          if (b === "remove") delete a.attributes[c];
          else if (b === "add" || b === "replace") a.attributes[c] = d2;
        }
        function qe(a) {
          var b = "", c = a.tagName.split(":");
          c.length > 0 && (b = c[0], b = Pd.has(b) ? Pd.get(b) : "");
          b = document.createElementNS(b, a.tagName);
          for (var d2 in a.attributes) b.setAttribute(d2, a.attributes[d2]);
          a = t2(a.children);
          for (d2 = a.next(); !d2.done; d2 = a.next()) d2 = d2.value, c = void 0, typeof d2 == "string" ? c = new Text(d2) : c = qe(d2), b.appendChild(c);
          return b;
        }
        function re(a) {
          if (!a) return null;
          var b = {
            tagName: a.tagName,
            attributes: Id(a.attributes),
            children: [],
            parent: null
          };
          a = t2(a.children);
          for (var c = a.next(); !c.done; c = a.next()) c = c.value, typeof c === "string" ? b.children.push(c) : (c = re(c), c.parent = b, b.children.push(c));
          return b;
        }
        var Od = /* @__PURE__ */ new Map(), Pd = /* @__PURE__ */ new Map();
        function se(a, b, c) {
          this.startTime = a;
          this.endTime = b;
          this.payload = c;
          this.region = new qd();
          this.position = null;
          this.positionAlign = te;
          this.size = 0;
          this.textAlign = ue;
          this.direction = ve;
          this.writingMode = we;
          this.lineInterpretation = xe;
          this.line = null;
          this.lineHeight = "";
          this.lineAlign = ye;
          this.displayAlign = ze;
          this.fontSize = this.border = this.backgroundImage = this.backgroundColor = this.color = "";
          this.fontWeight = Ae;
          this.fontStyle = Be;
          this.linePadding = this.letterSpacing = this.fontFamily = "";
          this.opacity = 1;
          this.textCombineUpright = "";
          this.textDecoration = [];
          this.textStrokeWidth = this.textStrokeColor = this.textShadow = "";
          this.wrapLine = true;
          this.id = "";
          this.nestedCues = [];
          this.lineBreak = this.isContainer = false;
          this.rubyTag = null;
          this.cellResolution = {
            columns: 32,
            rows: 15
          };
        }
        function Ce(a, b) {
          a = new se(a, b, "");
          a.lineBreak = true;
          return a;
        }
        se.prototype.clone = function() {
          var a = new se(0, 0, ""), b;
          for (b in this) a[b] = this[b], Array.isArray(a[b]) && (a[b] = a[b].slice());
          return a;
        };
        function De(a, b) {
          if (a.payload != b.payload || !(Math.abs(a.startTime - b.startTime) < 1e-3 && Math.abs(a.endTime - b.endTime) < 1e-3)) return false;
          for (var c in a) if (c != "startTime" && c != "endTime" && c != "payload") {
            if (c == "nestedCues") {
              if (!wd(a.nestedCues, b.nestedCues, De)) return false;
            } else if (c == "region" || c == "cellResolution") for (var d2 in a[c]) {
              if (a[c][d2] != b[c][d2]) return false;
            }
            else if (Array.isArray(a[c])) {
              if (!wd(a[c], b[c])) return false;
            } else if (a[c] != b[c]) return false;
          }
          return true;
        }
        function Fe(a, b) {
          b = b === void 0 ? /* @__PURE__ */ new Map() : b;
          var c = a.payload;
          if (c.includes("<")) {
            b.size === 0 && Ie(b);
            var d2 = c;
            c = [];
            for (var e = -1, f = 0; f < d2.length; f++) d2[f] === "<" ? e = f + 1 : d2[f] === ">" && e > 0 && (e = d2.substr(e, f - e), e.match(Je) && c.push(e), e = -1);
            c = t2(c);
            for (f = c.next(); !f.done; f = c.next()) f = f.value, d2 = d2.replace("<" + f + ">", '<div time="' + f + '">'), d2 += "</div>";
            a: {
              f = d2;
              e = [];
              var g = -1;
              c = "";
              d2 = false;
              for (var h = 0; h < f.length; h++) if (f[h] === "/") {
                var k2 = f.indexOf(">", h);
                if (k2 === -1) {
                  c = f;
                  break a;
                }
                if ((k2 = f.substring(h + 1, k2)) && k2 == "v") {
                  d2 = true;
                  var l = null;
                  e.length && (l = e[e.length - 1]);
                  if (l) {
                    if (l === k2) c += "/" + k2 + ">";
                    else {
                      if (!l.startsWith("v")) {
                        c += f[h];
                        continue;
                      }
                      c += "/" + l + ">";
                    }
                    h += k2.length + 1;
                  } else c += f[h];
                } else c += f[h];
              } else f[h] === "<" ? (g = h + 1, f[g] != "v" && (g = -1)) : f[h] === ">" && g > 0 && (e.push(f.substr(g, h - g)), g = -1), c += f[h];
              f = t2(e);
              for (e = f.next(); !e.done; e = f.next()) e = e.value, g = e.replace(" ", ".voice-"), c = c.replace("<" + e + ">", "<" + g + ">"), c = c.replace("</" + e + ">", "</" + g + ">"), d2 || (c += "</" + g + ">");
            }
            c = Ke(c);
            a.payload = "";
            try {
              var m = Ld("<span>" + c + "</span>", "span");
            } catch (n) {
            }
            if (m) {
              if (m = m.children, m.length != 1 || m[0].tagName) for (m = t2(m), c = m.next(); !c.done; c = m.next()) Le(c.value, a, b);
              else a.payload = dc(c);
            } else a.payload = dc(c);
          } else a.payload = dc(c);
        }
        function Ie(a) {
          for (var b = t2(Object.entries(Me)), c = b.next(); !c.done; c = b.next()) {
            var d2 = t2(c.value);
            c = d2.next().value;
            d2 = d2.next().value;
            var e = new se(0, 0, "");
            e.color = d2;
            a.set("." + c, e);
          }
          b = t2(Object.entries(Ne));
          for (c = b.next(); !c.done; c = b.next()) d2 = t2(c.value), c = d2.next().value, d2 = d2.next().value, e = new se(0, 0, ""), e.backgroundColor = d2, a.set("." + c, e);
        }
        function Ke(a) {
          var b = {
            "< ": "",
            " >": " &gt;"
          }, c = /(< +>|<\s|\s>)/g, d2 = RegExp(c.source);
          return a && d2.test(a) ? a.replace(c, function(e) {
            return b[e] || "";
          }) : a || "";
        }
        function Le(a, b, c) {
          var d2 = b.clone();
          d2.nestedCues = [];
          d2.payload = "";
          d2.rubyTag = "";
          d2.line = null;
          d2.region = new qd();
          d2.position = null;
          d2.size = 0;
          d2.textAlign = ue;
          if (a.tagName) for (var e = t2(a.tagName.split(/(?=[ .])+/g)), f = e.next(); !f.done; f = e.next()) {
            var g = f = f.value;
            if (g.startsWith(".voice-")) {
              var h = g.split("-").pop();
              g = 'v[voice="' + h + '"]';
              c.has(g) || (g = "v[voice=" + h + "]");
            }
            c.has(g) && (h = d2, g = c.get(g)) && (h.backgroundColor = Oe(g.backgroundColor, h.backgroundColor), h.color = Oe(g.color, h.color), h.fontFamily = Oe(g.fontFamily, h.fontFamily), h.fontSize = Oe(g.fontSize, h.fontSize), h.textShadow = Oe(g.textShadow, h.textShadow), h.fontWeight = g.fontWeight, h.fontStyle = g.fontStyle, h.opacity = g.opacity, h.rubyTag = g.rubyTag, h.textCombineUpright = g.textCombineUpright, h.wrapLine = g.wrapLine);
            switch (f) {
              case "br":
                d2 = Ce(d2.startTime, d2.endTime);
                b.nestedCues.push(d2);
                return;
              case "b":
                d2.fontWeight = Pe;
                break;
              case "i":
                d2.fontStyle = Qe;
                break;
              case "u":
                d2.textDecoration.push(Re);
                break;
              case "font":
                if (f = a.attributes.color) d2.color = f;
                break;
              case "div":
                f = a.attributes.time;
                if (!f) break;
                if (f = Fd(f)) d2.startTime = f;
                break;
              case "ruby":
              case "rp":
              case "rt":
                d2.rubyTag = f;
            }
          }
          e = a.children;
          if (Qd(a) || e.length == 1 && Qd(e[0])) for (c = Td(a).split("\n"), a = true, c = t2(c), e = c.next(); !e.done; e = c.next()) e = e.value, a || (a = Ce(d2.startTime, d2.endTime), b.nestedCues.push(a)), e.length > 0 && (a = d2.clone(), a.payload = dc(e), b.nestedCues.push(a)), a = false;
          else for (b.nestedCues.push(d2), b = t2(e), a = b.next(); !a.done; a = b.next()) Le(a.value, d2, c);
        }
        function Oe(a, b) {
          return a && a.length > 0 ? a : b;
        }
        S("shaka.text.Cue", se);
        se.parseCuePayload = Fe;
        se.equal = De;
        se.prototype.clone = se.prototype.clone;
        var te = "auto";
        se.positionAlign = {
          LEFT: "line-left",
          RIGHT: "line-right",
          CENTER: "center",
          AUTO: te
        };
        var ue = "center", Se = {
          LEFT: "left",
          RIGHT: "right",
          CENTER: ue,
          START: "start",
          END: "end"
        };
        se.textAlign = Se;
        var ze = "after", Te = {
          BEFORE: "before",
          CENTER: "center",
          AFTER: ze
        };
        se.displayAlign = Te;
        var ve = "ltr";
        se.direction = {
          HORIZONTAL_LEFT_TO_RIGHT: ve,
          HORIZONTAL_RIGHT_TO_LEFT: "rtl"
        };
        var we = "horizontal-tb";
        se.writingMode = {
          HORIZONTAL_TOP_TO_BOTTOM: we,
          VERTICAL_LEFT_TO_RIGHT: "vertical-lr",
          VERTICAL_RIGHT_TO_LEFT: "vertical-rl"
        };
        var xe = 0;
        se.lineInterpretation = {
          LINE_NUMBER: xe,
          PERCENTAGE: 1
        };
        var ye = "start", Ue = {
          CENTER: "center",
          START: ye,
          END: "end"
        };
        se.lineAlign = Ue;
        var Me = {
          white: "white",
          lime: "lime",
          cyan: "cyan",
          red: "red",
          yellow: "yellow",
          magenta: "magenta",
          blue: "blue",
          black: "black"
        };
        se.defaultTextColor = Me;
        var Ne = {
          bg_white: "white",
          bg_lime: "lime",
          bg_cyan: "cyan",
          bg_red: "red",
          bg_yellow: "yellow",
          bg_magenta: "magenta",
          bg_blue: "blue",
          bg_black: "black"
        };
        se.defaultTextBackgroundColor = Ne;
        var Ae = 400, Pe = 700;
        se.fontWeight = {
          NORMAL: Ae,
          BOLD: Pe
        };
        var Be = "normal", Qe = "italic", Ve = {
          NORMAL: Be,
          ITALIC: Qe,
          OBLIQUE: "oblique"
        };
        se.fontStyle = Ve;
        var Re = "underline";
        se.textDecoration = {
          UNDERLINE: Re,
          LINE_THROUGH: "lineThrough",
          OVERLINE: "overline"
        };
        var Je = /(?:(\d{1,}):)?(\d{2}):(\d{2})\.(\d{2,3})/g;
        function We() {
        }
        We.prototype.destroy = function() {
        };
        function Xe(a, b, c) {
          Ye.set(a.toLowerCase().split(";")[0] + "-" + c, {
            priority: c,
            Uf: b
          });
        }
        function Ze(a, b) {
          for (var c = a.toLowerCase().split(";")[0], d2 = t2([$e, af, bf, cf]), e = d2.next(); !e.done; e = d2.next()) if (e = Ye.get(c + "-" + e.value)) {
            var f = e.Uf(), g = f.isSupported(a, b);
            f.destroy();
            if (g) return e.Uf;
          }
          return null;
        }
        S("shaka.transmuxer.TransmuxerEngine", We);
        We.findTransmuxer = Ze;
        We.unregisterTransmuxer = function(a, b) {
          Ye.delete(a.toLowerCase().split(";")[0] + "-" + b);
        };
        We.registerTransmuxer = Xe;
        We.prototype.destroy = We.prototype.destroy;
        var Ye = /* @__PURE__ */ new Map(), cf = 1, bf = 2, af = 3, $e = 4;
        We.PluginPriority = {
          FALLBACK: cf,
          PREFERRED_SECONDARY: bf,
          PREFERRED: af,
          APPLICATION: $e
        };
        function df() {
        }
        function ef(a, b) {
          var c = a;
          b && !ff.includes(a) && (c += '; codecs="' + b + '"');
          return c;
        }
        function gf(a, b) {
          b && (a += '; codecs="' + b + '"');
          return a;
        }
        function hf(a, b, c) {
          var d2 = ef(a, b);
          b = gf(a, b);
          Ze(b) ? (a = Ze(b)) ? (a = a(), c = a.convertCodecs(c, b), a.destroy()) : c = b : c = a != "video/mp2t" && c == "audio" ? d2.replace("video", "audio") : d2;
          return c;
        }
        function jf(a) {
          return a.split(";")[0].split("/")[1];
        }
        function kf(a) {
          var b = lf(a);
          a = b[0].toLowerCase();
          b = b[1].toLowerCase();
          switch (true) {
            case (a === "mp4a" && b === "69"):
            case (a === "mp4a" && b === "6b"):
            case (a === "mp4a" && b === "40.34"):
              return "mp3";
            case (a === "mp4a" && b === "66"):
            case (a === "mp4a" && b === "67"):
            case (a === "mp4a" && b === "68"):
            case (a === "mp4a" && b === "40.2"):
            case (a === "mp4a" && b === "40.02"):
            case (a === "mp4a" && b === "40.5"):
            case (a === "mp4a" && b === "40.05"):
            case (a === "mp4a" && b === "40.29"):
            case (a === "mp4a" && b === "40.42"):
              return "aac";
            case (a === "mp4a" && b === "a5"):
            case a === "ac3":
            case a === "ac-3":
              return "ac-3";
            case (a === "mp4a" && b === "a6"):
            case a === "eac3":
            case a === "ec-3":
              return "ec-3";
            case a === "ac-4":
              return "ac-4";
            case (a === "mp4a" && b === "b2"):
              return "dtsx";
            case (a === "mp4a" && b === "a9"):
              return "dtsc";
            case a === "vp09":
            case a === "vp9":
              return "vp9";
            case a === "avc1":
            case a === "avc3":
              return "avc";
            case a === "hvc1":
            case a === "hev1":
              return "hevc";
            case a === "vvc1":
            case a === "vvi1":
              return "vvc";
            case a === "dvh1":
            case a === "dvhe":
              return b && b.startsWith("05") ? "dovi-p5" : "dovi-hevc";
            case a === "dvav":
            case a === "dva1":
              return "dovi-avc";
            case a === "dav1":
              return "dovi-av1";
            case a === "dvc1":
            case a === "dvi1":
              return "dovi-vvc";
          }
          return a;
        }
        function mf(a) {
          var b = [];
          a = t2(a.split(","));
          for (var c = a.next(); !c.done; c = a.next()) c = lf(c.value), b.push(c[0]);
          return b.sort().join(",");
        }
        function nf(a) {
          return a.split(";")[0];
        }
        function of(a) {
          a = a.split(/ *; */);
          a.shift();
          return (a = a.find(function(b) {
            return b.startsWith("codecs=");
          })) ? a.split("=")[1].replace(/^"|"$/g, "") : "";
        }
        function pf(a) {
          return a === "application/x-mpegurl" || a === "application/vnd.apple.mpegurl";
        }
        function lf(a) {
          a = a.split(".");
          var b = a[0];
          a.shift();
          return [b, a.join(".")];
        }
        S("shaka.util.MimeUtils", df);
        df.getFullTypeWithAllCodecs = gf;
        df.getFullType = ef;
        (/* @__PURE__ */ new Map()).set("codecs", "codecs").set("frameRate", "framerate").set("bandwidth", "bitrate").set("width", "width").set("height", "height").set("channelsCount", "channels");
        var ff = ["audio/aac", "audio/ac3", "audio/ec3", "audio/mpeg"];
        function qf(a) {
          this.i = null;
          this.j = a;
          this.D = false;
          this.l = this.A = 0;
          this.m = Infinity;
          this.h = this.g = null;
          this.F = "";
          this.C = function() {
          };
          this.u = /* @__PURE__ */ new Map();
        }
        function rf(a, b) {
          tf.set(a, b);
        }
        function uf(a) {
          return tf.get(a);
        }
        function vf(a) {
          return tf.has(a) ? true : a == "application/cea-608" || a == "application/cea-708" ? !!nd : false;
        }
        qf.prototype.destroy = function() {
          this.j = this.i = null;
          this.u.clear();
          return Promise.resolve();
        };
        function wf(a, b, c, d2, e) {
          var f, g, h, k2, l, m, n;
          return P(function(q) {
            if (q.g == 1) return G(q, Promise.resolve(), 2);
            if (!a.i || !a.j) return q.return();
            if (c == null || d2 == null) return a.i.parseInit(Lb(b)), q.return();
            f = a.D ? c : a.A;
            g = {
              periodStart: a.A,
              segmentStart: c,
              segmentEnd: d2,
              vttOffset: f
            };
            h = a.i.parseMedia(Lb(b), g, e, []);
            k2 = t2(h);
            for (l = k2.next(); !l.done; l = k2.next()) m = l.value, a.C(m, e || null, g);
            n = h.filter(function(r2) {
              return r2.startTime >= a.l && r2.startTime < a.m;
            });
            a.j.append(n);
            a.g == null && (a.g = Math.max(c, a.l));
            a.h = Math.min(d2, a.m);
            H(q);
          });
        }
        qf.prototype.remove = function(a, b) {
          var c = this;
          return P(function(d2) {
            if (d2.g == 1) return G(d2, Promise.resolve(), 2);
            !c.j || !c.j.remove(a, b) || c.g == null || b <= c.g || a >= c.h || (a <= c.g && b >= c.h ? c.g = c.h = null : a <= c.g && b < c.h ? c.g = b : a > c.g && b >= c.h && (c.h = a));
            H(d2);
          });
        };
        function xf(a, b, c) {
          a.l = b;
          a.m = c;
        }
        function yf(a, b, c) {
          a.F = b;
          if (b = a.u.get(b)) for (var d2 = t2(b.keys()), e = d2.next(); !e.done; e = d2.next()) (e = b.get(e.value).filter(function(f) {
            return f.endTime <= c;
          })) && a.j.append(e);
        }
        function zf(a, b, c) {
          b.startTime += c;
          b.endTime += c;
          b = t2(b.nestedCues);
          for (var d2 = b.next(); !d2.done; d2 = b.next()) zf(a, d2.value, c);
        }
        function Af(a, b, c, d2, e) {
          var f = c + " " + d2, g = /* @__PURE__ */ new Map();
          b = t2(b);
          for (var h = b.next(); !h.done; h = b.next()) {
            var k2 = h.value;
            h = k2.stream;
            k2 = k2.cue;
            g.has(h) || g.set(h, /* @__PURE__ */ new Map());
            g.get(h).has(f) || g.get(h).set(f, []);
            zf(a, k2, e);
            k2.startTime >= a.l && k2.startTime < a.m && (g.get(h).get(f).push(k2), h == a.F && a.j.append([k2]));
          }
          e = t2(g.keys());
          for (f = e.next(); !f.done; f = e.next()) for (f = f.value, a.u.has(f) || a.u.set(f, /* @__PURE__ */ new Map()), b = t2(g.get(f).keys()), h = b.next(); !h.done; h = b.next()) h = h.value, k2 = g.get(f).get(h), a.u.get(f).set(h, k2);
          a.g = a.g == null ? Math.max(c, a.l) : Math.min(a.g, Math.max(c, a.l));
          a.h = Math.max(a.h, Math.min(d2, a.m));
        }
        S("shaka.text.TextEngine", qf);
        qf.prototype.destroy = qf.prototype.destroy;
        qf.findParser = uf;
        qf.unregisterParser = function(a) {
          tf.delete(a);
        };
        qf.registerParser = rf;
        var tf = /* @__PURE__ */ new Map();
        function Bf(a) {
          this.h = a;
          this.g = null;
        }
        Bf.prototype.Y = function(a) {
          var b = this;
          this.stop();
          var c = true, d2 = null;
          this.g = function() {
            window7.clearTimeout(d2);
            c = false;
          };
          d2 = window7.setTimeout(function() {
            c && b.h();
          }, a * 1e3);
          return this;
        };
        Bf.prototype.stop = function() {
          this.g && (this.g(), this.g = null);
        };
        function Cf(a) {
          this.h = a;
          this.g = null;
        }
        Cf.prototype.La = function() {
          this.stop();
          this.h();
          return this;
        };
        Cf.prototype.Y = function(a) {
          var b = this;
          this.stop();
          this.g = new Bf(function() {
            b.h();
          }).Y(a);
          return this;
        };
        Cf.prototype.za = function(a) {
          var b = this;
          this.stop();
          this.g = new Bf(function() {
            b.g.Y(a);
            b.h();
          }).Y(a);
          return this;
        };
        Cf.prototype.stop = function() {
          this.g && (this.g.stop(), this.g = null);
        };
        S("shaka.util.Timer", Cf);
        Cf.prototype.stop = Cf.prototype.stop;
        Cf.prototype.tickEvery = Cf.prototype.za;
        Cf.prototype.tickAfter = Cf.prototype.Y;
        Cf.prototype.tickNow = Cf.prototype.La;
        function Df(a, b) {
          return a.concat(b);
        }
        function Ef() {
        }
        function Ff(a) {
          return a != null;
        }
        function Gf(a, b) {
          return Promise.race([b, new Promise(function(c, d2) {
            new Cf(d2).Y(a);
          })]);
        }
        ;
        function Hf() {
        }
        function If(a, b, c, d2, e) {
          function f(y) {
            var z = String(y.width || "") + String(y.height || "") + String(Math.round(y.frameRate || 0)) + (y.hdr || "") + y.fastSwitching;
            y.dependencyStream && (z += y.dependencyStream.baseOriginalId || "");
            return z;
          }
          function g(y) {
            var z = y.language + (y.channelsCount || 0) + (y.audioSamplingRate || 0) + y.roles.join(",") + y.label + y.groupId + y.fastSwitching;
            y.dependencyStream && (z += y.dependencyStream.baseOriginalId || "");
            return z;
          }
          if (e.length) {
            var h = a.textStreams;
            e = t2(e);
            for (var k2 = e.next(), l = {}; !k2.done; l = {
              si: void 0
            }, k2 = e.next()) if (l.si = k2.value, k2 = h.filter(/* @__PURE__ */ function(y) {
              return function(z) {
                return z.codecs.startsWith(y.si) || z.mimeType.startsWith(y.si) ? true : false;
              };
            }(l)), k2.length) {
              h = k2;
              break;
            }
            a.textStreams = h;
          }
          h = a.variants;
          if (b.length || c.length) h = Jf(h, b, c);
          if (d2.length) {
            b = new kb();
            c = t2(h);
            for (h = c.next(); !h.done; h = c.next()) h = h.value, b.push(String(h.video.width || 0), h);
            var m = [];
            b.forEach(function(y, z) {
              y = 0;
              var A = [];
              z = t2(z);
              for (var C = z.next(), D = {}; !C.done; D = {
                wg: void 0
              }, C = z.next()) D.wg = C.value, C = d2.filter(/* @__PURE__ */ function(F) {
                return function(B) {
                  return F.wg.decodingInfos[0][B];
                };
              }(D)).length, C > y ? (y = C, A = [D.wg]) : C == y && A.push(D.wg);
              m.push.apply(m, x(A));
            });
            h = m;
          }
          c = /* @__PURE__ */ new Set();
          b = /* @__PURE__ */ new Set();
          h = t2(h);
          for (e = h.next(); !e.done; e = h.next()) e = e.value, e.audio && c.add(e.audio), e.video && b.add(e.video);
          h = Array.from(c).sort(function(y, z) {
            return y.bandwidth - z.bandwidth;
          });
          var n = [];
          c = /* @__PURE__ */ new Map();
          h = t2(h);
          for (e = h.next(); !e.done; e = h.next()) {
            e = e.value;
            k2 = g(e);
            l = c.get(k2) || [];
            if (l.length) {
              var q = l[l.length - 1], r2 = kf(q.codecs), u = kf(e.codecs);
              r2 != u || e.bandwidth && q.bandwidth && !(e.bandwidth > q.bandwidth) || (l.push(e), n.push(e.id));
            } else l.push(e), n.push(e.id);
            c.set(k2, l);
          }
          var w = {
            vp8: 1,
            avc: 1,
            "dovi-avc": 0.95,
            vp9: 0.9,
            vp09: 0.9,
            hevc: 0.85,
            "dovi-hevc": 0.8,
            "dovi-p5": 0.75,
            av01: 0.7,
            "dovi-av1": 0.65,
            vvc: 0.6
          };
          h = Array.from(b).sort(function(y, z) {
            if (!y.bandwidth || !z.bandwidth || y.bandwidth == z.bandwidth) {
              if (y.codecs && z.codecs && y.codecs != z.codecs && y.width == z.width) {
                var A = kf(y.codecs), C = kf(z.codecs);
                if (A != C) return (w[A] || 1) - (w[C] || 1);
              }
              return y.width - z.width;
            }
            return y.bandwidth - z.bandwidth;
          });
          b = fd();
          var v = [];
          c = /* @__PURE__ */ new Map();
          h = t2(h);
          for (e = h.next(); !e.done; e = h.next()) {
            e = e.value;
            k2 = f(e);
            l = c.get(k2) || [];
            if (l.length) {
              q = l[l.length - 1];
              if (!b && (r2 = kf(q.codecs), u = kf(e.codecs), r2 !== u)) continue;
              r2 = kf(q.codecs);
              u = kf(e.codecs);
              r2 != u || e.bandwidth && q.bandwidth && !(e.bandwidth > q.bandwidth) || (l.push(e), v.push(e.id));
            } else l.push(e), v.push(e.id);
            c.set(k2, l);
          }
          a.variants = a.variants.filter(function(y) {
            var z = y.audio;
            y = y.video;
            return z && !n.includes(z.id) || y && !v.includes(y.id) ? false : true;
          });
        }
        function Jf(a, b, c) {
          b = t2(b);
          for (var d2 = b.next(), e = {}; !d2.done; e = {
            videoCodec: void 0
          }, d2 = b.next()) if (e.videoCodec = d2.value, d2 = a.filter(/* @__PURE__ */ function(f) {
            return function(g) {
              return g.video && g.video.codecs.startsWith(f.videoCodec);
            };
          }(e)), d2.length) {
            a = d2;
            break;
          }
          c = t2(c);
          b = c.next();
          for (d2 = {}; !b.done; d2 = {
            audioCodec: void 0
          }, b = c.next()) if (d2.audioCodec = b.value, b = a.filter(/* @__PURE__ */ function(f) {
            return function(g) {
              return g.audio && g.audio.codecs.startsWith(f.audioCodec);
            };
          }(d2)), b.length) {
            a = b;
            break;
          }
          return a;
        }
        function Kf(a, b, c) {
          a.variants = a.variants.filter(function(d2) {
            return Lf(d2, b, c);
          });
        }
        function Lf(a, b, c) {
          function d2(h, k2, l) {
            return h >= k2 && h <= l;
          }
          var e = a.video;
          if (e && e.width && e.height) {
            var f = e.width, g = e.height;
            g > f && (g = t2([g, f]), f = g.next().value, g = g.next().value);
            if (!d2(f, b.minWidth, Math.min(b.maxWidth, c.width)) || !d2(g, b.minHeight, Math.min(b.maxHeight, c.height)) || !d2(e.width * e.height, b.minPixels, b.maxPixels)) return false;
          }
          return a && a.video && a.video.frameRate && !d2(a.video.frameRate, b.minFrameRate, b.maxFrameRate) || a && a.audio && a.audio.channelsCount && !d2(a.audio.channelsCount, b.minChannelsCount, b.maxChannelsCount) || !d2(a.bandwidth, b.minBandwidth, b.maxBandwidth) ? false : true;
        }
        function Mf(a, b, c, d2) {
          c = c === void 0 ? [] : c;
          d2 = d2 === void 0 ? {} : d2;
          return P(function(e) {
            if (e.g == 1) return G(e, Nf(a, b, b.offlineSessionIds.length > 0, c, d2), 2);
            Of(b);
            return G(e, Pf(b), 0);
          });
        }
        function Nf(a, b, c, d2, e) {
          var f, g;
          return P(function(h) {
            if (h.g == 1) return Sb().Qj() && Qf(b.variants), G(h, Rf(b.variants, c, false, d2), 2);
            f = null;
            a && (g = a.g) && (f = g.keySystem);
            b.variants = b.variants.filter(function(k2) {
              var l = Sf(k2, f, e);
              if (!l) {
                var m = [];
                k2.audio && m.push(Tf(k2.audio));
                k2.video && m.push(Tf(k2.video));
              }
              return l;
            });
            H(h);
          });
        }
        function Qf(a) {
          var b = (/* @__PURE__ */ new Map()).set("dvav", "avc3").set("dva1", "avc1").set("dvhe", "hev1").set("dvh1", "hvc1").set("dvc1", "vvc1").set("dvi1", "vvi1"), c = /* @__PURE__ */ new Set();
          a = t2(a);
          for (var d2 = a.next(); !d2.done; d2 = a.next()) d2 = d2.value, d2.video && c.add(d2.video);
          c = t2(c);
          for (a = c.next(); !a.done; a = c.next()) {
            a = a.value;
            d2 = t2(b);
            for (var e = d2.next(); !e.done; e = d2.next()) {
              var f = t2(e.value);
              e = f.next().value;
              f = f.next().value;
              if (a.codecs.includes(e)) {
                a.codecs = a.codecs.replace(e, f);
                break;
              }
            }
          }
        }
        function Sf(a, b, c) {
          if (!a.decodingInfos.some(function(k2) {
            return !k2.supported || b && (k2 = k2.keySystemAccess) && (c[k2.keySystem] || k2.keySystem) != b ? false : true;
          })) return false;
          var d2 = Sb(), e = d2.Ub() === "Xbox";
          d2 = d2.Ka() === "MOBILE" && d2.Ga() === "GECKO";
          var f = a.video, g = f && f.width || 0, h = f && f.height || 0;
          if (e && f && (g > 1920 || h > 1080) && (f.codecs.includes("avc1.") || f.codecs.includes("avc3.")) || (e = f && f.dependencyStream) && !cd(e)) return false;
          a = a.audio;
          return d2 && a && a.encrypted && a.codecs.toLowerCase().includes("opus") || a && a.dependencyStream ? false : true;
        }
        function Uf(a, b) {
          var c, d2, e, f, g, h, k2;
          return P(function(l) {
            if (l.g == 1) {
              c = function(m, n) {
                if (m) {
                  var q = Id(m);
                  q.supported = m.supported && n.supported;
                  q.powerEfficient = m.powerEfficient && n.powerEfficient;
                  q.smooth = m.smooth && n.smooth;
                  n.keySystemAccess && !q.keySystemAccess && (q.keySystemAccess = n.keySystemAccess);
                  return q;
                }
                return n;
              };
              d2 = null;
              e = [];
              f = t2(b);
              g = f.next();
              for (h = {}; !g.done; h = {
                cache: void 0,
                gf: void 0
              }, g = f.next()) k2 = g.value, h.gf = Jd(k2), h.cache = Vf, h.cache.has(h.gf) ? d2 = c(d2, h.cache.get(h.gf)) : e.push(Wf(k2).then(/* @__PURE__ */ function(m) {
                return function(n) {
                  var q = null;
                  n = t2(n || []);
                  for (var r2 = n.next(); !r2.done; r2 = n.next()) q = c(q, r2.value);
                  q && (m.cache.set(m.gf, q), d2 = c(d2, q));
                };
              }(h)));
              return G(l, Promise.all(e), 2);
            }
            d2 && a.decodingInfos.push(d2);
            H(l);
          });
        }
        function Wf(a) {
          var b = [""];
          a.video && (b = of(a.video.contentType).split(","));
          var c = [""];
          a.audio && (c = of(a.audio.contentType).split(","));
          var d2 = [];
          b = t2(b);
          for (var e = b.next(); !e.done; e = b.next()) {
            e = e.value;
            for (var f = t2(c), g = f.next(), h = {}; !g.done; h = {
              bd: void 0
            }, g = f.next()) g = g.value, h.bd = Hd(a), a.video && (h.bd.video.contentType = ef(nf(h.bd.video.contentType), e)), a.audio && (h.bd.audio.contentType = ef(nf(h.bd.audio.contentType), g)), d2.push(new Promise(/* @__PURE__ */ function(k2) {
              return function(l, m) {
                (Sb().Ka() == "MOBILE" ? Gf(5, navigator.mediaCapabilities.decodingInfo(k2.bd)) : navigator.mediaCapabilities.decodingInfo(k2.bd)).then(function(n) {
                  l(n);
                }).catch(m);
              };
            }(h)));
          }
          return Promise.all(d2).catch(function() {
            JSON.stringify(a);
            return null;
          });
        }
        function Rf(a, b, c, d2) {
          var e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F;
          return P(function(B) {
            switch (B.g) {
              case 1:
                if (e = a.some(function(E) {
                  return E.decodingInfos.length;
                })) return B.return();
                f = t2(d2);
                g = f.next();
                h = {};
              case 2:
                if (g.done) {
                  B.B(4);
                  break;
                }
                h.uj = g.value;
                k2 = false;
                l = t2(a);
                m = l.next();
              case 5:
                if (m.done) {
                  B.B(7);
                  break;
                }
                n = m.value;
                q = Xf(n, b, c).filter(/* @__PURE__ */ function(E) {
                  return function(I) {
                    I = I[0];
                    return (I.keySystemConfiguration && I.keySystemConfiguration.keySystem) === E.uj;
                  };
                }(h));
                r2 = t2(q);
                u = r2.next();
              case 8:
                if (u.done) {
                  B.B(10);
                  break;
                }
                w = u.value;
                return G(B, Uf(n, w), 9);
              case 9:
                u = r2.next();
                B.B(8);
                break;
              case 10:
                n.decodingInfos.some(function(E) {
                  return E.supported;
                }) && (k2 = true);
                m = l.next();
                B.B(5);
                break;
              case 7:
                if (k2) return B.return();
                h = {
                  uj: void 0
                };
                g = f.next();
                B.B(2);
                break;
              case 4:
                v = t2(a), y = v.next();
              case 12:
                if (y.done) {
                  B.B(0);
                  break;
                }
                z = y.value;
                A = Xf(z, b, c).filter(function(E) {
                  E = E[0];
                  E = E.keySystemConfiguration && E.keySystemConfiguration.keySystem;
                  return !E || !d2.includes(E);
                });
                C = t2(A);
                D = C.next();
              case 15:
                if (D.done) {
                  y = v.next();
                  B.B(12);
                  break;
                }
                F = D.value;
                return G(B, Uf(z, F), 16);
              case 16:
                D = C.next(), B.B(15);
            }
          });
        }
        function Xf(a, b, c) {
          var d2 = a.audio, e = a.video, f = [], g = [];
          if (e) for (var h = t2(e.fullMimeTypes), k2 = h.next(); !k2.done; k2 = h.next()) {
            k2 = k2.value;
            var l = of(k2);
            if (l.includes(",") && !d2) {
              var m = l.split(","), n = nf(k2);
              l = qc("video", m);
              m = qc("audio", m);
              m = Yf(m, n);
              n = hf(n, m, "audio");
              g.push({
                contentType: n,
                channels: 2,
                bitrate: a.bandwidth || 1,
                samplerate: 1,
                spatialRendering: false
              });
            }
            l = Zf(l);
            k2 = {
              contentType: hf(nf(k2), l, "video"),
              width: e.width || 64,
              height: e.height || 64,
              bitrate: e.bandwidth || a.bandwidth || 1,
              framerate: e.frameRate || 30
            };
            if (e.hdr) switch (e.hdr) {
              case "PQ":
                k2.transferFunction = "pq";
                break;
              case "HLG":
                k2.transferFunction = "hlg";
            }
            e.colorGamut && (k2.colorGamut = e.colorGamut);
            f.push(k2);
          }
          if (d2) for (h = t2(d2.fullMimeTypes), k2 = h.next(); !k2.done; k2 = h.next()) l = k2.value, k2 = nf(l), l = Yf(of(l), k2), k2 = hf(k2, l, "audio"), g.push({
            contentType: k2,
            channels: d2.channelsCount || 2,
            bitrate: d2.bandwidth || a.bandwidth || 1,
            samplerate: d2.audioSamplingRate || 1,
            spatialRendering: d2.spatialAudio
          });
          h = [];
          f.length == 0 && f.push(null);
          g.length == 0 && g.push(null);
          f = t2(f);
          for (k2 = f.next(); !k2.done; k2 = f.next()) for (k2 = k2.value, l = t2(g), n = l.next(); !n.done; n = l.next()) n = n.value, m = {
            type: c ? "file" : "media-source"
          }, k2 && (m.video = k2), n && (m.audio = n), h.push(m);
          g = (a.video ? a.video.drmInfos : []).concat(a.audio ? a.audio.drmInfos : []);
          if (!g.length) return [h];
          a = [];
          c = /* @__PURE__ */ new Map();
          g = t2(g);
          for (f = g.next(); !f.done; f = g.next()) f = f.value, c.get(f.keySystem) || c.set(f.keySystem, []), c.get(f.keySystem).push(f);
          g = b ? "required" : "optional";
          b = b ? ["persistent-license"] : ["temporary"];
          f = t2(c.keys());
          for (k2 = f.next(); !k2.done; k2 = f.next()) {
            k2 = k2.value;
            n = c.get(k2);
            l = /* @__PURE__ */ new Map();
            n = t2(n);
            for (m = n.next(); !m.done; m = n.next()) {
              m = m.value;
              var q = m.videoRobustness + "," + m.audioRobustness;
              l.get(q) || l.set(q, []);
              l.get(q).push(m);
            }
            l = t2(l.values());
            for (n = l.next(); !n.done; n = l.next()) {
              n = n.value;
              m = [];
              q = t2(h);
              for (var r2 = q.next(); !r2.done; r2 = q.next()) {
                r2 = Object.assign({}, r2.value);
                for (var u = {
                  keySystem: k2,
                  initDataType: "cenc",
                  persistentState: g,
                  distinctiveIdentifier: "optional",
                  sessionTypes: b
                }, w = t2(n), v = w.next(); !v.done; v = w.next()) {
                  v = v.value;
                  if (v.initData && v.initData.length) {
                    for (var y = /* @__PURE__ */ new Set(), z = t2(v.initData), A = z.next(); !A.done; A = z.next()) y.add(A.value.initDataType);
                    u.initDataType = v.initData[0].initDataType;
                  }
                  v.distinctiveIdentifierRequired && (u.distinctiveIdentifier = "required");
                  v.persistentStateRequired && (u.persistentState = "required");
                  v.sessionType && (u.sessionTypes = [v.sessionType]);
                  d2 && (u.audio ? (v.encryptionScheme && (u.audio.encryptionScheme = u.audio.encryptionScheme || v.encryptionScheme), u.audio.robustness = u.audio.robustness || v.audioRobustness) : (u.audio = {
                    robustness: v.audioRobustness
                  }, v.encryptionScheme && (u.audio.encryptionScheme = v.encryptionScheme)), u.audio.robustness == "" && delete u.audio.robustness);
                  e && (u.video ? (v.encryptionScheme && (u.video.encryptionScheme = u.video.encryptionScheme || v.encryptionScheme), u.video.robustness = u.video.robustness || v.videoRobustness) : (u.video = {
                    robustness: v.videoRobustness
                  }, v.encryptionScheme && (u.video.encryptionScheme = v.encryptionScheme)), u.video.robustness == "" && delete u.video.robustness);
                }
                r2.keySystemConfiguration = u;
                m.push(r2);
              }
              a.push(m);
            }
          }
          return a;
        }
        function Yf(a, b) {
          var c = Sb();
          return a.toLowerCase() == "flac" ? c.Ga() != "WEBKIT" ? "flac" : "fLaC" : a.toLowerCase() === "opus" ? c.Ga() != "WEBKIT" ? "opus" : jf(b) == "mp4" ? "Opus" : "opus" : a.toLowerCase() == "ac-3" && c.Ce() ? "ec-3" : a;
        }
        function Zf(a) {
          if (a.includes("avc1")) {
            var b = a.split(".");
            if (b.length == 3) return a = b.shift() + ".", a += parseInt(b.shift(), 10).toString(16), a += ("000" + parseInt(b.shift(), 10).toString(16)).slice(-4);
          } else if (a == "vp9") return "vp09.00.41.08";
          return a;
        }
        function Of(a) {
          a.textStreams = a.textStreams.filter(function(b) {
            b = ef(b.mimeType, b.codecs);
            return vf(b);
          });
        }
        function Pf(a) {
          var b, c, d2, e, f, g, h, k2;
          return P(function(l) {
            switch (l.g) {
              case 1:
                b = [], c = t2(a.imageStreams), d2 = c.next();
              case 2:
                if (d2.done) {
                  l.B(4);
                  break;
                }
                e = d2.value;
                f = e.mimeType;
                f == "application/mp4" && e.codecs == "mjpg" && (f = "image/jpg");
                if ($f.has(f)) {
                  l.B(5);
                  break;
                }
                g = ag.get(f);
                if (!g) {
                  $f.set(f, false);
                  l.B(5);
                  break;
                }
                return G(l, bg(g), 7);
              case 7:
                h = l.h, $f.set(f, h);
              case 5:
                (k2 = $f.get(f)) && b.push(e);
                d2 = c.next();
                l.B(2);
                break;
              case 4:
                a.imageStreams = b, H(l);
            }
          });
        }
        function bg(a) {
          return new Promise(function(b) {
            var c = new Image();
            c.src = a;
            "decode" in c ? c.decode().then(function() {
              b(true);
            }).catch(function() {
              b(false);
            }) : c.onload = c.onerror = function() {
              b(c.height === 2);
            };
          });
        }
        function cg(a) {
          var b = a.audio, c = a.video, d2 = b ? b.mimeType : null, e = c ? c.mimeType : null, f = b ? b.codecs : null, g = c ? c.codecs : null, h = b ? b.groupId : null, k2 = [];
          c && k2.push(c.mimeType);
          b && k2.push(b.mimeType);
          k2 = k2[0] || null;
          var l = [];
          b && l.push(b.kind);
          c && l.push(c.kind);
          l = l[0] || null;
          var m = /* @__PURE__ */ new Set();
          if (b) for (var n = t2(b.roles), q = n.next(); !q.done; q = n.next()) m.add(q.value);
          if (c) for (n = t2(c.roles), q = n.next(); !q.done; q = n.next()) m.add(q.value);
          a = {
            id: a.id,
            active: false,
            type: "variant",
            bandwidth: a.bandwidth,
            language: a.language,
            label: null,
            kind: l,
            width: null,
            height: null,
            frameRate: null,
            pixelAspectRatio: null,
            hdr: null,
            colorGamut: null,
            videoLayout: null,
            mimeType: k2,
            audioMimeType: d2,
            videoMimeType: e,
            codecs: "",
            audioCodec: f,
            videoCodec: g,
            primary: a.primary,
            roles: Array.from(m),
            audioRoles: null,
            forced: false,
            videoId: null,
            audioId: null,
            audioGroupId: h,
            channelsCount: null,
            audioSamplingRate: null,
            spatialAudio: false,
            tilesLayout: null,
            audioBandwidth: null,
            videoBandwidth: null,
            originalVideoId: null,
            originalAudioId: null,
            originalTextId: null,
            originalImageId: null,
            accessibilityPurpose: null,
            originalLanguage: null
          };
          if (c) {
            a.videoId = c.id;
            a.originalVideoId = c.originalId;
            a.width = c.width || null;
            a.height = c.height || null;
            a.frameRate = c.frameRate || null;
            a.pixelAspectRatio = c.pixelAspectRatio || null;
            a.videoBandwidth = c.bandwidth || null;
            a.hdr = c.hdr || null;
            a.colorGamut = c.colorGamut || null;
            a.videoLayout = c.videoLayout || null;
            if (d2 = c.dependencyStream) a.width = d2.width || a.width, a.height = d2.height || a.height, a.videoCodec = d2.codecs || a.videoCodec;
            if (g.includes(",")) {
              a.channelsCount = c.channelsCount;
              a.audioSamplingRate = c.audioSamplingRate;
              a.spatialAudio = c.spatialAudio;
              a.originalLanguage = c.originalLanguage;
              a.audioMimeType = e;
              c = g.split(",");
              try {
                a.videoCodec = qc("video", c), a.audioCodec = qc("audio", c);
              } catch (r2) {
              }
            }
          }
          b && (a.audioId = b.id, a.originalAudioId = b.originalId, a.channelsCount = b.channelsCount, a.audioSamplingRate = b.audioSamplingRate, a.audioBandwidth = b.bandwidth || null, a.spatialAudio = b.spatialAudio, a.label = b.label, a.audioRoles = b.roles, a.accessibilityPurpose = b.accessibilityPurpose, a.originalLanguage = b.originalLanguage, b = b.dependencyStream) && (a.audioCodec = b.codecs || a.audioCodec);
          b = [];
          a.videoCodec && b.push(a.videoCodec);
          a.audioCodec && b.push(a.audioCodec);
          a.codecs = b.join(", ");
          return a;
        }
        function dg(a) {
          return {
            id: a.id,
            active: false,
            type: tc,
            bandwidth: a.bandwidth || 0,
            language: a.language,
            label: a.label,
            kind: a.kind || null,
            mimeType: a.mimeType,
            codecs: a.codecs || null,
            primary: a.primary,
            roles: a.roles,
            accessibilityPurpose: a.accessibilityPurpose,
            forced: a.forced,
            originalTextId: a.originalId,
            originalLanguage: a.originalLanguage
          };
        }
        function eg(a) {
          var b = a.width || null, c = a.height || null, d2 = null;
          a.segmentIndex && (d2 = fg(a.segmentIndex));
          var e = a.tilesLayout;
          d2 && (e = d2.tilesLayout || e);
          e && b != null && (b /= Number(e.split("x")[0]));
          e && c != null && (c /= Number(e.split("x")[1]));
          return {
            id: a.id,
            type: "image",
            bandwidth: a.bandwidth || 0,
            width: b,
            height: c,
            mimeType: a.mimeType,
            codecs: a.codecs || null,
            tilesLayout: e || null,
            originalImageId: a.originalId
          };
        }
        function gg(a) {
          a.__shaka_id || (a.__shaka_id = hg++);
          return a.__shaka_id;
        }
        function ig(a) {
          var b = {
            id: gg(a),
            active: a.mode != "disabled",
            type: tc,
            bandwidth: 0,
            language: zc(a.language || "und"),
            label: a.label,
            kind: a.kind,
            mimeType: null,
            codecs: null,
            primary: false,
            roles: [],
            accessibilityPurpose: null,
            forced: a.kind == "forced",
            originalTextId: a.id,
            originalLanguage: a.language
          };
          a.kind == "captions" && (b.mimeType = "unknown");
          a.kind == "subtitles" && (b.mimeType = "text/vtt");
          a.kind && (b.roles = [a.kind]);
          return b;
        }
        function jg(a, b) {
          var c = a ? a.language : null;
          c = {
            id: gg(a || b),
            active: a ? a.enabled : b.selected,
            type: "variant",
            bandwidth: 0,
            language: zc(c || "und"),
            label: a ? a.label : null,
            kind: a ? a.kind : null,
            width: null,
            height: null,
            frameRate: null,
            pixelAspectRatio: null,
            hdr: null,
            colorGamut: null,
            videoLayout: null,
            mimeType: null,
            audioMimeType: null,
            videoMimeType: null,
            codecs: null,
            audioCodec: null,
            videoCodec: null,
            primary: a ? a.kind == "main" : false,
            roles: [],
            forced: false,
            audioRoles: null,
            videoId: null,
            audioId: null,
            audioGroupId: null,
            channelsCount: null,
            audioSamplingRate: null,
            spatialAudio: false,
            tilesLayout: null,
            audioBandwidth: null,
            videoBandwidth: null,
            originalVideoId: b ? b.id : null,
            originalAudioId: a ? a.id : null,
            originalTextId: null,
            originalImageId: null,
            accessibilityPurpose: null,
            originalLanguage: c
          };
          a && a.kind && (c.roles = [a.kind], c.audioRoles = [a.kind]);
          a && a.configuration && (a.configuration.codec && (c.audioCodec = a.configuration.codec, c.codecs = c.audioCodec), a.configuration.bitrate && (c.audioBandwidth = a.configuration.bitrate, c.bandwidth += c.audioBandwidth), a.configuration.sampleRate && (c.audioSamplingRate = a.configuration.sampleRate), a.configuration.numberOfChannels && (c.channelsCount = a.configuration.numberOfChannels));
          if (b && b.configuration && (b.configuration.codec && (c.videoCodec = b.configuration.codec, c.codecs = c.codecs ? c.codecs + ("," + c.videoCodec) : c.videoCodec), b.configuration.bitrate && (c.videoBandwidth = b.configuration.bitrate, c.bandwidth += c.videoBandwidth), b.configuration.framerate && (c.frameRate = b.configuration.framerate), b.configuration.width && (c.width = b.configuration.width), b.configuration.height && (c.height = b.configuration.height), b.configuration.colorSpace && b.configuration.colorSpace.transfer)) switch (b.configuration.colorSpace.transfer) {
            case "pq":
              c.hdr = "PQ";
              break;
            case "hlg":
              c.hdr = "HLG";
              break;
            case "bt709":
              c.hdr = "SDR";
          }
          return c;
        }
        function kg(a) {
          return a.allowedByApplication && a.allowedByKeySystem && a.disabledUntilTime == 0;
        }
        function lg(a) {
          return a.filter(function(b) {
            return kg(b);
          });
        }
        function mg(a, b, c, d2) {
          var e = a, f = a.filter(function(k2) {
            return k2.primary;
          });
          f.length && (e = f);
          var g = e.length ? e[0].language : "";
          e = e.filter(function(k2) {
            return k2.language == g;
          });
          if (b) {
            var h = Hc(zc(b), a.map(function(k2) {
              return k2.language;
            }));
            h && (e = a.filter(function(k2) {
              return zc(k2.language) == h;
            }));
          }
          e = e.filter(function(k2) {
            return k2.forced == d2;
          });
          if (c) {
            if (a = ng(e, c), a.length) return a;
          } else if (a = e.filter(function(k2) {
            return k2.roles.length == 0;
          }), a.length) return a;
          a = e.map(function(k2) {
            return k2.roles;
          }).reduce(Df, []);
          return a.length ? ng(e, a[0]) : e;
        }
        function ng(a, b) {
          return a.filter(function(c) {
            return c.roles.includes(b);
          });
        }
        function og(a) {
          var b = [];
          a.audio && b.push(a.audio);
          a.video && b.push(a.video);
          return b;
        }
        function pg(a, b) {
          b.length && (b = b.filter(function(c) {
            return kf(a.codecs) == kf(c.codecs);
          }).sort(function(c, d2) {
            return c.bandwidth && d2.bandwidth && c.bandwidth != d2.bandwidth ? c.bandwidth - d2.bandwidth : (c.width || 0) - (d2.width || 0);
          }), a.trickModeVideo = b[0], b.length > 1 && (b = b.find(function(c) {
            return a.width == c.width && a.height == c.height;
          }))) && (a.trickModeVideo = b);
        }
        function Tf(a) {
          return a.type == "audio" ? "type=audio codecs=" + a.codecs + " bandwidth=" + a.bandwidth + " channelsCount=" + a.channelsCount + " audioSamplingRate=" + a.audioSamplingRate : a.type == "video" ? "type=video codecs=" + a.codecs + " bandwidth=" + a.bandwidth + " frameRate=" + a.frameRate + " width=" + a.width + " height=" + a.height : "unexpected stream type";
        }
        function qg(a, b, c) {
          if (c.autoShowText == 0) return false;
          if (c.autoShowText == 1) return true;
          var d2 = zc(c.preferredTextLanguage);
          b = zc(b.language);
          if (c.autoShowText == 2) return yc(b, d2);
          if (c.autoShowText == 3) {
            if (!a) return false;
            a = zc(a.language);
            return yc(b, d2) && !yc(a, b);
          }
          bb("Invalid autoShowText setting!");
          return false;
        }
        function rg(a) {
          var b = {
            id: 0,
            language: "und",
            disabledUntilTime: 0,
            primary: false,
            audio: null,
            video: null,
            bandwidth: 100,
            allowedByApplication: true,
            allowedByKeySystem: true,
            decodingInfos: []
          };
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) {
            c = c.value;
            var d2 = {
              id: 0,
              originalId: null,
              groupId: null,
              createSegmentIndex: function() {
                return Promise.resolve();
              },
              segmentIndex: null,
              mimeType: c ? nf(c) : "",
              codecs: c ? of(c) : "",
              encrypted: true,
              drmInfos: [],
              keyIds: /* @__PURE__ */ new Set(),
              language: "und",
              originalLanguage: null,
              label: null,
              type: "video",
              primary: false,
              trickModeVideo: null,
              dependencyStream: null,
              emsgSchemeIdUris: null,
              roles: [],
              forced: false,
              channelsCount: null,
              audioSamplingRate: null,
              spatialAudio: false,
              closedCaptions: null,
              accessibilityPurpose: null,
              external: false,
              fastSwitching: false,
              fullMimeTypes: /* @__PURE__ */ new Set(),
              isAudioMuxedInVideo: false,
              baseOriginalId: null
            };
            d2.fullMimeTypes.add(ef(d2.mimeType, d2.codecs));
            c.startsWith("audio/") ? (d2.type = "audio", b.audio = d2) : b.video = d2;
          }
          return b;
        }
        S("shaka.util.StreamUtils", Hf);
        Hf.meetsRestrictions = Lf;
        var Vf = /* @__PURE__ */ new Map(), hg = 0, $f = (/* @__PURE__ */ new Map()).set("image/svg+xml", true).set("image/png", true).set("image/jpeg", true).set("image/jpg", true), ag = (/* @__PURE__ */ new Map()).set("image/webp", "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA").set("image/avif", "data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A=");
        function sg() {
          var a = this;
          this.H = null;
          this.l = false;
          this.u = new Pc();
          this.j = new Qc();
          navigator.connection && navigator.connection.addEventListener && this.j.o(navigator.connection, "change", function() {
            if (a.l && a.g.useNetworkInformation) {
              a.u = new Pc();
              a.g && a.u.configure(a.g.advanced);
              var b = a.chooseVariant();
              b && navigator.onLine && a.H(b, a.g.clearBufferSwitch, a.g.safeMarginSwitch);
            }
          });
          this.G = [];
          this.I = 1;
          this.J = false;
          this.h = this.m = this.g = this.A = null;
          this.C = new Cf(function() {
            if (a.l && (a.g.restrictToElementSize || a.g.restrictToScreenSize)) {
              var b = a.chooseVariant();
              b && a.H(b, a.g.clearBufferSwitch, a.g.safeMarginSwitch);
            }
          });
          this.D = window7;
          "documentPictureInPicture" in window7 && this.j.o(window7.documentPictureInPicture, "enter", function() {
            a.D = window7.documentPictureInPicture.window;
            a.C && a.C.La();
            a.j.qa(a.D, "pagehide", function() {
              a.D = window7;
              a.C && a.C.La();
            });
          });
          this.F = this.i = null;
        }
        p = sg.prototype;
        p.stop = function() {
          this.H = null;
          this.l = false;
          this.G = [];
          this.I = 1;
          this.m = this.A = null;
          this.h && (this.h.disconnect(), this.h = null);
          this.C.stop();
          this.F = this.i = null;
        };
        p.release = function() {
          this.j.release();
          this.C = null;
        };
        p.init = function(a) {
          this.H = a;
        };
        p.chooseVariant = function() {
          var a = Infinity, b = Infinity;
          if (this.g.restrictToScreenSize) {
            var c = this.g.ignoreDevicePixelRatio ? 1 : this.D.devicePixelRatio;
            a = this.D.screen.height * c;
            b = this.D.screen.width * c;
          }
          if (this.h && this.g.restrictToElementSize) {
            c = this.g.ignoreDevicePixelRatio ? 1 : this.D.devicePixelRatio;
            var d2 = this.m.clientHeight, e = this.m.clientWidth;
            this.i && document.pictureInPictureElement && document.pictureInPictureElement == this.m && (d2 = this.i.height, e = this.i.width);
            a = Math.min(a, d2 * c);
            b = Math.min(b, e * c);
          }
          c = this.G.filter(function(l) {
            return l && !(l.audio && l.audio.fastSwitching || l.video && l.video.fastSwitching);
          });
          c.length || (c = this.G);
          d2 = c;
          c.length != this.G.length && (d2 = this.G.filter(function(l) {
            return l && (l.audio && l.audio.fastSwitching || l.video && l.video.fastSwitching ? true : false);
          }));
          c = tg(this, this.g.restrictions, d2, Infinity, Infinity);
          if (a != Infinity || b != Infinity) {
            c = ug(c);
            c = t2(c);
            for (e = c.next(); !e.done; e = c.next()) if (e = e.value, e.height >= a && e.width >= b) {
              a = e.height;
              b = e.width;
              break;
            }
            c = tg(this, this.g.restrictions, d2, a, b);
          }
          a = this.getBandwidthEstimate();
          d2.length && !c.length && (c = tg(this, null, d2, Infinity, Infinity), c = [c[0]]);
          b = c[0] || null;
          for (d2 = 0; d2 < c.length; d2++) {
            e = c[d2];
            for (var f = isNaN(this.I) ? 1 : Math.abs(this.I), g = f * e.bandwidth / this.g.bandwidthDowngradeTarget, h = {
              bandwidth: Infinity
            }, k2 = d2 + 1; k2 < c.length; k2++) if (e.bandwidth != c[k2].bandwidth) {
              h = c[k2];
              break;
            }
            f = f * h.bandwidth / this.g.bandwidthUpgradeTarget;
            a >= g && a <= f && (b.bandwidth != e.bandwidth || b.bandwidth == e.bandwidth && b.video && e.video && (b.video.width < e.video.width || b.video.height < e.video.height)) && (b = e);
          }
          this.A = Date.now();
          return b;
        };
        p.enable = function() {
          this.l = true;
        };
        p.disable = function() {
          this.l = false;
        };
        p.segmentDownloaded = function(a, b, c, d2) {
          var e = a;
          this.g.removeLatencyFromFirstPacketTime && d2 && d2.packetNumber === 1 && d2.timeToFirstByte && (e = a - d2.timeToFirstByte);
          e >= this.g.cacheLoadThreshold && this.u.sample(e, b);
          c && this.A != null && this.l && vg(this);
        };
        p.trySuggestStreams = function() {
          this.A != null && this.l && vg(this);
        };
        p.getBandwidthEstimate = function() {
          var a = this.g.defaultBandwidthEstimate;
          navigator.connection && navigator.connection.downlink && this.g.useNetworkInformation && (a = navigator.connection.downlink * 1e6);
          if (navigator.connection && navigator.connection.downlink && this.g.useNetworkInformation && this.g.preferNetworkInformationBandwidth) return a;
          a = this.u.getBandwidthEstimate(a);
          return this.F ? this.F.getBandwidthEstimate(a) : a;
        };
        p.setVariants = function(a) {
          this.G = a;
        };
        p.playbackRateChanged = function(a) {
          this.I = a;
        };
        p.setMediaElement = function(a) {
          function b() {
            c.C.Y(wg);
          }
          var c = this;
          this.m = a;
          this.h && (this.h.disconnect(), this.h = null);
          this.m && "ResizeObserver" in window7 && (this.h = new ResizeObserver(b), this.h.observe(this.m));
          this.j.o(a, "enterpictureinpicture", function(d2) {
            d2.pictureInPictureWindow && (c.i = d2.pictureInPictureWindow, c.j.o(c.i, "resize", b));
          });
          this.j.o(a, "leavepictureinpicture", function() {
            c.i && c.j.Ea(c.i, "resize", b);
            c.i = null;
          });
        };
        p.setCmsdManager = function(a) {
          this.F = a;
        };
        p.configure = function(a) {
          this.g = a;
          this.u && this.g && this.u.configure(this.g.advanced);
        };
        function vg(a) {
          if (!a.J) {
            var b = a.u;
            if (!(b.g >= b.i)) return;
            a.J = true;
            a.A -= (a.g.switchInterval - a.g.minTimeToSwitch) * 1e3;
          }
          Date.now() - a.A < a.g.switchInterval * 1e3 || (b = a.chooseVariant(), a.getBandwidthEstimate(), b && a.H(b, a.g.clearBufferSwitch, a.g.safeMarginSwitch));
        }
        function tg(a, b, c, d2, e) {
          if (a.F) {
            var f = a.F.Yi();
            f && (c = c.filter(function(g) {
              return g.bandwidth && f ? g.bandwidth <= f : true;
            }));
          }
          b && (c = c.filter(function(g) {
            return Lf(g, b, {
              width: e,
              height: d2
            });
          }));
          return c.sort(function(g, h) {
            return g.bandwidth - h.bandwidth;
          });
        }
        function ug(a) {
          var b = [];
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) (c = c.value.video) && c.height && c.width && b.push({
            height: c.height,
            width: c.width
          });
          return b.sort(function(d2, e) {
            return d2.width - e.width;
          });
        }
        S("shaka.abr.SimpleAbrManager", sg);
        sg.prototype.configure = sg.prototype.configure;
        sg.prototype.setCmsdManager = sg.prototype.setCmsdManager;
        sg.prototype.setMediaElement = sg.prototype.setMediaElement;
        sg.prototype.playbackRateChanged = sg.prototype.playbackRateChanged;
        sg.prototype.setVariants = sg.prototype.setVariants;
        sg.prototype.getBandwidthEstimate = sg.prototype.getBandwidthEstimate;
        sg.prototype.trySuggestStreams = sg.prototype.trySuggestStreams;
        sg.prototype.segmentDownloaded = sg.prototype.segmentDownloaded;
        sg.prototype.disable = sg.prototype.disable;
        sg.prototype.enable = sg.prototype.enable;
        sg.prototype.chooseVariant = sg.prototype.chooseVariant;
        sg.prototype.init = sg.prototype.init;
        sg.prototype.release = sg.prototype.release;
        sg.prototype.stop = sg.prototype.stop;
        var wg = 1;
        S("shaka.config.CrossBoundaryStrategy", {
          KEEP: "keep",
          RESET: "reset",
          RESET_TO_ENCRYPTED: "reset_to_encrypted",
          RESET_ON_ENCRYPTION_CHANGE: "RESET_ON_ENCRYPTION_CHANGE"
        });
        function yg(a, b) {
          if (a === b || !a.length || !b.length) return true;
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) {
            c = c.value;
            if (zg(c)) return true;
            for (var d2 = t2(b), e = d2.next(); !e.done; e = d2.next()) if (e = e.value, c.keySystem === e.keySystem || zg(e)) return true;
          }
          return false;
        }
        function Ag(a, b) {
          if (!a.length) return b;
          if (!b.length) return a;
          var c = [];
          a = t2(a);
          for (var d2 = a.next(); !d2.done; d2 = a.next()) {
            d2 = d2.value;
            for (var e = t2(b), f = e.next(); !f.done; f = e.next()) if (f = f.value, d2.keySystem == f.keySystem) {
              e = /* @__PURE__ */ new Map();
              for (var g = t2((d2.initData || []).concat(f.initData || [])), h = g.next(); !h.done; h = g.next()) h = h.value, e.set(h.keyId, h);
              e = Array.from(e.values());
              g = d2.keyIds && f.keyIds ? new Set([].concat(x(d2.keyIds), x(f.keyIds))) : d2.keyIds || f.keyIds;
              c.push({
                keySystem: d2.keySystem,
                licenseServerUri: d2.licenseServerUri || f.licenseServerUri,
                distinctiveIdentifierRequired: d2.distinctiveIdentifierRequired || f.distinctiveIdentifierRequired,
                persistentStateRequired: d2.persistentStateRequired || f.persistentStateRequired,
                videoRobustness: d2.videoRobustness || f.videoRobustness,
                audioRobustness: d2.audioRobustness || f.audioRobustness,
                serverCertificate: d2.serverCertificate || f.serverCertificate,
                serverCertificateUri: d2.serverCertificateUri || f.serverCertificateUri,
                initData: e,
                keyIds: g
              });
              break;
            } else zg(d2) ? c.push(d2) : zg(f) && c.push(f);
          }
          return c;
        }
        function Bg(a) {
          return a ? !!a.match(/^com\.(microsoft|chromecast)\.playready/) : false;
        }
        function Cg(a) {
          return a ? !!a.match(/^com\.apple\.fps/) : false;
        }
        function zg(a) {
          return (a = a.licenseServerUri) ? a.startsWith("data:application/json;base64,") : false;
        }
        var Dg = new Rb(function() {
          return Mb(new Uint8Array([0]));
        }), Ig = /* @__PURE__ */ new Map();
        function Jg(a, b) {
          var c = Kg();
          this.l = a.maxAttempts == null ? c.maxAttempts : a.maxAttempts;
          this.j = a.baseDelay == null ? c.baseDelay : a.baseDelay;
          this.u = a.fuzzFactor == null ? c.fuzzFactor : a.fuzzFactor;
          this.m = a.backoffFactor == null ? c.backoffFactor : a.backoffFactor;
          this.g = 0;
          this.h = this.j;
          if (this.i = b === void 0 ? false : b) this.g = 1;
        }
        function Lg(a) {
          var b, c;
          return P(function(d2) {
            if (d2.g == 1) {
              if (a.g >= a.l) if (a.i) a.g = 1, a.h = a.j;
              else throw new U(2, 7, 1010);
              b = a.g;
              a.g++;
              if (b == 0) return d2.return();
              c = a.h * (1 + (Math.random() * 2 - 1) * a.u);
              return G(d2, new Promise(function(e) {
                new Cf(e).Y(c / 1e3);
              }), 2);
            }
            a.h *= a.m;
            H(d2);
          });
        }
        function Kg() {
          return {
            maxAttempts: 2,
            baseDelay: 1e3,
            backoffFactor: 2,
            fuzzFactor: 0.5,
            timeout: 3e4,
            stallTimeout: 5e3,
            connectionTimeout: 1e4
          };
        }
        ;
        function Mg() {
          var a, b, c = new Promise(function(d2, e) {
            a = d2;
            b = e;
          });
          c.resolve = a;
          c.reject = b;
          return c;
        }
        Mg.prototype.resolve = function() {
        };
        Mg.prototype.reject = function() {
        };
        function Ng(a, b) {
          this.promise = a;
          this.i = b;
          this.g = null;
        }
        function Og(a) {
          return new Ng(Promise.reject(a), function() {
            return Promise.resolve();
          });
        }
        function Pg() {
          var a = Promise.reject(new U(2, 7, 7001));
          a.catch(function() {
          });
          return new Ng(a, function() {
            return Promise.resolve();
          });
        }
        function Qg(a) {
          return new Ng(Promise.resolve(a), function() {
            return Promise.resolve();
          });
        }
        function Rg(a) {
          return new Ng(a, function() {
            return a.catch(function() {
            });
          });
        }
        Ng.prototype.abort = function() {
          this.g || (this.g = this.i());
          return this.g;
        };
        function Sg(a) {
          return new Ng(Promise.all(a.map(function(b) {
            return b.promise;
          })), function() {
            return Promise.all(a.map(function(b) {
              return b.abort();
            }));
          });
        }
        Ng.prototype.finally = function(a) {
          this.promise.then(function() {
            return a(true);
          }, function() {
            return a(false);
          });
          return this;
        };
        Ng.prototype.cb = function(a, b) {
          function c(h) {
            return function(k2) {
              if (e.g && h) f.reject(g);
              else {
                var l = h ? a : b;
                l ? d2 = Tg(l, k2, f) : (h ? f.resolve : f.reject)(k2);
              }
            };
          }
          function d2() {
            f.reject(g);
            return e.abort();
          }
          var e = this, f = new Mg();
          f.catch(function() {
          });
          var g = new U(2, 7, 7001);
          this.promise.then(c(true), c(false));
          return new Ng(f, function() {
            return d2();
          });
        };
        function Tg(a, b, c) {
          try {
            var d2 = a(b);
            if (d2 && d2.promise && d2.abort) return c.resolve(d2.promise), function() {
              return d2.abort();
            };
            c.resolve(d2);
            return function() {
              return Promise.resolve(d2).then(function() {
              }, function() {
              });
            };
          } catch (e) {
            return c.reject(e), function() {
              return Promise.resolve();
            };
          }
        }
        ea.Object.defineProperties(Ng.prototype, {
          aborted: {
            configurable: true,
            enumerable: true,
            get: function() {
              return this.g !== null;
            }
          }
        });
        S("shaka.util.AbortableOperation", Ng);
        Ng.prototype.chain = Ng.prototype.cb;
        Ng.prototype["finally"] = Ng.prototype.finally;
        Ng.all = Sg;
        Ng.prototype.abort = Ng.prototype.abort;
        Ng.notAbortable = Rg;
        Ng.completed = Qg;
        Ng.aborted = Pg;
        Ng.failed = Og;
        function Ug() {
          this.g = [];
        }
        function Vg(a, b) {
          a.g.push(b.finally(function() {
            ud(a.g, b);
          }));
        }
        Ug.prototype.destroy = function() {
          for (var a = [], b = t2(this.g), c = b.next(); !c.done; c = b.next()) c = c.value, c.promise.catch(function() {
          }), a.push(c.abort());
          this.g = [];
          return Promise.all(a);
        };
        function Wg(a, b, c, d2, e, f, g) {
          lb.call(this);
          this.i = null;
          this.j = false;
          this.A = new Ug();
          this.g = /* @__PURE__ */ new Set();
          this.h = /* @__PURE__ */ new Set();
          this.u = a || null;
          this.m = b || null;
          this.C = c || null;
          this.D = d2 || null;
          this.F = e || null;
          this.H = f || null;
          this.G = g || null;
          this.l = /* @__PURE__ */ new Map();
        }
        ma(Wg, lb);
        p = Wg.prototype;
        p.configure = function(a) {
          this.i = a;
        };
        function Xg(a, b, c, d2) {
          d2 = d2 === void 0 ? false : d2;
          c = c || Yg;
          var e = Zg.get(a);
          (!e || c >= e.priority) && Zg.set(a, {
            priority: c,
            Uf: b,
            Wl: d2
          });
        }
        function $g(a, b) {
          for (var c = t2(a.g), d2 = c.next(); !d2.done; d2 = c.next()) b.g.add(d2.value);
          a = t2(a.h);
          for (c = a.next(); !c.done; c = a.next()) b.h.add(c.value);
        }
        p.Zl = function(a) {
          this.g.add(a);
        };
        p.zm = function(a) {
          this.g.delete(a);
        };
        p.qk = function() {
          this.g.clear();
        };
        p.$l = function(a) {
          this.h.add(a);
        };
        p.Am = function(a) {
          this.h.delete(a);
        };
        p.rk = function() {
          this.h.clear();
        };
        p.Ni = function() {
          this.l.clear();
        };
        function ah(a, b, c) {
          return {
            uris: a,
            method: "GET",
            body: null,
            headers: {},
            allowCrossSiteCredentials: false,
            retryParameters: b,
            licenseRequestType: null,
            sessionId: null,
            drmInfo: null,
            initData: null,
            initDataType: null,
            streamDataCallback: c === void 0 ? null : c
          };
        }
        p.destroy = function() {
          this.j = true;
          this.g.clear();
          this.h.clear();
          this.l.clear();
          lb.prototype.release.call(this);
          return this.A.destroy();
        };
        p.request = function(a, b, c) {
          var d2 = this, e = new bh();
          if (this.j) {
            var f = Promise.reject(new U(2, 7, 7001));
            f.catch(function() {
            });
            return new ch(f, function() {
              return Promise.resolve();
            }, e);
          }
          b.method = b.method || "GET";
          b.headers = b.headers || {};
          b.retryParameters = b.retryParameters ? Hd(b.retryParameters) : Kg();
          b.uris = Hd(b.uris);
          f = dh(this, a, b, c);
          var g = f.cb(function() {
            return eh(d2, a, b, c, new Jg(b.retryParameters, false), 0, null, e);
          }), h = g.cb(function(q) {
            return fh(d2, a, q, c);
          }), k2 = Date.now(), l = 0;
          f.promise.then(function() {
            l = Date.now() - k2;
          }, function() {
          });
          var m = 0;
          g.promise.then(function() {
            m = Date.now();
          }, function() {
          });
          var n = h.cb(function(q) {
            var r2 = Date.now() - m, u = q.response;
            u.timeMs += l;
            u.timeMs += r2;
            q.zl || !d2.u || u.fromCache || b.method == "HEAD" || a != gh || d2.u(u.timeMs, u.data.byteLength, hh(c), b, c);
            d2.G && d2.G(a, u, c);
            return u;
          }, function(q) {
            q && (q.severity = 2);
            throw q;
          });
          f = new ch(n.promise, function() {
            return n.abort();
          }, e);
          Vg(this.A, f);
          return f;
        };
        function dh(a, b, c, d2) {
          function e(h) {
            f = f.cb(function() {
              c.body && (c.body = Mb(c.body));
              return h(b, c, d2);
            });
          }
          var f = Qg(void 0);
          a.F && e(a.F);
          a = t2(a.g);
          for (var g = a.next(); !g.done; g = a.next()) e(g.value);
          return f.cb(void 0, function(h) {
            if (h instanceof U && h.code == 7001) throw h;
            throw new U(2, 1, 1006, h);
          });
        }
        function eh(a, b, c, d2, e, f, g, h) {
          a.i.forceHTTP && (c.uris[f] = c.uris[f].replace("https://", "http://"));
          a.i.forceHTTPS && (c.uris[f] = c.uris[f].replace("http://", "https://"));
          f > 0 && a.H && a.H(b, d2, c.uris[f], c.uris[f - 1]);
          var k2 = new rb(c.uris[f]), l = k2.lc, m = false;
          l || (l = location.protocol, l = l.slice(0, -1), sb(k2, l), c.uris[f] = k2.toString());
          l = l.toLowerCase();
          var n = (l = Zg.get(l)) ? l.Uf : null;
          if (!n) return Og(new U(2, 1, 1e3, k2));
          var q = l.Wl;
          (k2 = a.l.get(k2.Ib)) && (c.headers["common-access-token"] = k2);
          var r2 = null, u = null, w = false, v = false, y;
          return Rg(Lg(e)).cb(function() {
            if (a.j) return Pg();
            y = Date.now();
            var z = 0;
            c.requestStartTime = Date.now();
            var A = n(c.uris[f], c, b, function(F, B, E) {
              r2 && r2.stop();
              u && u.Y(D / 1e3);
              a.u && b == gh && (z++, c.packetNumber = z, a.u(F, B, hh(d2), c, d2), m = true, h.g = E);
            }, function(F) {
              v = true;
              c.timeToFirstByte = Date.now() - c.requestStartTime;
              a.m && a.m(F, c, b);
            }, {
              minBytesForProgressEvents: a.i.minBytesForProgressEvents
            });
            if (!q) return A;
            var C = c.retryParameters.connectionTimeout;
            C && (r2 = new Cf(function() {
              w = true;
              A.abort();
            }), r2.Y(C / 1e3));
            var D = c.retryParameters.stallTimeout;
            D && (u = new Cf(function() {
              w = true;
              A.abort();
            }));
            return A;
          }).cb(function(z) {
            r2 && r2.stop();
            u && u.stop();
            z.timeMs == void 0 && (z.timeMs = Date.now() - y);
            var A = z.headers["common-access-token"];
            if (A) {
              var C = new rb(z.uri);
              a.l.set(C.Ib, A);
            }
            A = {
              response: z,
              zl: m
            };
            !v && a.m && a.m(z.headers, c, b);
            a.C && a.C(c, z);
            return A;
          }, function(z) {
            r2 && r2.stop();
            u && u.stop();
            if (a.D) {
              var A = null, C = 0;
              z instanceof U && (A = z, z.code == 1001 && (C = z.data[1]));
              a.D(c, A, C, w);
            }
            if (a.j) return Pg();
            w && (z = new U(1, 1, 1003, c.uris[f], b));
            if (z instanceof U) {
              if (z.code == 7001) throw z;
              if (z.code == 1010) throw g;
              if (z.severity == 1) {
                A = (/* @__PURE__ */ new Map()).set("error", z);
                A = new T("retry", A);
                A.cancelable = true;
                a.dispatchEvent(A);
                if (A.defaultPrevented) throw z;
                f = (f + 1) % c.uris.length;
                return eh(a, b, c, d2, e, f, z, h);
              }
            }
            throw z;
          });
        }
        function fh(a, b, c, d2) {
          var e = Qg(void 0);
          a = t2(a.h);
          for (var f = a.next(), g = {}; !f.done; g = {
            Bj: void 0
          }, f = a.next()) g.Bj = f.value, e = e.cb(/* @__PURE__ */ function(h) {
            return function() {
              var k2 = c.response;
              k2.data && (k2.data = Mb(k2.data));
              return (0, h.Bj)(b, k2, d2);
            };
          }(g));
          return e.cb(function() {
            return c;
          }, function(h) {
            var k2 = 2;
            if (h instanceof U) {
              if (h.code == 7001) throw h;
              k2 = h.severity;
            }
            throw new U(k2, 1, 1007, h);
          });
        }
        function hh(a) {
          if (a) {
            var b = a.segment;
            a = a.stream;
            if (b && a && a.fastSwitching && b.u) return false;
          }
          return true;
        }
        S("shaka.net.NetworkingEngine", Wg);
        Wg.prototype.request = Wg.prototype.request;
        Wg.prototype.destroy = Wg.prototype.destroy;
        Wg.makeRequest = ah;
        Wg.defaultRetryParameters = function() {
          return Kg();
        };
        Wg.prototype.clearCommonAccessTokenMap = Wg.prototype.Ni;
        Wg.prototype.clearAllResponseFilters = Wg.prototype.rk;
        Wg.prototype.unregisterResponseFilter = Wg.prototype.Am;
        Wg.prototype.registerResponseFilter = Wg.prototype.$l;
        Wg.prototype.clearAllRequestFilters = Wg.prototype.qk;
        Wg.prototype.unregisterRequestFilter = Wg.prototype.zm;
        Wg.prototype.registerRequestFilter = Wg.prototype.Zl;
        Wg.unregisterScheme = function(a) {
          Zg.delete(a);
        };
        Wg.registerScheme = Xg;
        Wg.prototype.configure = Wg.prototype.configure;
        function bh() {
          this.g = 0;
        }
        Wg.NumBytesRemainingClass = bh;
        function ch(a, b, c) {
          Ng.call(this, a, b);
          this.h = c;
        }
        ma(ch, Ng);
        Wg.PendingRequest = ch;
        var gh = 1;
        Wg.RequestType = {
          MANIFEST: 0,
          SEGMENT: gh,
          LICENSE: 2,
          APP: 3,
          TIMING: 4,
          SERVER_CERTIFICATE: 5,
          KEY: 6,
          ADS: 7,
          CONTENT_STEERING: 8
        };
        Wg.AdvancedRequestType = {
          INIT_SEGMENT: 0,
          MEDIA_SEGMENT: 1,
          MEDIA_PLAYLIST: 2,
          MASTER_PLAYLIST: 3,
          MPD: 4,
          MSS: 5,
          MPD_PATCH: 6,
          MEDIATAILOR_SESSION_INFO: 7,
          MEDIATAILOR_TRACKING_INFO: 8,
          MEDIATAILOR_STATIC_RESOURCE: 9,
          MEDIATAILOR_TRACKING_EVENT: 10,
          INTERSTITIAL_ASSET_LIST: 11,
          INTERSTITIAL_AD_URL: 12
        };
        var Yg = 3;
        Wg.PluginPriority = {
          FALLBACK: 1,
          PREFERRED: 2,
          APPLICATION: Yg
        };
        var Zg = /* @__PURE__ */ new Map();
        function ih(a) {
          this.g = false;
          this.h = new Mg();
          this.i = a;
        }
        ih.prototype.destroy = function() {
          var a = this;
          if (this.g) return this.h;
          this.g = true;
          return this.i().then(function() {
            a.h.resolve();
          }, function() {
            a.h.resolve();
          });
        };
        function jh(a, b) {
          if (a.g) {
            if (b instanceof U && b.code == 7003) throw b;
            throw new U(2, 7, 7003, b);
          }
        }
        ;
        function kh(a) {
          for (var b = /* @__PURE__ */ new Map(), c = t2(Object.keys(a)), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, b.set(d2, a[d2]);
          return b;
        }
        function lh(a) {
          var b = {};
          a.forEach(function(c, d2) {
            b[d2] = c;
          });
          return b;
        }
        ;
        function mh(a, b) {
          this.h = Pb(a);
          this.i = b == nh;
          this.g = 0;
        }
        p = mh.prototype;
        p.Pa = function() {
          return this.g < this.h.byteLength;
        };
        p.Ua = function() {
          return this.g;
        };
        p.getLength = function() {
          return this.h.byteLength;
        };
        p.ba = function() {
          try {
            var a = this.h.getUint8(this.g);
            this.g += 1;
            return a;
          } catch (b) {
            throw oh();
          }
        };
        p.Ha = function() {
          try {
            var a = this.h.getUint16(this.g, this.i);
            this.g += 2;
            return a;
          } catch (b) {
            throw oh();
          }
        };
        p.X = function() {
          try {
            var a = this.h.getUint32(this.g, this.i);
            this.g += 4;
            return a;
          } catch (b) {
            throw oh();
          }
        };
        p.Sh = function() {
          try {
            var a = this.h.getInt32(this.g, this.i);
            this.g += 4;
            return a;
          } catch (b) {
            throw oh();
          }
        };
        p.Qd = function() {
          try {
            if (this.i) {
              var a = this.h.getUint32(this.g, true);
              var b = this.h.getUint32(this.g + 4, true);
            } else b = this.h.getUint32(this.g, false), a = this.h.getUint32(this.g + 4, false);
          } catch (c) {
            throw oh();
          }
          if (b > 2097151) throw new U(2, 3, 3001);
          this.g += 8;
          return b * 4294967296 + a;
        };
        p.$b = function(a) {
          if (this.g + a > this.h.byteLength) throw oh();
          var b = Lb(this.h, this.g, a);
          this.g += a;
          return b;
        };
        p.skip = function(a) {
          if (this.g + a > this.h.byteLength) throw oh();
          this.g += a;
        };
        p.Cj = function(a) {
          if (this.g < a) throw oh();
          this.g -= a;
        };
        p.seek = function(a) {
          if (a < 0 || a > this.h.byteLength) throw oh();
          this.g = a;
        };
        p.nd = function() {
          for (var a = this.g; this.Pa() && this.h.getUint8(this.g) != 0; ) this.g += 1;
          a = Lb(this.h, a, this.g - a);
          this.g += 1;
          return Xb(a);
        };
        function oh() {
          return new U(2, 3, 3e3);
        }
        S("shaka.util.DataViewReader", mh);
        mh.prototype.readTerminatedString = mh.prototype.nd;
        mh.prototype.seek = mh.prototype.seek;
        mh.prototype.rewind = mh.prototype.Cj;
        mh.prototype.skip = mh.prototype.skip;
        mh.prototype.readBytes = mh.prototype.$b;
        mh.prototype.readUint64 = mh.prototype.Qd;
        mh.prototype.readInt32 = mh.prototype.Sh;
        mh.prototype.readUint32 = mh.prototype.X;
        mh.prototype.readUint16 = mh.prototype.Ha;
        mh.prototype.readUint8 = mh.prototype.ba;
        mh.prototype.getLength = mh.prototype.getLength;
        mh.prototype.getPosition = mh.prototype.Ua;
        mh.prototype.hasMoreData = mh.prototype.Pa;
        var nh = 1;
        mh.Endianness = {
          BIG_ENDIAN: 0,
          LITTLE_ENDIAN: nh
        };
        function ph() {
          this.i = /* @__PURE__ */ new Map();
          this.h = /* @__PURE__ */ new Map();
          this.g = false;
        }
        p = ph.prototype;
        p.box = function(a, b) {
          a = qh(a);
          this.i.set(a, rh);
          this.h.set(a, b);
          return this;
        };
        p.W = function(a, b) {
          a = qh(a);
          this.i.set(a, sh);
          this.h.set(a, b);
          return this;
        };
        p.stop = function() {
          this.g = true;
        };
        p.parse = function(a, b, c) {
          a = new mh(a, 0);
          for (this.g = false; a.Pa() && !this.g; ) this.Md(0, a, b, c);
        };
        p.Md = function(a, b, c, d2) {
          var e = b.Ua();
          if (d2 && e + 8 > b.getLength()) this.g = true;
          else {
            var f = b.X(), g = b.X(), h = th(g), k2 = false;
            switch (f) {
              case 0:
                f = b.getLength() - e;
                break;
              case 1:
                if (d2 && b.Ua() + 8 > b.getLength()) {
                  this.g = true;
                  return;
                }
                f = b.Qd();
                k2 = true;
            }
            var l = this.h.get(g);
            if (l) {
              var m = null, n = null;
              if (this.i.get(g) == sh) {
                if (d2 && b.Ua() + 4 > b.getLength()) {
                  this.g = true;
                  return;
                }
                n = b.X();
                m = n >>> 24;
                n &= 16777215;
              }
              g = e + f;
              c && g > b.getLength() && (g = b.getLength());
              d2 && g > b.getLength() ? this.g = true : (g -= b.Ua(), b = g > 0 ? b.$b(g) : new Uint8Array(0), b = new mh(b, 0), l({
                name: h,
                parser: this,
                partialOkay: c || false,
                stopOnPartial: d2 || false,
                version: m,
                flags: n,
                reader: b,
                size: f,
                start: e + a,
                has64BitSize: k2
              }));
            } else b.skip(Math.min(e + f - b.Ua(), b.getLength() - b.Ua()));
          }
        };
        function uh(a) {
          for (var b = vh(a); a.reader.Pa() && !a.parser.g; ) a.parser.Md(a.start + b, a.reader, a.partialOkay, a.stopOnPartial);
        }
        function wh(a) {
          for (var b = vh(a), c = a.reader.X(), d2 = 0; d2 < c && (a.parser.Md(a.start + b, a.reader, a.partialOkay, a.stopOnPartial), !a.parser.g); d2++) ;
        }
        function xh(a) {
          var b = vh(a);
          for (a.reader.skip(78); a.reader.Pa() && !a.parser.g; ) a.parser.Md(a.start + b, a.reader, a.partialOkay, a.stopOnPartial);
        }
        function yh(a) {
          var b = vh(a);
          a.reader.skip(8);
          var c = a.reader.Ha();
          a.reader.skip(6);
          c == 2 ? a.reader.skip(48) : a.reader.skip(12);
          for (c == 1 && a.reader.skip(16); a.reader.Pa() && !a.parser.g; ) a.parser.Md(a.start + b, a.reader, a.partialOkay, a.stopOnPartial);
        }
        function zh(a) {
          return function(b) {
            a(b.reader.$b(b.reader.getLength() - b.reader.Ua()));
          };
        }
        function qh(a) {
          var b = 0;
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) b = b << 8 | c.value.charCodeAt(0);
          return b;
        }
        function th(a) {
          return String.fromCharCode(a >> 24 & 255, a >> 16 & 255, a >> 8 & 255, a & 255);
        }
        function vh(a) {
          return 8 + (a.has64BitSize ? 8 : 0) + (a.flags != null ? 4 : 0);
        }
        S("shaka.util.Mp4Parser", ph);
        ph.headerSize = vh;
        ph.typeToString = th;
        ph.allData = zh;
        ph.audioSampleEntry = yh;
        ph.visualSampleEntry = xh;
        ph.sampleDescription = wh;
        ph.children = uh;
        ph.prototype.parseNext = ph.prototype.Md;
        ph.prototype.parse = ph.prototype.parse;
        ph.prototype.stop = ph.prototype.stop;
        ph.prototype.fullBox = ph.prototype.W;
        ph.prototype.box = ph.prototype.box;
        var rh = 0, sh = 1;
        function Ah(a) {
          var b = this;
          this.g = [];
          this.h = [];
          this.data = [];
          new ph().box("moov", uh).box("moof", uh).W("pssh", function(c) {
            if (!(c.version > 1)) {
              var d2 = Lb(c.reader.h, -12, c.size);
              b.data.push(d2);
              b.g.push(lc(c.reader.$b(16)));
              if (c.version > 0) {
                d2 = c.reader.X();
                for (var e = 0; e < d2; e++) {
                  var f = lc(c.reader.$b(16));
                  b.h.push(f);
                }
              }
            }
          }).parse(a);
        }
        function Bh(a, b, c, d2) {
          var e = a.length, f = 12 + b.length + 4 + e;
          d2 > 0 && (f += 4 + 16 * c.size);
          var g = new Uint8Array(f), h = Pb(g), k2 = 0;
          h.setUint32(k2, f);
          k2 += 4;
          h.setUint32(k2, 1886614376);
          k2 += 4;
          d2 < 1 ? h.setUint32(k2, 0) : h.setUint32(k2, 16777216);
          k2 += 4;
          g.set(b, k2);
          k2 += b.length;
          if (d2 > 0) for (h.setUint32(k2, c.size), k2 += 4, b = t2(c), c = b.next(); !c.done; c = b.next()) c = kc(c.value), g.set(c, k2), k2 += c.length;
          h.setUint32(k2, e);
          g.set(a, k2 + 4);
          return g;
        }
        ;
        function Ch(a) {
          var b = this;
          this.F = a;
          this.j = this.C = null;
          this.ea = this.R = false;
          this.I = 0;
          this.g = null;
          this.u = new Qc();
          this.i = /* @__PURE__ */ new Map();
          this.V = [];
          this.D = /* @__PURE__ */ new Map();
          this.J = false;
          this.m = new Mg();
          this.h = null;
          this.A = function(c) {
            c.severity == 2 && b.m.reject(c);
            a.onError(c);
          };
          this.$ = /* @__PURE__ */ new Map();
          this.aa = /* @__PURE__ */ new Map();
          this.K = new Cf(function() {
            return Dh(b);
          });
          this.P = false;
          this.M = [];
          this.Z = false;
          this.G = new Cf(function() {
            Eh(b);
          });
          this.m.catch(function() {
          });
          this.l = new ih(function() {
            return Fh(b);
          });
          this.O = false;
          this.L = this.H = null;
          this.S = function() {
            return false;
          };
        }
        p = Ch.prototype;
        p.destroy = function() {
          return this.l.destroy();
        };
        function Fh(a) {
          return P(function(b) {
            switch (b.g) {
              case 1:
                return a.u.release(), a.u = null, a.m.reject(), a.G.stop(), a.G = null, a.K.stop(), a.K = null, G(b, Gh(a), 2);
              case 2:
                if (!a.j) {
                  b.B(3);
                  break;
                }
                sa(b, 4);
                return G(b, a.j.setMediaKeys(null), 6);
              case 6:
                ua(b, 5);
                break;
              case 4:
                va(b);
              case 5:
                a.j = null;
              case 3:
                a.g = null, a.C = null, a.D = /* @__PURE__ */ new Map(), a.h = null, a.A = function() {
                }, a.F = null, a.O = false, a.H = null, H(b);
            }
          });
        }
        p.configure = function(a, b) {
          this.h = a;
          b && (this.S = b);
          this.G && this.R && this.g && this.G.za(this.h.updateExpirationTime);
        };
        function Hh(a, b, c) {
          a.ea = true;
          a.D = /* @__PURE__ */ new Map();
          a.P = c;
          return Ih(a, b, false);
        }
        function Jh(a, b, c, d2) {
          d2 = d2 === void 0 ? true : d2;
          a.D = /* @__PURE__ */ new Map();
          c = t2(c);
          for (var e = c.next(); !e.done; e = c.next()) a.D.set(e.value, {
            initData: null,
            initDataType: null
          });
          c = t2(a.h.persistentSessionsMetadata);
          for (e = c.next(); !e.done; e = c.next()) e = e.value, a.D.set(e.sessionId, {
            initData: e.initData,
            initDataType: e.initDataType
          });
          a.P = a.D.size > 0;
          return Ih(a, b, d2);
        }
        function Kh(a, b, c, d2, e, f) {
          var g, h, k2, l, m;
          return P(function(n) {
            if (n.g == 1) return g = [], f.length && g.push(f[0].contentType), e.length && g.push(e[0].contentType), h = function(q) {
              q = oc(b, q, null);
              q.licenseServerUri = c;
              q.serverCertificate = d2;
              q.persistentStateRequired = true;
              q.sessionType = "persistent-license";
              return q;
            }, k2 = rg(g), k2.video && (l = h(f[0].encryptionScheme || ""), k2.video.drmInfos.push(l)), k2.audio && (m = h(e[0].encryptionScheme || ""), k2.audio.drmInfos.push(m)), G(n, Rf([k2], true, a.O, []), 2);
            jh(a.l);
            return n.return(Lh(a, [k2]));
          });
        }
        function Ih(a, b, c) {
          var d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C;
          return P(function(D) {
            if (D.g == 1) {
              Mh(a.h.clearKeys, b);
              d2 = b.some(function(F) {
                return F.video && F.video.drmInfos.length || F.audio && F.audio.drmInfos.length ? true : false;
              });
              e = kh(a.h.servers);
              f = kh(a.h.advanced || {});
              !d2 && c && Nh(b, e);
              g = /* @__PURE__ */ new WeakSet();
              h = t2(b);
              for (k2 = h.next(); !k2.done; k2 = h.next()) for (l = k2.value, m = Oh(l), n = t2(m), q = n.next(); !q.done; q = n.next()) r2 = q.value, g.has(r2) || (g.add(r2), Ph(r2, e, f, a.h.keySystemsMapping));
              u = function(F, B) {
                var E = [];
                F = t2(F);
                for (var I = F.next(); !I.done; I = F.next()) {
                  I = I.value;
                  var J = I[B] || f.has(I.keySystem) && f.get(I.keySystem)[B] || "", K;
                  if (K = J == "") K = (K = I.keySystem) ? !!K.match(/^com\.widevine\.alpha/) : false;
                  K && (B == "audioRobustness" ? J = [a.h.defaultAudioRobustnessForWidevine] : B == "videoRobustness" && (J = [a.h.defaultVideoRobustnessForWidevine]));
                  if (typeof J === "string") E.push(I);
                  else if (Array.isArray(J)) for (J.length === 0 && (J = [""]), J = t2(J), K = J.next(); !K.done; K = J.next()) {
                    var L = {};
                    E.push(Object.assign({}, I, (L[B] = K.value, L)));
                  }
                }
                return E;
              };
              w = /* @__PURE__ */ new WeakSet();
              v = t2(b);
              for (y = v.next(); !y.done; y = v.next()) z = y.value, z.video && !w.has(z.video) && (z.video.drmInfos = u(z.video.drmInfos, "videoRobustness"), z.video.drmInfos = u(z.video.drmInfos, "audioRobustness"), w.add(z.video)), z.audio && !w.has(z.audio) && (z.audio.drmInfos = u(z.audio.drmInfos, "videoRobustness"), z.audio.drmInfos = u(z.audio.drmInfos, "audioRobustness"), w.add(z.audio));
              return G(D, Rf(b, a.P, a.O, a.h.preferredKeySystems), 2);
            }
            jh(a.l);
            A = d2 || e.size > 0;
            if (!A) return a.R = true, D.return(Promise.resolve());
            C = Lh(a, b);
            return D.return(d2 ? C : C.catch(function() {
            }));
          });
        }
        function Qh(a) {
          var b;
          return P(function(c) {
            switch (c.g) {
              case 1:
                if (a.j.mediaKeys) return c.return();
                if (!a.H) {
                  c.B(2);
                  break;
                }
                return G(c, a.H, 3);
              case 3:
                return jh(a.l), c.return();
              case 2:
                return sa(c, 4), a.H = a.j.setMediaKeys(a.C), G(c, a.H, 6);
              case 6:
                ua(c, 5);
                break;
              case 4:
                b = va(c), a.A(new U(2, 6, 6003, b.message));
              case 5:
                jh(a.l), H(c);
            }
          });
        }
        function Rh(a, b) {
          return P(function(c) {
            if (c.g == 1) return G(c, Qh(a), 2);
            Sh(a, b.initDataType, Lb(b.initData));
            H(c);
          });
        }
        p.bc = function(a) {
          var b = this, c, d2;
          return P(function(e) {
            if (e.g == 1) {
              if (b.j === a) return e.return();
              if (!b.C) return b.u.qa(a, "encrypted", function() {
                b.A(new U(2, 6, 6010));
              }), e.return();
              b.j = a;
              b.u.qa(b.j, "play", function() {
                for (var f = t2(b.M), g = f.next(); !g.done; g = f.next()) Th(b, g.value);
                b.Z = true;
                b.M = [];
              });
              b.j.remote ? (b.u.o(b.j.remote, "connect", function() {
                return Gh(b);
              }), b.u.o(b.j.remote, "connecting", function() {
                return Gh(b);
              }), b.u.o(b.j.remote, "disconnect", function() {
                return Gh(b);
              })) : "webkitCurrentPlaybackTargetIsWireless" in b.j && b.u.o(b.j, "webkitcurrentplaybacktargetiswirelesschanged", function() {
                return Gh(b);
              });
              b.L = b.g ? b.g.initData.find(function(f) {
                return f.initData.length > 0;
              }) || null : null;
              c = b.g.keySystem;
              return (d2 = Sb().Kh(c)) || !(b.L || b.D.size || b.h.parseInbandPsshEnabled) ? (b.u.o(b.j, "encrypted", function(f) {
                return Rh(b, f);
              }), e.B(2)) : G(e, Qh(b), 2);
            }
            Uh(b).catch(function() {
            });
            H(e);
          });
        };
        function Vh(a) {
          var b, c, d2, e, f;
          return P(function(g) {
            switch (g.g) {
              case 1:
                if (!a.C || !a.g) return g.return();
                if (!a.g.serverCertificateUri || a.g.serverCertificate && a.g.serverCertificate.length) {
                  g.B(2);
                  break;
                }
                b = ah([a.g.serverCertificateUri], a.h.retryParameters);
                sa(g, 3);
                c = a.F.Bc.request(5, b, {
                  isPreload: a.S()
                });
                return G(g, c.promise, 5);
              case 5:
                d2 = g.h;
                a.g.serverCertificate = Lb(d2.data);
                ua(g, 4);
                break;
              case 3:
                throw e = va(g), new U(2, 6, 6017, e);
              case 4:
                if (a.l.g) return g.return();
              case 2:
                if (!a.g.serverCertificate || !a.g.serverCertificate.length) return g.return();
                sa(g, 6);
                return G(g, a.C.setServerCertificate(a.g.serverCertificate), 8);
              case 8:
                ua(g, 0);
                break;
              case 6:
                throw f = va(g), new U(2, 6, 6004, f.message);
            }
          });
        }
        function Wh(a, b) {
          var c, d2, e;
          return P(function(f) {
            if (f.g == 1) return G(f, Xh(a, b, {
              initData: null,
              initDataType: null
            }), 2);
            if (f.g != 3) {
              c = f.h;
              if (!c) return f.return();
              d2 = [];
              if (e = a.i.get(c)) e.Rb = new Mg(), d2.push(e.Rb);
              d2.push(c.remove());
              return G(f, Promise.all(d2), 3);
            }
            a.i.delete(c);
            H(f);
          });
        }
        function Uh(a) {
          var b, c, d2, e, f;
          return P(function(g) {
            if (g.g == 1) {
              if (!a.D.size) return g.B(2);
              a.D.forEach(function(h, k2) {
                Xh(a, k2, h);
              });
              return G(g, a.m, 3);
            }
            if (g.g != 2) {
              b = a.g && a.g.keyIds || /* @__PURE__ */ new Set([]);
              if (b.size > 0 && Yh(a)) return g.return(a.m);
              a.J = false;
              a.m = new Mg();
              a.m.catch(function() {
              });
            }
            c = (a.g ? a.g.initData : []) || [];
            d2 = t2(c);
            for (e = d2.next(); !e.done; e = d2.next()) f = e.value, Sh(a, f.initDataType, f.initData);
            Zh(a) && a.m.resolve();
            return g.return(a.m);
          });
        }
        function Sh(a, b, c) {
          if (c.length) {
            if (a.h.ignoreDuplicateInitData) {
              var d2 = a.i.values();
              d2 = t2(d2);
              for (var e = d2.next(); !e.done; e = d2.next()) if (Kb(c, e.value.initData)) return;
              var f = false;
              a.D.forEach(function(g) {
                !f && Kb(c, g.initData) && (f = true);
              });
              if (f) return;
            }
            a.J = true;
            a.i.size > 0 && Zh(a) && (a.m.resolve(), a.J = false, a.m = new Mg(), a.m.catch(function() {
            }));
            $h(a, b, c, a.g.sessionType);
          }
        }
        function bi(a) {
          a = a.i.keys();
          a = mb(a, function(b) {
            return b.sessionId;
          });
          return Array.from(a);
        }
        p.mh = function() {
          var a = this, b = this.i.keys();
          b = mb(b, function(c) {
            var d2 = a.i.get(c);
            return {
              sessionId: c.sessionId,
              sessionType: d2.type,
              initData: d2.initData,
              initDataType: d2.initDataType
            };
          });
          return Array.from(b);
        };
        p.ke = function() {
          var a = Infinity, b = this.i.keys();
          b = t2(b);
          for (var c = b.next(); !c.done; c = b.next()) c = c.value, isNaN(c.expiration) || (a = Math.min(a, c.expiration));
          return a;
        };
        function ci(a) {
          return a.I ? a.I : NaN;
        }
        p.tf = function() {
          return lh(this.aa);
        };
        function Lh(a, b) {
          var c, d2, e, f, g, h, k2;
          return P(function(l) {
            switch (l.g) {
              case 1:
                c = /* @__PURE__ */ new Map();
                d2 = di(a, b, c);
                if (!d2) {
                  if (!navigator.requestMediaKeySystemAccess) throw new U(2, 6, 6020);
                  throw new U(2, 6, 6001);
                }
                jh(a.l);
                sa(l, 2);
                d2.getConfiguration();
                var m = e = a.h.keySystemsMapping[d2.keySystem] || d2.keySystem, n = c.get(e), q = [], r2 = [], u = [], w = [], v = [], y = /* @__PURE__ */ new Set(), z = /* @__PURE__ */ new Set();
                ei(n, q, r2, w, u, v, y, z);
                var A = a.P ? "persistent-license" : "temporary";
                m = {
                  keySystem: m,
                  encryptionScheme: q[0],
                  licenseServerUri: r2[0],
                  distinctiveIdentifierRequired: n[0].distinctiveIdentifierRequired,
                  persistentStateRequired: n[0].persistentStateRequired,
                  sessionType: n[0].sessionType || A,
                  audioRobustness: n[0].audioRobustness || "",
                  videoRobustness: n[0].videoRobustness || "",
                  serverCertificate: w[0],
                  serverCertificateUri: u[0],
                  initData: v,
                  keyIds: y
                };
                z.size > 0 && (m.keySystemUris = z);
                n = t2(n);
                for (z = n.next(); !z.done; z = n.next()) z = z.value, z.distinctiveIdentifierRequired && (m.distinctiveIdentifierRequired = z.distinctiveIdentifierRequired), z.persistentStateRequired && (m.persistentStateRequired = z.persistentStateRequired);
                a.g = m;
                if (!a.g.licenseServerUri) throw new U(2, 6, 6012, a.g.keySystem);
                return G(l, d2.createMediaKeys(), 4);
              case 4:
                f = l.h;
                jh(a.l);
                a.C = f;
                if (!(a.h.minHdcpVersion != "" && "getStatusForPolicy" in a.C)) {
                  l.B(5);
                  break;
                }
                sa(l, 6);
                return G(l, a.C.getStatusForPolicy({
                  minHdcpVersion: a.h.minHdcpVersion
                }), 8);
              case 8:
                g = l.h;
                if (g != "usable") throw new U(2, 6, 6018);
                jh(a.l);
                ua(l, 5, 2);
                break;
              case 6:
                h = va(l, 2);
                if (h instanceof U) throw h;
                throw new U(2, 6, 6019, h.message);
              case 5:
                return a.R = true, a.G.za(a.h.updateExpirationTime), G(l, Vh(a), 9);
              case 9:
                jh(a.l);
                ua(l, 0);
                break;
              case 2:
                k2 = va(l);
                jh(a.l, k2);
                a.g = null;
                if (k2 instanceof U) throw k2;
                throw new U(2, 6, 6002, k2.message);
            }
          });
        }
        function di(a, b, c) {
          for (var d2 = t2(b), e = d2.next(); !e.done; e = d2.next()) {
            e = t2(Oh(e.value));
            for (var f = e.next(); !f.done; f = e.next()) f = f.value, c.has(f.keySystem) || c.set(f.keySystem, []), c.get(f.keySystem).push(f);
          }
          if (c.size == 1 && c.has("")) throw new U(2, 6, 6e3);
          d2 = a.h.preferredKeySystems;
          d2.length || (e = kh(a.h.servers), e.size == 1 && (d2 = Array.from(e.keys())));
          e = t2(d2);
          var g = e.next();
          for (f = {}; !g.done; f = {
            vj: void 0
          }, g = e.next()) {
            f.vj = g.value;
            g = t2(b);
            for (var h = g.next(); !h.done; h = g.next()) if (h = h.value.decodingInfos.find(/* @__PURE__ */ function(n) {
              return function(q) {
                return q.supported && q.keySystemAccess != null && q.keySystemAccess.keySystem == n.vj;
              };
            }(f))) return h.keySystemAccess;
          }
          e = t2([true, false]);
          for (f = e.next(); !f.done; f = e.next()) for (f = f.value, g = t2(b), h = g.next(); !h.done; h = g.next()) {
            h = t2(h.value.decodingInfos);
            for (var k2 = h.next(); !k2.done; k2 = h.next()) if (k2 = k2.value, k2.supported && k2.keySystemAccess) {
              var l = k2.keySystemAccess.keySystem;
              if (!d2.includes(l)) {
                var m = c.get(l);
                !m && a.h.keySystemsMapping[l] && (m = c.get(a.h.keySystemsMapping[l]));
                l = t2(m);
                for (m = l.next(); !m.done; m = l.next()) if (!!m.value.licenseServerUri == f) return k2.keySystemAccess;
              }
            }
          }
          return null;
        }
        function fi(a) {
          Zh(a) && a.m.resolve();
        }
        function gi(a, b) {
          new Cf(function() {
            b.loaded = true;
            fi(a);
          }).Y(hi);
        }
        function Xh(a, b, c) {
          var d2, e, f, g, h, k2, l;
          return P(function(m) {
            switch (m.g) {
              case 1:
                try {
                  d2 = a.C.createSession("persistent-license");
                } catch (n) {
                  return e = new U(2, 6, 6005, n.message), a.A(e), m.return(Promise.reject(e));
                }
                a.u.o(d2, "message", function(n) {
                  a.j && a.h.delayLicenseRequestUntilPlayed && a.j.paused && !a.Z ? a.M.push(n) : Th(a, n);
                });
                a.u.o(d2, "keystatuseschange", function(n) {
                  return ii(a, n);
                });
                f = {
                  initData: c.initData,
                  initDataType: c.initDataType,
                  loaded: false,
                  Nh: Infinity,
                  Rb: null,
                  type: "persistent-license"
                };
                a.i.set(d2, f);
                sa(m, 2);
                return G(m, d2.load(b), 4);
              case 4:
                return g = m.h, jh(a.l), g || (a.i.delete(d2), h = a.h.persistentSessionOnlinePlayback ? 1 : 2, a.A(new U(h, 6, 6013)), f.loaded = true), gi(a, f), fi(a), m.return(d2);
              case 2:
                k2 = va(m), jh(a.l, k2), a.i.delete(d2), l = a.h.persistentSessionOnlinePlayback ? 1 : 2, a.A(new U(l, 6, 6005, k2.message)), f.loaded = true, fi(a);
              case 3:
                return m.return(Promise.resolve());
            }
          });
        }
        function $h(a, b, c, d2) {
          try {
            var e = a.C.createSession(d2);
          } catch (f) {
            a.A(new U(2, 6, 6005, f.message));
            return;
          }
          a.u.o(e, "message", function(f) {
            a.j && a.h.delayLicenseRequestUntilPlayed && a.j.paused && !a.Z ? a.M.push(f) : Th(a, f);
          });
          a.u.o(e, "keystatuseschange", function(f) {
            return ii(a, f);
          });
          a.i.set(e, {
            initData: c,
            initDataType: b,
            loaded: false,
            Nh: Infinity,
            Rb: null,
            type: d2
          });
          try {
            c = a.h.initDataTransform(c, b, a.g);
          } catch (f) {
            b = f;
            f instanceof U || (b = new U(2, 6, 6016, f));
            a.A(b);
            return;
          }
          a.h.logLicenseExchange && ic(c);
          e.generateRequest(b, c).catch(function(f) {
            if (!a.l.g) {
              a.i.delete(e);
              var g = f.errorCode;
              if (g && g.systemCode) {
                var h = g.systemCode;
                h < 0 && (h += 4294967296);
                h = "0x" + h.toString(16);
              }
              a.A(new U(2, 6, 6006, f.message, f, h));
            }
          });
        }
        function ji(a) {
          return P(function(b) {
            return b.g == 1 ? a.J ? G(b, a.m, 3) : b.B(0) : G(b, Promise.all(a.V.map(function(c) {
              return c.promise;
            })), 0);
          });
        }
        function Th(a, b) {
          var c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v;
          P(function(y) {
            switch (y.g) {
              case 1:
                c = b.target;
                a.h.logLicenseExchange && ic(b.message);
                d2 = a.i.get(c);
                e = a.g.licenseServerUri;
                f = a.h.advanced[a.g.keySystem];
                b.messageType == "individualization-request" && f && f.individualizationServer && (e = f.individualizationServer);
                g = ah([e], a.h.retryParameters);
                g.body = b.message;
                g.method = "POST";
                g.licenseRequestType = b.messageType;
                g.sessionId = c.sessionId;
                g.drmInfo = a.g;
                d2 && (g.initData = d2.initData, g.initDataType = d2.initDataType);
                if (f && f.headers) for (h in f.headers) g.headers[h] = f.headers[h];
                if (a.g.keySystem === "org.w3.clearkey") {
                  var z = g, A = a.g;
                  try {
                    var C = $b(z.body);
                    if (C) {
                      var D = JSON.parse(C);
                      D.type || (D.type = A.sessionType, z.body = ac(JSON.stringify(D)));
                    }
                  } catch (F) {
                  }
                }
                if (Bg(a.g.keySystem)) if (z = Yb(g.body, true, true), z.includes("PlayReadyKeyMessage")) {
                  z = Ld(z, "PlayReadyKeyMessage");
                  A = Vd(z, "HttpHeader");
                  A = t2(A);
                  for (C = A.next(); !C.done; C = A.next()) D = C.value, C = Vd(D, "name")[0], D = Vd(D, "value")[0], g.headers[Td(C)] = Td(D);
                  z = Vd(z, "Challenge")[0];
                  g.body = jc(Td(z));
                } else g.headers["Content-Type"] = "text/xml; charset=utf-8";
                k2 = Date.now();
                sa(y, 2);
                m = a.F.Bc.request(2, g, {
                  isPreload: a.S()
                });
                a.V.push(m);
                return G(y, m.promise, 4);
              case 4:
                l = y.h;
                ud(a.V, m);
                ua(y, 3);
                break;
              case 2:
                n = va(y);
                if (a.l.g) return y.return();
                q = new U(2, 6, 6007, n);
                a.i.size == 1 ? (a.A(q), d2 && d2.Rb && d2.Rb.reject(q)) : (d2 && d2.Rb && d2.Rb.reject(q), a.i.delete(c), Zh(a) && (a.m.resolve(), a.K.Y(0.1)));
                return y.return();
              case 3:
                if (a.l.g) return y.return();
                a.I += (Date.now() - k2) / 1e3;
                a.h.logLicenseExchange && ic(l.data);
                sa(y, 5);
                return G(y, c.update(l.data), 7);
              case 7:
                ua(y, 6);
                break;
              case 5:
                return u = (r2 = va(y)) && r2.message || String(r2), w = new U(2, 6, 6008, u), a.A(w), d2 && d2.Rb && d2.Rb.reject(w), y.return();
              case 6:
                if (a.l.g) return y.return();
                v = new T("drmsessionupdate");
                a.F.onEvent(v);
                d2 && (d2.Rb && d2.Rb.resolve(), gi(a, d2));
                H(y);
            }
          });
        }
        function ii(a, b) {
          b = b.target;
          var c = a.i.get(b), d2 = false;
          b.keyStatuses.forEach(function(f, g) {
            if (typeof g == "string") {
              var h = g;
              g = f;
              f = h;
            }
            h = Sb();
            if (Bg(a.g.keySystem) && g.byteLength == 16 && h.Yh()) {
              h = Pb(g);
              var k2 = h.getUint32(0, true), l = h.getUint16(4, true), m = h.getUint16(6, true);
              h.setUint32(0, k2, false);
              h.setUint16(4, l, false);
              h.setUint16(6, m, false);
            }
            f != "status-pending" && (c.loaded = true);
            f == "expired" && (d2 = true);
            g = lc(g).slice(0, 32);
            a.$.set(g, f);
          });
          var e = b.expiration - Date.now();
          (e < 0 || d2 && e < 1e3) && c && !c.Rb && (a.i.delete(b), ki(b));
          Zh(a) && (a.m.resolve(), a.K.Y(li));
        }
        function Dh(a) {
          var b = a.$, c = a.aa;
          c.clear();
          b.forEach(function(d2, e) {
            return c.set(e, d2);
          });
          b = Array.from(c.values());
          b.length && b.every(function(d2) {
            return d2 == "expired";
          }) && a.A(new U(2, 6, 6014));
          a.F.Qf(lh(c));
        }
        function pi() {
          var a, b, c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N, O, Q, R, V;
          return P(function(Ba) {
            if (Ba.g == 1) {
              a = "org.w3.clearkey com.widevine.alpha com.widevine.alpha.experiment com.microsoft.playready com.microsoft.playready.hardware com.microsoft.playready.recommendation com.microsoft.playready.recommendation.3000 com.microsoft.playready.recommendation.3000.clearlead com.chromecast.playready com.apple.fps.1_0 com.apple.fps com.huawei.wiseplay".split(" ");
              if (!(window7.MediaKeys && window7.navigator && window7.navigator.requestMediaKeySystemAccess && window7.MediaKeySystemAccess && window7.MediaKeySystemAccess.prototype.getConfiguration)) {
                b = {};
                c = t2(a);
                for (d2 = c.next(); !d2.done; d2 = c.next()) e = d2.value, b[e] = null;
                return Ba.return(b);
              }
              f = "1.0 1.1 1.2 1.3 1.4 2.0 2.1 2.2 2.3".split(" ");
              g = ["SW_SECURE_CRYPTO", "SW_SECURE_DECODE", "HW_SECURE_CRYPTO", "HW_SECURE_DECODE", "HW_SECURE_ALL"];
              h = ["150", "2000", "3000"];
              k2 = {
                "com.widevine.alpha": g,
                "com.widevine.alpha.experiment": g,
                "com.microsoft.playready.recommendation": h
              };
              l = [{
                contentType: 'video/mp4; codecs="avc1.42E01E"'
              }, {
                contentType: 'video/webm; codecs="vp8"'
              }];
              m = [{
                contentType: 'audio/mp4; codecs="mp4a.40.2"'
              }, {
                contentType: 'audio/webm; codecs="opus"'
              }];
              n = {
                videoCapabilities: l,
                audioCapabilities: m,
                initDataTypes: ["cenc", "sinf", "skd", "keyids"]
              };
              q = [null, "cenc", "cbcs"];
              r2 = /* @__PURE__ */ new Map();
              u = Sb();
              w = function(aa, Oa) {
                var La, Ja, Ea, ya, Fa, Da, za, Ca, fb, hb, ib, xb, vb;
                return P(function(Va) {
                  switch (Va.g) {
                    case 1:
                      return sa(Va, 2), G(Va, Oa.createMediaKeys(), 5);
                    case 5:
                      La = Va.h;
                    case 4:
                      ua(Va, 3);
                      break;
                    case 2:
                      return va(Va), Va.return();
                    case 3:
                      Ea = (Ja = Oa.getConfiguration().sessionTypes) ? Ja.includes("persistent-license") : false;
                      u.nj() && (Ea = false);
                      ya = Oa.getConfiguration().videoCapabilities;
                      Fa = Oa.getConfiguration().audioCapabilities;
                      Da = {
                        persistentState: Ea,
                        encryptionSchemes: [],
                        videoRobustnessLevels: [],
                        audioRobustnessLevels: [],
                        minHdcpVersions: []
                      };
                      r2.has(aa) && r2.get(aa) ? Da = r2.get(aa) : r2.set(aa, Da);
                      (za = ya[0].encryptionScheme) && !Da.encryptionSchemes.includes(za) && Da.encryptionSchemes.push(za);
                      (Ca = ya[0].robustness) && !Da.videoRobustnessLevels.includes(Ca) && Da.videoRobustnessLevels.push(Ca);
                      (fb = Fa[0].robustness) && !Da.audioRobustnessLevels.includes(fb) && Da.audioRobustnessLevels.push(fb);
                      if ("getStatusForPolicy" in La) {
                        hb = [];
                        ib = t2(f);
                        xb = ib.next();
                        for (vb = {}; !xb.done; vb = {
                          pe: void 0
                        }, xb = ib.next()) vb.pe = xb.value, Da.minHdcpVersions.includes(vb.pe) || hb.push(La.getStatusForPolicy({
                          minHdcpVersion: vb.pe
                        }).then(/* @__PURE__ */ function(Wd) {
                          return function(Lc) {
                            Lc != "usable" || Da.minHdcpVersions.includes(Wd.pe) || Da.minHdcpVersions.push(Wd.pe);
                          };
                        }(vb)));
                        return G(Va, Promise.all(hb), 0);
                      }
                      Va.B(0);
                  }
                });
              };
              v = function(aa, Oa, La, Ja) {
                var Ea, ya, Fa, Da, za, Ca, fb, hb, ib, xb, vb;
                return P(function(Va) {
                  switch (Va.g) {
                    case 1:
                      sa(Va, 2);
                      Ea = Hd(n);
                      ya = t2(Ea.videoCapabilities);
                      for (Fa = ya.next(); !Fa.done; Fa = ya.next()) Da = Fa.value, Da.encryptionScheme = Oa, Da.robustness = La;
                      za = t2(Ea.audioCapabilities);
                      for (Ca = za.next(); !Ca.done; Ca = za.next()) fb = Ca.value, fb.encryptionScheme = Oa, fb.robustness = Ja;
                      hb = Hd(Ea);
                      hb.persistentState = "required";
                      hb.sessionTypes = ["persistent-license"];
                      ib = [hb, Ea];
                      vb = Sb();
                      return vb.Ka() == "MOBILE" ? G(Va, Gf(5, navigator.requestMediaKeySystemAccess(aa, ib)), 7) : G(Va, navigator.requestMediaKeySystemAccess(aa, ib), 6);
                    case 6:
                      xb = Va.h;
                      Va.B(5);
                      break;
                    case 7:
                      xb = Va.h;
                    case 5:
                      return G(Va, w(aa, xb), 8);
                    case 8:
                      ua(Va, 0);
                      break;
                    case 2:
                      va(Va), H(Va);
                  }
                });
              };
              y = function(aa, Oa, La, Ja) {
                var Ea, ya, Fa, Da;
                return P(function(za) {
                  switch (za.g) {
                    case 1:
                      return sa(za, 2), Ea = {
                        type: "media-source",
                        video: {
                          contentType: l[0].contentType,
                          width: 640,
                          height: 480,
                          bitrate: 1,
                          framerate: 1
                        },
                        audio: {
                          contentType: m[0].contentType,
                          channels: 2,
                          bitrate: 1,
                          samplerate: 1
                        },
                        keySystemConfiguration: {
                          keySystem: aa,
                          video: {
                            encryptionScheme: Oa,
                            robustness: La
                          },
                          audio: {
                            encryptionScheme: Oa,
                            robustness: Ja
                          }
                        }
                      }, Fa = Sb(), Fa.Ka() == "MOBILE" ? G(za, Gf(5, navigator.mediaCapabilities.decodingInfo(Ea)), 7) : G(za, navigator.mediaCapabilities.decodingInfo(Ea), 6);
                    case 6:
                      ya = za.h;
                      za.B(5);
                      break;
                    case 7:
                      ya = za.h;
                    case 5:
                      return Da = ya.keySystemAccess, G(za, w(aa, Da), 8);
                    case 8:
                      ua(za, 0);
                      break;
                    case 2:
                      va(za), H(za);
                  }
                });
              };
              z = t2(a);
              for (A = z.next(); !A.done; A = z.next()) C = A.value, r2.set(C, null);
              D = function(aa) {
                return Sb().Ga() === "WEBKIT" && aa === "org.w3.clearkey" ? false : true;
              };
              F = [];
              B = t2(q);
              for (E = B.next(); !E.done; E = B.next()) for (I = E.value, J = t2(a), K = J.next(); !K.done; K = J.next()) L = K.value, D(L) && (F.push(v(L, I, "", "")), F.push(y(L, I, "", "")));
              M = t2(a);
              for (N = M.next(); !N.done; N = M.next()) for (O = N.value, Q = t2(k2[O] || []), R = Q.next(); !R.done; R = Q.next()) V = R.value, D(O) && (F.push(v(O, null, V, "")), F.push(v(O, null, "", V)), F.push(y(O, null, V, "")), F.push(y(O, null, "", V)));
              return G(Ba, Promise.all(F), 2);
            }
            return Ba.return(lh(r2));
          });
        }
        function ki(a) {
          return P(function(b) {
            if (b.g == 1) return sa(b, 2), G(b, Gf(qi, Promise.all([a.close().catch(function() {
            }), a.closed])), 4);
            if (b.g != 2) return ua(b, 0);
            va(b);
            H(b);
          });
        }
        function Gh(a) {
          var b;
          return P(function(c) {
            b = Array.from(a.i.entries());
            a.i.clear();
            return G(c, Promise.all(b.map(function(d2) {
              d2 = t2(d2);
              var e = d2.next().value;
              var f = d2.next().value;
              return P(function(g) {
                if (g.g == 1) return sa(g, 2), a.ea || a.D.has(e.sessionId) || f.type !== "persistent-license" || a.h.persistentSessionOnlinePlayback ? G(g, ki(e), 5) : G(g, e.remove(), 5);
                if (g.g != 2) return ua(g, 0);
                va(g);
                H(g);
              });
            })), 0);
          });
        }
        function Oh(a) {
          return (a.video ? a.video.drmInfos : []).concat(a.audio ? a.audio.drmInfos : []);
        }
        function Eh(a) {
          a.i.forEach(function(b, c) {
            var d2 = b.Nh, e = c.expiration;
            isNaN(e) && (e = Infinity);
            e != d2 && (a.F.onExpirationUpdated(c.sessionId, e), b.Nh = e);
          });
        }
        function Zh(a) {
          a = a.i.values();
          return nb(a, function(b) {
            return b.loaded;
          });
        }
        function Yh(a) {
          for (var b = t2(a.g && a.g.keyIds || /* @__PURE__ */ new Set([])), c = b.next(); !c.done; c = b.next()) if (a.$.get(c.value) !== "usable") return false;
          return true;
        }
        function Nh(a, b) {
          var c = [];
          b.forEach(function(d2, e) {
            c.push({
              keySystem: e,
              licenseServerUri: d2,
              distinctiveIdentifierRequired: false,
              persistentStateRequired: false,
              audioRobustness: "",
              videoRobustness: "",
              serverCertificate: null,
              serverCertificateUri: "",
              initData: [],
              keyIds: /* @__PURE__ */ new Set()
            });
          });
          a = t2(a);
          for (b = a.next(); !b.done; b = a.next()) b = b.value, b.video && (b.video.drmInfos = c), b.audio && (b.audio.drmInfos = c);
        }
        function ei(a, b, c, d2, e, f, g, h) {
          var k2 = [];
          a = t2(a);
          for (var l = a.next(), m = {}; !l.done; m = {
            Ra: void 0
          }, l = a.next()) {
            m.Ra = l.value;
            b.includes(m.Ra.encryptionScheme) || b.push(m.Ra.encryptionScheme);
            m.Ra.keySystem == "org.w3.clearkey" && m.Ra.licenseServerUri.startsWith("data:application/json;base64,") ? k2.includes(m.Ra.licenseServerUri) || k2.push(m.Ra.licenseServerUri) : c.includes(m.Ra.licenseServerUri) || c.push(m.Ra.licenseServerUri);
            e.includes(m.Ra.serverCertificateUri) || e.push(m.Ra.serverCertificateUri);
            m.Ra.serverCertificate && (d2.some(/* @__PURE__ */ function(r2) {
              return function(u) {
                return Kb(u, r2.Ra.serverCertificate);
              };
            }(m)) || d2.push(m.Ra.serverCertificate));
            if (m.Ra.initData) {
              l = t2(m.Ra.initData);
              for (var n = l.next(), q = {}; !n.done; q = {
                Dh: void 0
              }, n = l.next()) q.Dh = n.value, f.some(/* @__PURE__ */ function(r2) {
                return function(u) {
                  var w = r2.Dh;
                  return u.keyId && u.keyId == w.keyId ? true : u.initDataType == w.initDataType && Kb(u.initData, w.initData);
                };
              }(q)) || f.push(q.Dh);
            }
            if (m.Ra.keyIds) for (l = t2(m.Ra.keyIds), n = l.next(); !n.done; n = l.next()) g.add(n.value);
            if (m.Ra.keySystemUris && h) for (m = t2(m.Ra.keySystemUris), l = m.next(); !l.done; l = m.next()) h.add(l.value);
          }
          if (k2.length == 1) c.push(k2[0]);
          else if (k2.length > 0) {
            b = [];
            k2 = t2(k2);
            for (d2 = k2.next(); !d2.done; d2 = k2.next()) d2 = window7.atob(d2.value.split("data:application/json;base64,").pop()), d2 = JSON.parse(d2), b.push.apply(b, x(d2.keys));
            k2 = JSON.stringify({
              keys: b
            });
            c.push("data:application/json;base64," + window7.btoa(k2));
          }
        }
        function Ph(a, b, c, d2) {
          var e = a.keySystem;
          if (e && (e != "org.w3.clearkey" || !a.licenseServerUri)) {
            b.size && b.get(e) && (b = b.get(e), a.licenseServerUri = b);
            a.keyIds || (a.keyIds = /* @__PURE__ */ new Set());
            if (c = c.get(e)) a.distinctiveIdentifierRequired || (a.distinctiveIdentifierRequired = c.distinctiveIdentifierRequired), a.persistentStateRequired || (a.persistentStateRequired = c.persistentStateRequired), a.serverCertificate || (a.serverCertificate = c.serverCertificate), c.sessionType && (a.sessionType = c.sessionType), a.serverCertificateUri || (a.serverCertificateUri = c.serverCertificateUri);
            d2[e] && (a.keySystem = d2[e]);
            window7.cast && window7.cast.__platform__ && e == "com.microsoft.playready" && (a.keySystem = "com.chromecast.playready");
          }
        }
        function Mh(a, b) {
          a = kh(a);
          if (a.size != 0) {
            a = pc(a);
            b = t2(b);
            for (var c = b.next(); !c.done; c = b.next()) c = c.value, c.video && (c.video.drmInfos = [a]), c.audio && (c.audio.drmInfos = [a]);
          }
        }
        var qi = 1, hi = 5, li = 0.5;
        function ri(a, b, c) {
          c = c === void 0 ? true : c;
          this.h = a;
          this.g = /* @__PURE__ */ new Set([a]);
          b = b || [];
          a = t2(b);
          for (b = a.next(); !b.done; b = a.next()) this.add(b.value, c);
        }
        ri.prototype.add = function(a, b) {
          var c = this.h;
          b = b === void 0 ? true : b;
          var d2;
          if (!(d2 = !!c.audio != !!a.audio || !!c.video != !!a.video || c.language != a.language) && (d2 = c.audio && a.audio)) {
            d2 = c.audio;
            var e = a.audio;
            d2 = !(!((!d2.channelsCount || !e.channelsCount || d2.channelsCount > 2 || e.channelsCount > 2) && d2.channelsCount != e.channelsCount || d2.spatialAudio !== e.spatialAudio || b && !si(d2, e)) && ti(d2.roles, e.roles) && d2.groupId === e.groupId);
          }
          !d2 && (d2 = c.video && a.video) && (c = c.video, d2 = a.video, d2 = !((!b || si(c, d2)) && ti(c.roles, d2.roles)));
          return d2 ? false : (this.g.add(a), true);
        };
        ri.prototype.values = function() {
          return this.g.values();
        };
        function si(a, b) {
          if (a.mimeType != b.mimeType) return false;
          a = a.codecs.split(",").map(function(d2) {
            return mf(d2);
          });
          b = b.codecs.split(",").map(function(d2) {
            return mf(d2);
          });
          if (a.length != b.length) return false;
          a.sort();
          b.sort();
          for (var c = 0; c < a.length; c++) if (a[c] != b[c]) return false;
          return true;
        }
        function ti(a, b) {
          a = new Set(a);
          b = new Set(b);
          a.delete("main");
          b.delete("main");
          if (a.size != b.size) return false;
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) if (!b.has(c.value)) return false;
          return true;
        }
        S("shaka.media.AdaptationSet", ri);
        S("shaka.config.CodecSwitchingStrategy", {
          RELOAD: "reload",
          SMOOTH: "smooth"
        });
        function ui() {
        }
        ui.prototype.create = function() {
        };
        ui.prototype.configure = function() {
        };
        ui.prototype.getConfiguration = function() {
        };
        S("shaka.media.AdaptationSetCriteria", ui);
        function vi() {
          this.g = wi;
          this.i = (/* @__PURE__ */ new Map()).set(wi, 2).set(xi, 1);
          this.h = 0;
        }
        var xi = 0, wi = 1;
        function yi(a, b, c) {
          this.g = a;
          this.i = b;
          this.h = c;
        }
        function zi(a, b) {
          return P(function(c) {
            if (c.g == 1) return G(c, Mf(a.h, b, a.g.drm.preferredKeySystems, a.g.drm.keySystemsMapping), 2);
            a.g.streaming.dontChooseCodecs || If(b, a.g.preferredVideoCodecs, a.g.preferredAudioCodecs, a.g.preferredDecodingAttributes, a.g.preferredTextFormats);
            if (!b.variants.some(kg)) throw new U(2, 4, 4032);
            return c.return(Ai(a, b));
          });
        }
        function Bi(a, b) {
          var c = a.g.restrictions;
          a = a.i;
          var d2 = false;
          b = t2(b.variants);
          for (var e = b.next(); !e.done; e = b.next()) {
            e = e.value;
            var f = e.allowedByApplication;
            e.allowedByApplication = Lf(e, c, a);
            f != e.allowedByApplication && (d2 = true);
          }
          return d2;
        }
        function Ai(a, b) {
          var c = Bi(a, b);
          if (b) {
            var d2 = a.h ? a.h.g : null;
            if (d2 && a.h.C) {
              for (var e = /* @__PURE__ */ new Set(), f = t2(b.variants), g = f.next(); !g.done; g = f.next()) g = g.value, g.audio && e.add(g.audio), g.video && e.add(g.video);
              e = t2(e);
              for (f = e.next(); !f.done; f = e.next()) Ci(a, d2.keySystem, f.value);
            }
            Di(a, b);
          }
          return c;
        }
        function Ci(a, b, c) {
          c = t2(c.drmInfos);
          for (var d2 = c.next(); !d2.done; d2 = c.next()) if (d2 = d2.value, d2.keySystem == b) {
            d2 = t2(d2.initData || []);
            for (var e = d2.next(); !e.done; e = d2.next()) e = e.value, Sh(a.h, e.initDataType, e.initData);
          }
        }
        function Di(a, b) {
          a = a.h ? a.h.tf() : {};
          var c = Object.keys(a);
          c = c.length && c[0] == "00";
          var d2 = false, e = false, f = /* @__PURE__ */ new Set(), g = /* @__PURE__ */ new Set(), h = /* @__PURE__ */ new Set();
          b = t2(b.variants);
          for (var k2 = b.next(); !k2.done; k2 = b.next()) k2 = k2.value, k2.audio && h.add(k2.audio), k2.video && h.add(k2.video), k2.allowedByApplication ? k2.allowedByKeySystem && (d2 = true) : e = true;
          h = t2(h);
          for (b = h.next(); !b.done; b = h.next()) if (b = b.value, b.keyIds.size) for (b = t2(b.keyIds), k2 = b.next(); !k2.done; k2 = b.next()) {
            k2 = k2.value;
            var l = a[c ? "00" : k2];
            l ? Ei.includes(l) && g.add(l) : f.add(k2);
          }
          if (!d2) throw a = {
            hasAppRestrictions: e,
            missingKeys: Array.from(f),
            restrictedKeyStatuses: Array.from(g)
          }, new U(2, 4, 4012, a);
        }
        var Ei = ["output-restricted", "internal-error"];
        function Fi() {
        }
        function Gi(a, b) {
          Hi.set(a, b);
        }
        function Ii() {
          var a = {};
          Sb();
          if (Ji()) for (var b = t2(Hi.keys()), c = b.next(); !c.done; c = b.next()) a[c.value] = true;
          b = t2(["application/dash+xml", "application/x-mpegurl", "application/vnd.apple.mpegurl", "application/vnd.ms-sstr+xml"]);
          for (c = b.next(); !c.done; c = b.next()) c = c.value, a[c] = Ji() ? Hi.has(c) : Ki().canPlayType(c) != "";
          return a;
        }
        function Li(a, b) {
          if (b) {
            var c = Hi.get(b.toLowerCase());
            if (c) return c;
          }
          throw new U(2, 4, 4e3, a, b);
        }
        S("shaka.media.ManifestParser", Fi);
        Fi.unregisterParserByMime = function(a) {
          Hi.delete(a);
        };
        Fi.registerParserByMime = Gi;
        Fi.registerParserByExtension = function() {
          Wc("ManifestParser.registerParserByExtension", "Please use an ManifestParser with registerParserByMime function.");
        };
        Fi.AccessibilityPurpose = {
          On: "visually impaired",
          Ym: "hard of hearing",
          xn: "spoken subtitles"
        };
        var Hi = /* @__PURE__ */ new Map();
        function Mi(a, b) {
          var c = null, d2 = null, e = null, f = null, g = a.X();
          b & 1 && (e = a.Qd());
          b & 2 && (f = a.X());
          b & 8 && (c = a.X());
          b & 16 && (d2 = a.X());
          return {
            trackId: g,
            ge: c,
            ie: d2,
            nk: e,
            Dj: f
          };
        }
        function Ni(a, b) {
          return b == 1 ? (b = a.X(), a = a.X(), {
            baseMediaDecodeTime: b * 4294967296 + a
          }) : {
            baseMediaDecodeTime: a.X()
          };
        }
        function Oi(a, b) {
          b == 1 ? (a.skip(8), a.skip(8)) : (a.skip(4), a.skip(4));
          b = a.X();
          a.skip(4);
          a = a.Ha();
          return {
            timescale: b,
            language: String.fromCharCode((a >> 10) + 96) + String.fromCharCode(((a & 960) >> 5) + 96) + String.fromCharCode((a & 31) + 96)
          };
        }
        function Pi(a, b, c) {
          var d2 = a.X(), e = [], f = null;
          c & 1 && (f = a.Sh());
          c & 4 && a.skip(4);
          for (var g = 0; g < d2; g++) {
            var h = {
              $h: null,
              sampleSize: null,
              cg: null
            };
            c & 256 && (h.$h = a.X());
            c & 512 && (h.sampleSize = a.X());
            c & 1024 && a.skip(4);
            c & 2048 && (h.cg = b == 0 ? a.X() : a.Sh());
            e.push(h);
          }
          return {
            Tn: d2,
            Zh: e,
            Ug: f
          };
        }
        function Qi(a) {
          a.skip(6);
          a.skip(2);
          a.skip(8);
          var b = a.Ha();
          a.skip(2);
          a.skip(2);
          a.skip(2);
          a = a.Ha() + a.Ha() / 65536;
          return {
            channelCount: b,
            sampleRate: a
          };
        }
        function Ri(a) {
          a = a.X();
          return {
            codec: th(a)
          };
        }
        function Si(a) {
          var b = null, c = null, d2 = a.$b(4);
          var e = String.fromCharCode(d2[0]);
          e += String.fromCharCode(d2[1]);
          e += String.fromCharCode(d2[2]);
          e += String.fromCharCode(d2[3]);
          if (e === "nclx") {
            switch (a.Ha()) {
              case 1:
              case 5:
              case 6:
              case 7:
                b = "srgb";
                break;
              case 9:
                b = "rec2020";
                break;
              case 11:
              case 12:
                b = "p3";
            }
            d2 = a.Ha();
            a.Ha();
            switch (d2) {
              case 1:
              case 6:
              case 13:
              case 14:
              case 15:
                c = "SDR";
                break;
              case 16:
                c = "PQ";
                break;
              case 18:
                c = "HLG";
            }
          }
          return {
            colorGamut: b,
            Ke: c
          };
        }
        function Ti(a, b) {
          b = b === void 0 ? false : b;
          a = a.toString(16).toUpperCase();
          return b ? a : ("0" + a).slice(-2);
        }
        function Ui(a) {
          return (a < 10 ? "0" : "") + a;
        }
        ;
        function Vi(a) {
          this.g = a;
        }
        function Wi(a) {
          for (var b = [], c = t2(a.g), d2 = c.next(); !d2.done; d2 = c.next()) {
            var e = b, f = e.push;
            var g = d2.value;
            d2 = Xi;
            var h = g.id + 1;
            var k2 = g.stream.width || 0, l = g.stream.height || 0;
            g.type == "audio" && (l = k2 = 0);
            var m = g.duration * g.timescale, n = Math.floor(m / (Yi + 1));
            m = Math.floor(m % (Yi + 1));
            h = new Uint8Array([1, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3].concat(x(Zi(h, 4)), [0, 0, 0, 0], x(Zi(n, 4)), x(Zi(m, 4)), [0, 0, 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, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0], x(Zi(k2, 2)), [0, 0], x(Zi(l, 2)), [0, 0]));
            h = Xi("tkhd", h);
            k2 = Xi;
            n = g.duration * g.timescale;
            l = Math.floor(n / (Yi + 1));
            n = Math.floor(n % (Yi + 1));
            m = g.stream.language;
            m = m.charCodeAt(0) - 96 << 10 | m.charCodeAt(1) - 96 << 5 | m.charCodeAt(2) - 96;
            l = new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3].concat(x(Zi(g.timescale, 4)), x(Zi(l, 4)), x(Zi(n, 4)), x(Zi(m, 2)), [0, 0]));
            l = Xi("mdhd", l);
            n = g;
            m = new Uint8Array([]);
            switch (n.type) {
              case "video":
                m = $i.value();
                break;
              case "audio":
                m = aj.value();
            }
            n = Xi("hdlr", m);
            a: {
              switch (g.type) {
                case "video":
                  g = Xi("minf", Xi("vmhd", bj.value()), cj.value(), dj(g));
                  break a;
                case "audio":
                  g = Xi("minf", Xi("smhd", ej.value()), cj.value(), dj(g));
                  break a;
              }
              g = new Uint8Array([]);
            }
            g = k2("mdia", l, n, g);
            d2 = d2("trak", h, g);
            f.call(e, d2);
          }
          b = mc.apply(ec, x(b));
          f = a.g[0];
          c = Xi;
          d2 = f.duration * f.timescale;
          e = Math.floor(d2 / (Yi + 1));
          d2 = Math.floor(d2 % (Yi + 1));
          e = new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3].concat(x(Zi(f.timescale, 4)), x(Zi(e, 4)), x(Zi(d2, 4)), [0, 1, 0, 0, 1, 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, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255]));
          e = Xi("mvhd", e);
          d2 = [];
          a = t2(a.g);
          for (k2 = a.next(); !k2.done; k2 = a.next()) g = d2, h = g.push, k2 = new Uint8Array([0, 0, 0, 0].concat(x(Zi(k2.value.id + 1, 4)), [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])), k2 = Xi("trex", k2), h.call(g, k2);
          a = mc.apply(ec, x(d2));
          a = Xi("mvex", a);
          d2 = [];
          if (f.encrypted) {
            f = t2(f.stream.drmInfos);
            for (g = f.next(); !g.done; g = f.next()) if (g = g.value, g.initData) for (g = t2(g.initData), h = g.next(); !h.done; h = g.next()) d2.push(h.value.initData);
            f = mc.apply(ec, x(d2));
          } else f = new Uint8Array([]);
          a = c("moov", e, b, a, f);
          b = fj.value();
          c = new Uint8Array(b.byteLength + a.byteLength);
          c.set(b);
          c.set(a, b.byteLength);
          return c;
        }
        function dj(a) {
          var b = Xi, c = "aac";
          a.codecs.includes("mp3") ? c = "mp3" : a.codecs.includes("ac-3") ? c = Sb().Ce() ? "ec-3" : "ac-3" : a.codecs.includes("ec-3") ? c = "ec-3" : a.codecs.includes("opus") && (c = "opus");
          var d2 = new Uint8Array([]);
          switch (a.type) {
            case "video":
              if (a.codecs.includes("avc1")) {
                c = a.stream.width || 0;
                d2 = a.stream.height || 0;
                if (a.Xa.byteLength > 0) var e = Xi("avcC", a.Xa);
                else {
                  e = Xi;
                  for (var f = 7, g = [], h = [], k2 = 0, l = 0, m = 0, n = 0; n < a.Gb.length; n++) {
                    var q = gj(a.Gb[n]);
                    switch (q[0] & 31) {
                      case 7:
                        g.push(q);
                        f += q.length + 2;
                        break;
                      case 8:
                        h.push(q), f += q.length + 2;
                    }
                  }
                  g.length > 0 && (k2 = g[0][1], m = g[0][2], l = g[0][3]);
                  f = new Uint8Array(f);
                  n = 0;
                  f[n++] = 1;
                  f[n++] = k2;
                  f[n++] = m;
                  f[n++] = l;
                  f[n++] = 255;
                  f[n++] = 224 | g.length;
                  for (k2 = 0; k2 < g.length; k2++) f[n++] = (g[k2].length & 65280) >> 8, f[n++] = g[k2].length & 255, f.set(g[k2], n), n += g[k2].length;
                  f[n++] = h.length;
                  for (g = 0; g < h.length; g++) f[n++] = (h[g].length & 65280) >> 8, f[n++] = h[g].length & 255, f.set(h[g], n), n += h[g].length;
                  e = e("avcC", f);
                }
                c = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].concat(x(Zi(c, 2)), x(Zi(d2, 2)), [0, 72, 0, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 1, 19, 118, 105, 100, 101, 111, 106, 115, 45, 99, 111, 110, 116, 114, 105, 98, 45, 104, 108, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 17, 17]));
                d2 = "avc1";
                h = hj(a);
                g = new Uint8Array([]);
                a.encrypted && (g = ij(a.stream, a.codecs), d2 = "encv");
                d2 = Xi(d2, c, e, h, g);
              } else a.codecs.includes("hvc1") && (d2 = a.stream.width || 0, e = a.stream.height || 0, c = new Uint8Array([]), a.Xa.byteLength > 0 && (c = Xi("hvcC", a.Xa)), d2 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].concat(x(Zi(d2, 2)), x(Zi(e, 2)), [0, 72, 0, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 1, 19, 118, 105, 100, 101, 111, 106, 115, 45, 99, 111, 110, 116, 114, 105, 98, 45, 104, 108, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 17, 17])), e = "hvc1", h = hj(a), g = new Uint8Array([]), a.encrypted && (g = ij(a.stream, a.codecs), e = "encv"), d2 = Xi(e, d2, c, h, g));
              break;
            case "audio":
              if (c == "mp3") a = Xi(".mp3", jj(a));
              else if (c == "ac-3") c = Xi("dac3", a.Na), d2 = "ac-3", e = new Uint8Array([]), a.encrypted && (e = ij(a.stream, a.codecs), d2 = "enca"), a = Xi(d2, jj(a), c, e);
              else if (c == "ec-3") c = Xi("dec3", a.Na), d2 = "ec-3", e = new Uint8Array([]), a.encrypted && (e = ij(a.stream, a.codecs), d2 = "enca"), a = Xi(d2, jj(a), c, e);
              else if (c == "opus") c = Xi("dOps", a.Na), d2 = "Opus", e = new Uint8Array([]), a.encrypted && (e = ij(a.stream, a.codecs), d2 = "enca"), a = Xi(d2, jj(a), c, e);
              else {
                if (a.Na.byteLength > 0) c = Xi("esds", a.Na);
                else {
                  c = Xi;
                  d2 = a.id + 1;
                  e = a.stream.channelsCount || 2;
                  g = a.stream.audioSamplingRate || 44100;
                  k2 = qc("audio", a.codecs.split(","));
                  l = {
                    96e3: 0,
                    88200: 1,
                    64e3: 2,
                    48e3: 3,
                    44100: 4,
                    32e3: 5,
                    24e3: 6,
                    22050: 7,
                    16e3: 8,
                    12e3: 9,
                    11025: 10,
                    8e3: 11,
                    7350: 12
                  };
                  h = l[g];
                  if (k2 === "mp4a.40.5" || k2 === "mp4a.40.29") h = l[g * 2];
                  g = parseInt(k2.split(".").pop(), 10);
                  d2 = new Uint8Array([0, 0, 0, 0, 3, 25].concat(x(Zi(d2, 2)), [0, 4, 17, 64, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 2, g << 3 | h >>> 1, h << 7 | e << 3, 6, 1, 2]));
                  c = c("esds", d2);
                }
                d2 = "mp4a";
                e = new Uint8Array([]);
                a.encrypted && (e = ij(a.stream, a.codecs), d2 = "enca");
                a = Xi(d2, jj(a), c, e);
              }
              d2 = a;
          }
          a = Xi("stsd", kj.value(), d2);
          return b("stbl", a, Xi("stts", lj.value()), Xi("stsc", mj.value()), Xi("stsz", nj.value()), Xi("stco", oj.value()));
        }
        function hj(a) {
          if (!a.eb && !a.gb) return new Uint8Array([]);
          var b = a.gb;
          a = new Uint8Array([].concat(x(Zi(a.eb, 4)), x(Zi(b, 4))));
          return Xi("pasp", a);
        }
        function jj(a) {
          return new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, a.stream.channelsCount || 2, 0, 16, 0, 0, 0, 0].concat(x(Zi(a.stream.audioSamplingRate || 44100, 2)), [0, 0]));
        }
        function ij(a, b) {
          var c = Xi;
          b = new Uint8Array([].concat(x(Zi(pj(b.split(".")[0]), 4))));
          b = Xi("frma", b);
          var d2 = "cenc";
          var e = a.drmInfos[0];
          e && e.encryptionScheme && (d2 = e.encryptionScheme);
          d2 = new Uint8Array([0, 0, 0, 0].concat(x(Zi(pj(d2), 4)), [0, 1, 0, 0]));
          d2 = Xi("schm", d2);
          e = Xi;
          var f = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
          a = t2(a.drmInfos);
          for (var g = a.next(); !g.done; g = a.next()) if ((g = g.value) && g.keyIds && g.keyIds.size) {
            g = t2(g.keyIds);
            for (var h = g.next(); !h.done; h = g.next()) f = gj(h.value);
          }
          a = new Uint8Array([0, 0, 0, 0, 0, 0, 1, 8]);
          f = Xi("tenc", a, f);
          return c("sinf", b, d2, e("schi", f));
        }
        function qj(a) {
          var b = [];
          a = t2(a.g);
          for (var c = a.next(); !c.done; c = a.next()) {
            c = c.value;
            var d2 = b.push, e = d2.apply;
            var f = Xi;
            var g = new Uint8Array([0, 0, 0, 0].concat(x(Zi(c.data ? c.data.sequenceNumber : 0, 4))));
            g = Xi("mfhd", g);
            var h;
            var k2 = c.data ? c.data.Eb : [];
            var l = new Uint8Array(4 + k2.length);
            for (h = 0; h < k2.length; h++) {
              var m = k2[h].flags;
              l[h + 4] = m.qb << 4 | m.ub << 2 | m.sb;
            }
            k2 = Xi("sdtp", l);
            var n = k2.length + 32 + 20 + 8 + 16 + 8 + 8;
            l = Xi;
            h = new Uint8Array([0, 0, 0, 58].concat(x(Zi(c.id + 1, 4)), [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
            h = Xi("tfhd", h);
            m = c.data ? c.data.baseMediaDecodeTime : 0;
            var q = Math.floor(m % (Yi + 1));
            m = new Uint8Array([1, 0, 0, 0].concat(x(Zi(Math.floor(m / (Yi + 1)), 4)), x(Zi(q, 4))));
            m = Xi("tfdt", m);
            var r2 = n;
            n = c.data ? c.data.Eb : [];
            q = n.length;
            var u = 12 + 16 * q, w = new Uint8Array(u);
            r2 += 8 + u;
            w.set([c.type === "video" ? 1 : 0, 0, 15, 1].concat(x(Zi(q, 4)), x(Zi(r2, 4))), 0);
            for (r2 = 0; r2 < q; r2++) {
              var v = n[r2];
              u = Zi(v.duration, 4);
              var y = Zi(v.size, 4), z = v.flags;
              v = Zi(v.Ab, 4);
              w.set([].concat(x(u), x(y), [z.Cb << 2 | z.qb, z.ub << 6 | z.sb << 4 | z.Db, z.pb & 61440, z.pb & 15], x(v)), 12 + 16 * r2);
            }
            n = Xi("trun", w);
            k2 = l("traf", h, m, n, k2);
            f = f("moof", g, k2);
            e.call(d2, b, [f, rj(c)]);
          }
          return mc.apply(ec, x(b));
        }
        function rj(a) {
          a = (a.data ? a.data.Eb : []).map(function(b) {
            return b.data;
          });
          a = mc.apply(ec, x(a));
          return Xi("mdat", a);
        }
        function Zi(a, b) {
          var c = [];
          for (--b; b >= 0; b--) c.push(a >> 8 * b & 255);
          return c;
        }
        function gj(a) {
          for (var b = new Uint8Array(a.length / 2), c = 0; c < a.length / 2; c += 1) b[c] = parseInt(String(a[c * 2] + a[c * 2 + 1]), 16);
          return b;
        }
        function pj(a) {
          for (var b = 0, c = 0; c < a.length; c += 1) b |= a.charCodeAt(c) << (a.length - c - 1) * 8;
          return b;
        }
        function Xi(a) {
          var b = Na.apply(1, arguments), c = sj.get(a);
          c || (c = [a.charCodeAt(0), a.charCodeAt(1), a.charCodeAt(2), a.charCodeAt(3)], sj.set(a, c));
          for (var d2 = 8, e = b.length - 1; e >= 0; e--) d2 += b[e].byteLength;
          e = new Uint8Array(d2);
          e[0] = d2 >> 24 & 255;
          e[1] = d2 >> 16 & 255;
          e[2] = d2 >> 8 & 255;
          e[3] = d2 & 255;
          e.set(c, 4);
          c = 0;
          for (d2 = 8; c < b.length; c++) e.set(b[c], d2), d2 += b[c].byteLength;
          return e;
        }
        var Yi = 4294967295, sj = /* @__PURE__ */ new Map(), $i = new Rb(function() {
          return new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 118, 105, 100, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 86, 105, 100, 101, 111, 72, 97, 110, 100, 108, 101, 114, 0]);
        }), aj = new Rb(function() {
          return new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 115, 111, 117, 110, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 111, 117, 110, 100, 72, 97, 110, 100, 108, 101, 114, 0]);
        }), lj = new Rb(function() {
          return new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]);
        }), mj = new Rb(function() {
          return new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]);
        }), oj = new Rb(function() {
          return new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]);
        }), nj = new Rb(function() {
          return new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
        }), bj = new Rb(function() {
          return new Uint8Array([0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
        }), ej = new Rb(function() {
          return new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]);
        }), kj = new Rb(function() {
          return new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1]);
        }), fj = new Rb(function() {
          var a = new Uint8Array([105, 115, 111, 109]), b = new Uint8Array([97, 118, 99, 49]), c = new Uint8Array([0, 0, 0, 1]);
          return Xi("ftyp", a, c, a, b);
        }), cj = new Rb(function() {
          var a = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 12, 117, 114, 108, 32, 0, 0, 0, 1]);
          a = Xi("dref", a);
          return Xi("dinf", a);
        });
        function tj(a) {
          a = Lb(a);
          var b = null;
          new ph().box("moov", uh).box("trak", uh).box("mdia", uh).box("minf", uh).box("stbl", uh).W("stsd", wh).box("enca", function(c) {
            b = c.reader.h;
            return yh(c);
          }).box("sinf", uh).box("frma", function(c) {
            c.parser.stop();
            Ri(c.reader).codec === "ec-3" && b && b.getUint16(16) !== 2 && b.setUint16(16, 2);
          }).parse(a);
          return a;
        }
        function uj(a, b, c) {
          function d2(r2) {
            n.push({
              box: r2,
              pj: 1701733217
            });
          }
          function e(r2) {
            n.push({
              box: r2,
              pj: 1701733238
            });
          }
          function f(r2) {
            k2 = true;
            r2.parser.stop();
          }
          function g(r2) {
            m.push(r2);
            uh(r2);
          }
          var h = b = Lb(b), k2 = false, l, m = [], n = [];
          new ph().box("moov", g).box("trak", g).box("mdia", g).box("minf", g).box("stbl", g).W("stsd", function(r2) {
            l = r2;
            m.push(r2);
            wh(r2);
          }).W("encv", f).W("enca", f).W("dvav", e).W("dva1", e).W("dvh1", e).W("dvhe", e).W("dvc1", e).W("dvi1", e).W("hev1", e).W("hvc1", e).W("avc1", e).W("avc3", e).W("ac-3", d2).W("ec-3", d2).W("ac-4", d2).W("Opus", d2).W("fLaC", d2).W("mp4a", d2).parse(b);
          if (k2) return b;
          if (n.length == 0 || !l) throw jb(lc(b)), new U(2, 3, 3019, c);
          n.reverse();
          c = t2(n);
          for (var q = c.next(); !q.done; q = c.next()) q = q.value, h = vj(a, h, l, q.box, m, q.pj);
          return Sb().yj() ? (a = new Uint8Array(b.byteLength + h.byteLength), a.set(h), a.set(b, h.byteLength), a) : h;
        }
        function wj(a) {
          a = Lb(a);
          var b = [];
          new ph().box("mdat", function(g) {
            b.push(g);
          }).parse(a);
          for (var c = [], d2 = 0; d2 < b.length; d2++) {
            var e = b[d2 - 1], f = b[d2];
            c.push(xj(a.subarray(e ? e.start + e.size : 0, f.start + f.size)));
          }
          return mc.apply(ec, x(c));
        }
        function xj(a) {
          function b(n) {
            g.push(n);
            uh(n);
          }
          var c, d2, e, f, g = [];
          new ph().box("moof", b).box("traf", b).W("tfhd", function(n) {
            c = n;
            e = Mi(n.reader, n.flags);
          }).W("trun", function(n) {
            d2 = n;
            f = Pi(n.reader, n.version, n.flags);
          }).parse(a);
          if (e && e.Dj !== 2) {
            var h = c.start + vh(c) + 4 + (e.nk !== null ? 8 : 0), k2 = Pb(a);
            if (e.Dj !== null) k2.setUint32(h, 2);
            else {
              yj(a, c.start, c.size + 4);
              var l = k2.getUint32(c.start + 8);
              k2.setUint32(c.start + 8, l | 2);
              f && f.Ug !== null && k2.setInt32(d2.start + vh(d2) + 4, f.Ug + 4);
              l = a.subarray(0, h);
              k2 = a.subarray(h);
              a = new Uint8Array(a.byteLength + 4);
              a.set(l);
              l = [];
              for (var m = 3; m >= 0; m--) l.push(2 >> 8 * m & 255);
              a.set(new Uint8Array(l), h);
              a.set(k2, h + 4);
              h = t2(g);
              for (k2 = h.next(); !k2.done; k2 = h.next()) k2 = k2.value, yj(a, k2.start, k2.size + 4);
            }
          }
          return a;
        }
        function vj(a, b, c, d2, e, f) {
          var g = ij(a, d2.name), h = b.subarray(d2.start, d2.start + d2.size);
          a = new Uint8Array(d2.size + g.byteLength);
          a.set(h, 0);
          Pb(a).setUint32(4, f);
          a.set(g, d2.size);
          yj(a, 0, a.byteLength);
          f = new Uint8Array(b.byteLength + a.byteLength);
          d2 = Sb().Af() ? d2.start : d2.start + d2.size;
          g = b.subarray(d2);
          f.set(b.subarray(0, d2));
          f.set(a, d2);
          f.set(g, d2 + a.byteLength);
          b = t2(e);
          for (e = b.next(); !e.done; e = b.next()) e = e.value, yj(f, e.start, e.size + a.byteLength);
          a = Pb(f, c.start);
          c = vh(c);
          b = a.getUint32(c);
          a.setUint32(c, b + 1);
          return f;
        }
        function yj(a, b, c) {
          a = Pb(a, b);
          b = a.getUint32(0);
          b != 0 && (b == 1 ? (a.setUint32(8, c >> 32), a.setUint32(12, c & 4294967295)) : a.setUint32(0, c));
        }
        function zj(a) {
          function b(e) {
            d2.push({
              start: e.start,
              size: e.size
            });
            uh(e);
          }
          var c = Lb(a), d2 = [];
          new ph().box("moov", b).box("trak", b).box("mdia", b).box("minf", b).box("stbl", b).box("stsd", function(e) {
            d2.push({
              start: e.start,
              size: e.size
            });
            for (var f = Pb(c, e.start), g = 0; g < e.size - 3; g++) {
              var h = f.getUint32(g);
              h == 1633889587 ? f.setUint32(g, 1700998451) : h == 1684103987 && f.setUint32(g, 1684366131);
            }
          }).parse(c);
          return c;
        }
        ;
        function Aj(a, b, c, d2, e, f, g, h) {
          this.T = a;
          this.startByte = b;
          this.endByte = c;
          this.Kd = d2 === void 0 ? null : d2;
          this.timescale = e === void 0 ? null : e;
          this.h = f === void 0 ? null : f;
          this.aesKey = g === void 0 ? null : g;
          this.g = this.mimeType = this.codecs = null;
          this.encrypted = h === void 0 ? false : h;
        }
        Aj.prototype.Nc = function() {
          return this.startByte;
        };
        Aj.prototype.Lc = function() {
          return this.endByte;
        };
        Aj.prototype.Ee = function(a) {
          this.h = a;
        };
        Aj.prototype.fc = function() {
          return this.h;
        };
        function Bj(a, b) {
          return a === b ? true : a && b ? a.Nc() == b.Nc() && a.Lc() == b.Lc() && wd(a.T().sort(), b.T().sort()) && Kb(a.fc(), b.fc()) : a == b;
        }
        S("shaka.media.InitSegmentReference", Aj);
        Aj.prototype.getEndByte = Aj.prototype.Lc;
        Aj.prototype.getStartByte = Aj.prototype.Nc;
        function Cj(a, b, c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w) {
          l = l === void 0 ? [] : l;
          r2 = r2 === void 0 ? Dj : r2;
          this.startTime = a;
          this.j = this.endTime = b;
          this.F = c;
          this.startByte = d2;
          this.endByte = e;
          this.ha = f;
          this.timestampOffset = g;
          this.appendWindowStart = h;
          this.appendWindowEnd = k2;
          this.g = l;
          this.tilesLayout = m === void 0 ? "" : m;
          this.D = n === void 0 ? null : n;
          this.h = q === void 0 ? null : q;
          this.status = r2;
          this.preload = false;
          this.l = true;
          this.m = false;
          this.aesKey = u === void 0 ? null : u;
          this.thumbnailSprite = null;
          this.i = -1;
          this.C = w === void 0 ? false : w;
          this.G = this.u = false;
          a = t2(this.g);
          for (b = a.next(); !b.done; b = a.next()) b.value.lj();
          this.C && this.g.length && this.g[this.g.length - 1].kj();
          this.A = this.bandwidth = this.mimeType = this.codecs = null;
          this.H = false;
        }
        p = Cj.prototype;
        p.T = function() {
          return this.F();
        };
        p.getStartTime = function() {
          return this.startTime;
        };
        p.Mk = function() {
          return this.endTime;
        };
        p.Nc = function() {
          return this.startByte;
        };
        p.Lc = function() {
          return this.endByte;
        };
        p.ql = function() {
          return this.tilesLayout;
        };
        p.ol = function() {
          return this.D;
        };
        p.Oc = function() {
          return this.status;
        };
        p.Ol = function() {
          this.status = Ej;
        };
        p.Jh = function() {
          this.preload = true;
        };
        p.isPreload = function() {
          return this.preload;
        };
        p.Jd = function() {
          this.l = false;
        };
        p.El = function() {
          return this.l;
        };
        p.lj = function() {
          this.u = true;
        };
        p.Gl = function() {
          return this.u;
        };
        p.kj = function() {
          this.G = true;
        };
        p.Fl = function() {
          return this.G;
        };
        p.jj = function() {
          this.m = true;
        };
        p.Al = function() {
          return this.m;
        };
        p.jg = function(a) {
          this.thumbnailSprite = a;
        };
        p.ll = function() {
          return this.thumbnailSprite;
        };
        p.offset = function(a) {
          this.startTime += a;
          this.endTime += a;
          this.j += a;
          for (var b = t2(this.g), c = b.next(); !c.done; c = b.next()) c = c.value, c.startTime += a, c.endTime += a, c.j += a;
        };
        p.pi = function(a) {
          this.h == null ? ab("Sync attempted without sync time!") : (a = this.h - a - this.startTime, Math.abs(a) >= 1e-3 && this.offset(a));
        };
        p.Ee = function(a, b) {
          this.A = a;
          this.H = b === void 0 ? false : b;
        };
        p.fc = function(a) {
          var b = this.A;
          (a === void 0 || a) && this.H && (this.A = null);
          return b;
        };
        function Fj(a, b) {
          a.ha = b;
          a = t2(a.g);
          for (var c = a.next(); !c.done; c = a.next()) Fj(c.value, b);
        }
        S("shaka.media.SegmentReference", Cj);
        Cj.prototype.getSegmentData = Cj.prototype.fc;
        Cj.prototype.setSegmentData = Cj.prototype.Ee;
        Cj.prototype.syncAgainst = Cj.prototype.pi;
        Cj.prototype.offset = Cj.prototype.offset;
        Cj.prototype.getThumbnailSprite = Cj.prototype.ll;
        Cj.prototype.setThumbnailSprite = Cj.prototype.jg;
        Cj.prototype.hasByterangeOptimization = Cj.prototype.Al;
        Cj.prototype.markAsByterangeOptimization = Cj.prototype.jj;
        Cj.prototype.isLastPartial = Cj.prototype.Fl;
        Cj.prototype.markAsLastPartial = Cj.prototype.kj;
        Cj.prototype.isPartial = Cj.prototype.Gl;
        Cj.prototype.markAsPartial = Cj.prototype.lj;
        Cj.prototype.isIndependent = Cj.prototype.El;
        Cj.prototype.markAsNonIndependent = Cj.prototype.Jd;
        Cj.prototype.isPreload = Cj.prototype.isPreload;
        Cj.prototype.markAsPreload = Cj.prototype.Jh;
        Cj.prototype.markAsUnavailable = Cj.prototype.Ol;
        Cj.prototype.getStatus = Cj.prototype.Oc;
        Cj.prototype.getTileDuration = Cj.prototype.ol;
        Cj.prototype.getTilesLayout = Cj.prototype.ql;
        Cj.prototype.getEndByte = Cj.prototype.Lc;
        Cj.prototype.getStartByte = Cj.prototype.Nc;
        Cj.prototype.getEndTime = Cj.prototype.Mk;
        Cj.prototype.getStartTime = Cj.prototype.getStartTime;
        Cj.prototype.getUris = Cj.prototype.T;
        var Dj = 0, Ej = 1;
        Cj.Status = {
          Fm: Dj,
          Mn: Ej,
          ln: 2
        };
        function Gj(a) {
          return a.length == 1 && a.end(0) - a.start(0) < 1e-4;
        }
        function Hj(a) {
          return !a || Gj(a) ? null : a.length == 1 && a.start(0) < 0 ? 0 : a.length ? a.start(0) : null;
        }
        function Ij(a) {
          return !a || Gj(a) ? null : a.length ? a.end(a.length - 1) : null;
        }
        function Jj(a, b) {
          return !a || !a.length || Gj(a) || b > a.end(a.length - 1) ? false : b >= a.start(0);
        }
        function Kj(a, b) {
          if (!a || !a.length || Gj(a)) return 0;
          var c = 0;
          a = t2(Lj(a));
          for (var d2 = a.next(); !d2.done; d2 = a.next()) {
            var e = d2.value;
            d2 = e.start;
            e = e.end;
            e > b && (c += e - Math.max(d2, b));
          }
          return c;
        }
        function Mj(a, b, c) {
          if (!a || !a.length || Gj(a)) return null;
          a = Lj(a).findIndex(function(d2, e, f) {
            return d2.start > b && (e == 0 || f[e - 1].end - b <= c);
          });
          return a >= 0 ? a : null;
        }
        function Lj(a) {
          if (!a) return [];
          for (var b = [], c = 0; c < a.length; c++) b.push({
            start: a.start(c),
            end: a.end(c)
          });
          return b;
        }
        ;
        function Nj() {
        }
        function W(a) {
          return document.createElement(a);
        }
        function Oj() {
          var a = document.createElement("button");
          a.setAttribute("type", "button");
          return a;
        }
        function Pj(a, b) {
          var c = document.createElement("source");
          c.src = a;
          c.type = b === void 0 ? "" : b;
          return c;
        }
        function Qj(a) {
          for (var b = false, c = a.getElementsByTagName("source"), d2 = c.length - 1; d2 >= 0; --d2) a.removeChild(c[d2]), b = true;
          a.src && (a.removeAttribute("src"), b = true);
          return b;
        }
        function Rj(a) {
          a = a.getElementsByClassName("shaka-overflow-quality-mark");
          return a.length ? a[0] : null;
        }
        function Sj(a) {
          for (; a.firstChild; ) a.removeChild(a.firstChild);
        }
        function Ki() {
          if (Tj) return Tj;
          Uj || (Uj = new Cf(function() {
            Tj = null;
          }));
          (Tj = document.getElementsByTagName("video")[0] || document.getElementsByTagName("audio")[0]) || (Tj = document.createElement("video"));
          Uj.Y(1);
          return Tj;
        }
        function Vj(a, b) {
          var c, d2, e, f, g;
          return P(function(h) {
            if (h.g == 1) return "fonts" in document && "FontFace" in window7 ? G(h, document.fonts.ready, 2) : h.return();
            if (!("entries" in document.fonts)) return h.return();
            c = function(k2) {
              k2 = k2.entries();
              for (var l = [], m = k2.next(); m.done === false; ) l.push(m.value), m = k2.next();
              return l;
            };
            d2 = t2(c(document.fonts));
            for (e = d2.next(); !e.done; e = d2.next()) if (f = e.value, f.family === a && f.display === "swap") return h.return();
            g = new FontFace(a, "url(" + b + ")", {
              display: "swap"
            });
            document.fonts.add(g);
            H(h);
          });
        }
        S("shaka.util.Dom", Nj);
        Nj.removeAllChildren = Sj;
        Nj.clearSourceFromVideo = Qj;
        var Uj = null, Tj = null;
        function Wj() {
        }
        function Xj(a, b) {
          return b + 10 <= a.length && a[b] === 73 && a[b + 1] === 68 && a[b + 2] === 51 && a[b + 3] < 255 && a[b + 4] < 255 && a[b + 6] < 128 && a[b + 7] < 128 && a[b + 8] < 128 && a[b + 9] < 128 ? true : false;
        }
        function Yj(a, b) {
          return b + 10 <= a.length && a[b] === 51 && a[b + 1] === 68 && a[b + 2] === 73 && a[b + 3] < 255 && a[b + 4] < 255 && a[b + 6] < 128 && a[b + 7] < 128 && a[b + 8] < 128 && a[b + 9] < 128 ? true : false;
        }
        function Zj(a, b) {
          var c = (a[b] & 127) << 21;
          c |= (a[b + 1] & 127) << 14;
          c |= (a[b + 2] & 127) << 7;
          return c |= a[b + 3] & 127;
        }
        function ak(a) {
          var b = {
            key: a.type,
            description: "",
            data: "",
            mimeType: null,
            pictureType: null
          };
          if (a.type === "APIC") {
            if (a.size < 2 || a.data[0] !== 3) return null;
            var c = a.data.subarray(1).indexOf(0);
            if (c === -1) return null;
            var d2 = Xb(Lb(a.data, 1, c)), e = a.data[2 + c], f = a.data.subarray(3 + c).indexOf(0);
            if (f === -1) return null;
            var g = Xb(Lb(a.data, 3 + c, f)), h;
            d2 === "-->" ? h = Xb(Lb(a.data, 4 + c + f)) : h = Mb(a.data.subarray(4 + c + f));
            b.mimeType = d2;
            b.pictureType = e;
            b.description = g;
            b.data = h;
            return b;
          }
          if (a.type === "TXXX") {
            if (a.size < 2 || a.data[0] !== 3) return null;
            d2 = a.data.subarray(1).indexOf(0);
            if (d2 === -1) return null;
            c = Xb(Lb(a.data, 1, d2));
            a = Xb(Lb(a.data, 2 + d2)).replace(/\0*$/, "");
            b.description = c;
            b.data = a;
            return b;
          }
          if (a.type === "WXXX") {
            if (a.size < 2 || a.data[0] !== 3) return null;
            d2 = a.data.subarray(1).indexOf(0);
            if (d2 === -1) return null;
            c = Xb(Lb(a.data, 1, d2));
            a = Xb(Lb(a.data, 2 + d2)).replace(/\0*$/, "");
            b.description = c;
            b.data = a;
            return b;
          }
          if (a.type === "PRIV") {
            if (a.size < 2) return null;
            c = a.data.indexOf(0);
            if (c === -1) return null;
            c = Xb(Lb(a.data, 0, c));
            b.description = c;
            c == "com.apple.streaming.transportStreamTimestamp" ? (c = a.data.subarray(c.length + 1), a = c[3] & 1, c = (c[4] << 23) + (c[5] << 15) + (c[6] << 7) + c[7], c /= 45, a && (c += 4772185884e-2), b.data = c) : (a = Mb(a.data.subarray(c.length + 1)), b.data = a);
            return b;
          }
          if (a.type[0] === "T") {
            if (a.size < 2 || a.data[0] !== 3) return null;
            a = Xb(a.data.subarray(1)).replace(/\0*$/, "");
            b.data = a;
            return b;
          }
          return a.type[0] === "W" ? (a = Xb(a.data).replace(/\0*$/, ""), b.data = a, b) : a.data ? (b.data = Mb(a.data), b) : null;
        }
        function bk(a) {
          for (var b = 0, c = []; Xj(a, b); ) {
            var d2 = Zj(a, b + 6);
            a[b + 5] >> 6 & 1 && (b += 10);
            b += 10;
            for (d2 = b + d2; b + 10 < d2; ) {
              var e = a.subarray(b), f = Zj(e, 4);
              e = {
                type: String.fromCharCode(e[0], e[1], e[2], e[3]),
                size: f,
                data: e.subarray(10, 10 + f)
              };
              (f = ak(e)) && c.push(f);
              b += e.size + 10;
            }
            Yj(a, b) && (b += 10);
          }
          return c;
        }
        function ck(a, b) {
          for (var c = b = b === void 0 ? 0 : b, d2 = 0; Xj(a, b); ) a[b + 5] >> 6 & 1 && (d2 += 10), d2 += 10, d2 += Zj(a, b + 6), Yj(a, b + 10) && (d2 += 10), b += d2;
          return d2 > 0 ? a.subarray(c, c + d2) : new Uint8Array([]);
        }
        S("shaka.util.Id3Utils", Wj);
        Wj.getID3Data = ck;
        Wj.getID3Frames = bk;
        function dk(a) {
          return new Date(Date.UTC(1900, 0, 1, 0, 0, 0, 0) + a).getTime();
        }
        ;
        function ek(a, b) {
          this.j = a;
          if (b === void 0 ? 0 : b) {
            b = new Uint8Array(a.byteLength);
            for (var c = 0, d2 = 0; d2 < a.byteLength; d2++) d2 >= 2 && a[d2] == 3 && a[d2 - 1] == 0 && a[d2 - 2] == 0 || (b[c] = a[d2], c++);
            this.j = Lb(b, 0, c);
          }
          this.i = this.j.byteLength;
          this.g = this.h = 0;
        }
        function fk(a) {
          var b = a.j.byteLength - a.i, c = new Uint8Array(4), d2 = Math.min(4, a.i);
          d2 !== 0 && (c.set(a.j.subarray(b, b + d2)), a.h = new mh(c, 0).X(), a.g = d2 * 8, a.i -= d2);
        }
        function gk(a, b) {
          if (a.g <= b) {
            b -= a.g;
            var c = Math.floor(b / 8);
            b -= c * 8;
            a.g -= c;
            fk(a);
          }
          a.h <<= b;
          a.g -= b;
        }
        function hk(a, b) {
          var c = Math.min(a.g, b), d2 = a.h >>> 32 - c;
          a.g -= c;
          a.g > 0 ? a.h <<= c : a.i > 0 && fk(a);
          c = b - c;
          return c > 0 ? d2 << c | hk(a, c) : d2;
        }
        function ik(a) {
          var b;
          for (b = 0; b < a.g; ++b) if ((a.h & 2147483648 >>> b) !== 0) return a.h <<= b, a.g -= b, b;
          fk(a);
          return b + ik(a);
        }
        function jk(a) {
          gk(a, 1 + ik(a));
        }
        function X(a) {
          var b = ik(a);
          return hk(a, b + 1) - 1;
        }
        function kk(a) {
          a = X(a);
          return 1 & a ? 1 + a >>> 1 : -1 * (a >>> 1);
        }
        function lk(a) {
          return hk(a, 1) === 1;
        }
        function mk(a) {
          return hk(a, 8);
        }
        function nk(a, b) {
          for (var c = 8, d2 = 8, e = 0; e < b; e++) d2 !== 0 && (d2 = kk(a), d2 = (c + d2 + 256) % 256), c = d2 === 0 ? c : d2;
        }
        function ok(a) {
          mk(a);
          X(a);
          return X(a);
        }
        S("shaka.util.ExpGolomb", ek);
        function pk() {
          this.I = null;
          this.J = false;
          this.m = this.K = null;
          this.j = [];
          this.g = [];
          this.D = this.F = null;
          this.i = [];
          this.h = [];
          this.G = null;
          this.l = [];
          this.C = this.H = this.u = this.A = null;
        }
        p = pk.prototype;
        p.clearData = function() {
          this.j = [];
          this.g = [];
          this.i = [];
          this.h = [];
          this.l = [];
        };
        p.gg = function(a) {
          this.C != null && this.C != a && (this.u = this.A = null);
          this.C = a;
        };
        p.parse = function(a) {
          if (a.length < 564) return this;
          for (var b = Math.max(0, qk(a)), c = a.length - (a.length + b) % 188, d2 = false, e = b; e < c; e += 188) if (a[e] == 71) {
            var f = !!(a[e + 1] & 64), g = ((a[e + 1] & 31) << 8) + a[e + 2];
            if ((a[e + 3] & 48) >> 4 > 1) {
              var h = e + 5 + a[e + 4];
              if (h == e + 188) continue;
            } else h = e + 4;
            switch (g) {
              case 0:
                f && (h += a[h] + 1);
                this.I = (a[h + 10] & 31) << 8 | a[h + 11];
                break;
              case 17:
              case 8191:
                break;
              case this.I:
                f && (h += a[h] + 1);
                f = a;
                g = {
                  audio: -1,
                  video: -1,
                  yf: -1,
                  audioCodec: "",
                  videoCodec: ""
                };
                var k2 = h + 3 + ((f[h + 1] & 15) << 8 | f[h + 2]) - 4;
                for (h += 12 + ((f[h + 10] & 15) << 8 | f[h + 11]); h < k2; ) {
                  var l = (f[h + 1] & 31) << 8 | f[h + 2], m = (f[h + 3] & 15) << 8 | f[h + 4];
                  switch (f[h]) {
                    case 6:
                      if (m > 0) for (var n = h + 5, q = m; q > 2; ) {
                        var r2 = f[n + 1] + 2;
                        switch (f[n]) {
                          case 5:
                            var u = Zb(f.subarray(n + 2, n + r2));
                            g.audio == -1 && u === "Opus" ? (g.audio = l, g.audioCodec = "opus") : g.video == -1 && u === "AV01" && (g.video = l, g.videoCodec = "av1");
                            break;
                          case 106:
                            g.audio == -1 && (g.audio = l, g.audioCodec = "ac3");
                            break;
                          case 122:
                            g.audio == -1 && (g.audio = l, g.audioCodec = "ec3");
                            break;
                          case 124:
                            g.audio == -1 && (g.audio = l, g.audioCodec = "aac");
                            break;
                          case 127:
                            g.audioCodec == "opus" && (u = null, f[n + 2] === 128 && (u = f[n + 3]), u != null && (this.H = {
                              channelCount: (u & 15) === 0 ? 2 : u & 15,
                              pk: u,
                              sampleRate: 48e3
                            }));
                        }
                        n += r2;
                        q -= r2;
                      }
                      break;
                    case 15:
                      g.audio == -1 && (g.audio = l, g.audioCodec = "aac");
                      break;
                    case 17:
                      g.audio == -1 && (g.audio = l, g.audioCodec = "aac-loas");
                      break;
                    case 21:
                      g.yf == -1 && (g.yf = l);
                      break;
                    case 27:
                      g.video == -1 && (g.video = l, g.videoCodec = "avc");
                      break;
                    case 3:
                    case 4:
                      g.audio == -1 && (g.audio = l, g.audioCodec = "mp3");
                      break;
                    case 36:
                      g.video == -1 && (g.video = l, g.videoCodec = "hvc");
                      break;
                    case 129:
                      g.audio == -1 && (g.audio = l, g.audioCodec = "ac3");
                      break;
                    case 132:
                    case 135:
                      g.audio == -1 && (g.audio = l, g.audioCodec = "ec3");
                  }
                  h += m + 5;
                }
                f = g;
                f.video != -1 && (this.K = f.video, this.m = f.videoCodec);
                f.audio != -1 && (this.F = f.audio, this.D = f.audioCodec);
                f.yf != -1 && (this.G = f.yf);
                d2 && !this.J && (d2 = false, e = b - 188);
                this.J = true;
                break;
              case this.K:
                h = a.subarray(h, e + 188);
                f ? this.j.push([h]) : this.j.length && this.j[this.j.length - 1] && this.j[this.j.length - 1].push(h);
                break;
              case this.F:
                h = a.subarray(h, e + 188);
                f ? this.i.push([h]) : this.i.length && this.i[this.i.length - 1] && this.i[this.i.length - 1].push(h);
                break;
              case this.G:
                h = a.subarray(h, e + 188);
                f ? this.l.push([h]) : this.l.length && this.l[this.l.length - 1] && this.l[this.l.length - 1].push(h);
                break;
              default:
                d2 = true;
            }
          }
          return this;
        };
        function rk(a, b) {
          if ((b[0] << 16 | b[1] << 8 | b[2]) !== 1) return null;
          var c = {
            data: new Uint8Array(0),
            packetLength: b[4] << 8 | b[5],
            pts: null,
            dts: null,
            nalus: []
          };
          if (c.packetLength && c.packetLength > b.byteLength - 6) return null;
          var d2 = b[7];
          if (d2 & 192) {
            var e = (b[9] & 14) * 536870912 + (b[10] & 255) * 4194304 + (b[11] & 254) * 16384 + (b[12] & 255) * 128 + (b[13] & 254) / 2;
            a.A == null && (a.A = e);
            c.pts = sk(e, a.A);
            a.A = c.pts;
            c.dts = c.pts;
            d2 & 64 && (d2 = (b[14] & 14) * 536870912 + (b[15] & 255) * 4194304 + (b[16] & 254) * 16384 + (b[17] & 255) * 128 + (b[18] & 254) / 2, a.u == null && (a.u = d2), c.dts = c.pts != e ? sk(d2, a.u) : d2);
            a.u = c.dts;
          }
          a = b[8] + 9;
          if (b.byteLength <= a) return null;
          c.data = b.subarray(a);
          return c;
        }
        p.Vl = function(a) {
          Wc("TsParser.parseAvcNalus", "Please use parseNalus function instead.");
          return this.Ph(a, {
            xe: null,
            state: null
          });
        };
        p.Ph = function(a, b) {
          var c = a.pts ? a.pts / 9e4 : null;
          a = a.data;
          var d2 = a.byteLength, e = 1;
          this.m == "hvc" && (e = 2);
          var f = b.state || 0, g = f, h = 0, k2 = [], l = -1, m = 0;
          f == -1 && (l = 0, m = this.m == "hvc" ? a[0] >> 1 & 63 : a[0] & 31, f = 0, h = 1);
          for (; h < d2; ) {
            var n = a[h++];
            if (f) {
              if (f === 1) f = n ? 0 : 2;
              else if (n) {
                if (n == 1) {
                  n = h - f - 1;
                  if (l >= 0) k2.push({
                    data: a.subarray(l + e, n),
                    fullData: a.subarray(l, n),
                    type: m,
                    time: c,
                    state: null
                  });
                  else if (f = k2.length ? k2[k2.length - 1] : b.xe) g && h <= 4 - g && f.state && (f.data = f.data.subarray(0, f.data.byteLength - g), f.fullData = f.fullData.subarray(0, f.fullData.byteLength - g)), n > 0 && (n = a.subarray(0, n), f.data = mc(f.data, n), f.fullData = mc(f.fullData, n), f.state = 0);
                  h < d2 ? (m = this.m == "hvc" ? a[h] >> 1 & 63 : a[h] & 31, l = h, f = 0) : f = -1;
                } else f = 0;
              } else f = 3;
            } else f = n ? 0 : 1;
          }
          l >= 0 && f >= 0 && k2.push({
            data: a.subarray(l + e, d2),
            fullData: a.subarray(l, d2),
            type: m,
            time: c,
            state: f
          });
          !k2.length && b.xe && (c = k2.length ? k2[k2.length - 1] : b.xe) && (c.data = mc(c.data, a), c.fullData = mc(c.fullData, a));
          b.state = f;
          return k2;
        };
        p.getMetadata = function() {
          for (var a = [], b = t2(this.l), c = b.next(); !c.done; c = b.next()) c = mc.apply(ec, x(c.value)), (c = rk(this, c)) && a.push({
            cueTime: c.pts ? c.pts / 9e4 : null,
            data: c.data,
            frames: bk(c.data),
            dts: c.dts,
            pts: c.pts
          });
          return a;
        };
        p.Bb = function() {
          if (this.i.length && !this.h.length) for (var a = t2(this.i), b = a.next(); !b.done; b = a.next()) {
            var c = mc.apply(ec, x(b.value)), d2 = rk(this, c);
            b = this.h.length ? this.h[this.h.length - 1] : null;
            d2 && d2.pts != null && d2.dts != null && (!b || b.pts != d2.pts && b.dts != d2.dts) ? this.h.push(d2) : this.h.length && (c = d2 ? d2.data : c) && (b = this.h.pop(), b.data = mc(b.data, c), this.h.push(b));
          }
          return this.h;
        };
        p.hd = function(a) {
          a = a === void 0 ? true : a;
          if (this.j.length && !this.g.length) {
            for (var b = t2(this.j), c = b.next(); !c.done; c = b.next()) {
              var d2 = mc.apply(ec, x(c.value)), e = rk(this, d2);
              c = this.g.length ? this.g[this.g.length - 1] : null;
              e && e.pts != null && e.dts != null && (!c || c.pts != e.pts && c.dts != e.dts) ? this.g.push(e) : this.g.length && (d2 = e ? e.data : d2) && (c = this.g.pop(), c.data = mc(c.data, d2), this.g.push(c));
            }
            if (a) {
              b = {
                xe: null,
                state: null
              };
              c = [];
              d2 = t2(this.g);
              for (e = d2.next(); !e.done; e = d2.next()) e = e.value, e.nalus = this.Ph(e, b), e.nalus.length && (c.push(e), b.xe = e.nalus[e.nalus.length - 1]);
              this.g = c;
            }
          }
          return a ? this.g : (a = this.g, this.g = [], a);
        };
        p.getStartTime = function(a) {
          if (a == "audio") {
            a = null;
            var b = this.Bb();
            b.length && (a = b[0], a = Math.min(a.dts, a.pts) / 9e4);
            return a;
          }
          return a == "video" ? (a = null, b = this.hd(false), b.length && (a = b[0], a = Math.min(a.dts, a.pts) / 9e4), a) : null;
        };
        p.je = function() {
          return {
            audio: this.D,
            video: this.m
          };
        };
        p.xf = function() {
          for (var a = [], b = t2(this.hd()), c = b.next(); !c.done; c = b.next()) a.push.apply(a, x(c.value.nalus));
          return a;
        };
        p.xl = function() {
          Wc("TsParser.getVideoResolution", "Please use getVideoInfo function instead.");
          var a = this.xh();
          return {
            height: a.height,
            width: a.width
          };
        };
        p.xh = function() {
          return this.m == "hvc" ? tk(this) : uk(this);
        };
        function vk(a) {
          var b = a.hd();
          return b.length > 1 && (a = b[0].pts, b = b[1].pts, !isNaN(b - a)) ? String(1 / (b - a) * 9e4) : null;
        }
        function uk(a) {
          var b = {
            height: null,
            width: null,
            codec: null,
            frameRate: null
          }, c = a.xf();
          if (!c.length) return b;
          c = c.find(function(r2) {
            return r2.type == 7;
          });
          if (!c) return b;
          c = new ek(c.data);
          var d2 = mk(c), e = mk(c), f = mk(c);
          jk(c);
          if (wk.includes(d2)) {
            var g = X(c);
            g === 3 && gk(c, 1);
            jk(c);
            jk(c);
            gk(c, 1);
            if (lk(c)) {
              g = g !== 3 ? 8 : 12;
              for (var h = 0; h < g; h++) lk(c) && (h < 6 ? nk(c, 16) : nk(c, 64));
            }
          }
          jk(c);
          g = X(c);
          if (g === 0) X(c);
          else if (g === 1) for (gk(c, 1), jk(c), jk(c), g = X(c), h = 0; h < g; h++) jk(c);
          jk(c);
          gk(c, 1);
          g = X(c);
          h = X(c);
          var k2 = hk(c, 1);
          k2 === 0 && gk(c, 1);
          gk(c, 1);
          var l = 0, m = 0, n = 0, q = 0;
          lk(c) && (l = X(c), m = X(c), n = X(c), q = X(c));
          b.height = String((2 - k2) * (h + 1) * 16 - n * 2 - q * 2);
          b.width = String((g + 1) * 16 - l * 2 - m * 2);
          b.codec = "avc1." + ("0" + d2.toString(16).toUpperCase()).slice(-2) + ("0" + e.toString(16).toUpperCase()).slice(-2) + ("0" + f.toString(16).toUpperCase()).slice(-2);
          b.frameRate = vk(a);
          return b;
        }
        function tk(a) {
          var b = {
            height: null,
            width: null,
            codec: null,
            frameRate: null
          }, c = a.xf();
          if (!c.length) return b;
          c = c.find(function(D) {
            return D.type == 33;
          });
          if (!c) return b;
          var d2 = new ek(c.fullData, true);
          mk(d2);
          mk(d2);
          hk(d2, 4);
          var e = hk(d2, 3);
          lk(d2);
          var f = hk(d2, 2), g = hk(d2, 1), h = hk(d2, 5), k2 = hk(d2, 32);
          c = mk(d2);
          for (var l = mk(d2), m = mk(d2), n = mk(d2), q = mk(d2), r2 = mk(d2), u = mk(d2), w = [], v = [], y = 0; y < e; y++) w.push(lk(d2)), v.push(lk(d2));
          if (e > 0) for (y = e; y < 8; y++) hk(d2, 2);
          for (y = 0; y < e; y++) w[y] && hk(d2, 88), v[y] && mk(d2);
          X(d2);
          e = X(d2);
          e == 3 && hk(d2, 1);
          w = X(d2);
          v = X(d2);
          var z = y = 0, A = 0, C = 0;
          lk(d2) && (y += X(d2), z += X(d2), A += X(d2), C += X(d2));
          b.width = String(w - (y + z) * (e === 1 || e === 2 ? 2 : 1));
          b.height = String(v - (A + C) * (e === 1 ? 2 : 1));
          d2 = function(D) {
            for (var F = 0, B = 0; B < 32; B++) F |= (D >> B & 1) << 31 - B;
            return F >>> 0;
          }(k2);
          g = g == 1 ? "H" : "L";
          f = "hvc1" + ("." + ["", "A", "B", "C"][f] + h);
          f += "." + d2.toString(16).toUpperCase();
          f += "." + g + u;
          r2 && (f += "." + r2.toString(16).toUpperCase());
          q && (f += "." + q.toString(16).toUpperCase());
          n && (f += "." + n.toString(16).toUpperCase());
          m && (f += "." + m.toString(16).toUpperCase());
          l && (f += "." + l.toString(16).toUpperCase());
          c && (f += "." + c.toString(16).toUpperCase());
          b.codec = f;
          b.frameRate = vk(a);
          return b;
        }
        function sk(a, b) {
          var c = 1;
          for (a > b && (c = -1); Math.abs(b - a) > 4294967296; ) a += c * 8589934592;
          return a;
        }
        function xk(a) {
          return qk(a) < 0 ? false : true;
        }
        function qk(a) {
          for (var b = Math.min(1e3, a.length - 564), c = 0; c < b; ) {
            if (a[c] == 71 && a[c + 188] == 71 && a[c + 376] == 71) return c;
            c++;
          }
          return -1;
        }
        S("shaka.util.TsParser", pk);
        pk.syncOffset = qk;
        pk.probe = xk;
        pk.prototype.getVideoInfo = pk.prototype.xh;
        pk.prototype.getVideoResolution = pk.prototype.xl;
        pk.prototype.getVideoNalus = pk.prototype.xf;
        pk.prototype.getCodecs = pk.prototype.je;
        pk.prototype.getStartTime = pk.prototype.getStartTime;
        pk.prototype.getVideoData = pk.prototype.hd;
        pk.prototype.getAudioData = pk.prototype.Bb;
        pk.prototype.getMetadata = pk.prototype.getMetadata;
        pk.prototype.parseNalus = pk.prototype.Ph;
        pk.prototype.parseAvcNalus = pk.prototype.Vl;
        pk.prototype.parse = pk.prototype.parse;
        pk.prototype.setDiscontinuitySequence = pk.prototype.gg;
        pk.prototype.clearData = pk.prototype.clearData;
        pk.Timescale = 9e4;
        var wk = [100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134];
        function yk(a, b, c, d2, e) {
          var f = this;
          this.g = a;
          this.O = c;
          this.C = d2;
          this.$ = b;
          this.l = /* @__PURE__ */ new Map();
          this.F = /* @__PURE__ */ new Map();
          this.Ma = /* @__PURE__ */ new Map();
          this.h = null;
          this.Ia = false;
          this.M = e || null;
          this.u = /* @__PURE__ */ new Map();
          this.A = new Qc();
          this.j = /* @__PURE__ */ new Map();
          this.J = null;
          this.K = new Mg();
          this.va = "";
          this.fb = false;
          this.ua = true;
          this.L = false;
          this.D = this.P = null;
          this.i = zk(this, this.K);
          this.hb = this.G = false;
          this.I = new ih(function() {
            return Ak(f);
          });
          this.H = false;
          this.V = "UNKNOWN";
          this.Va = this.Za = false;
          this.Oa = new Mg();
          this.m = false;
          this.sa = null;
          this.Z = /* @__PURE__ */ new Map();
          this.ea = this.R = this.oa = this.S = null;
          this.aa = new Mg();
          this.g.remote && (this.L = this.g.remote.state != "disconnected", this.A.o(this.g.remote, "connect", function() {
            f.L = f.g.remote.state != "disconnected";
          }), this.A.o(this.g.remote, "connecting", function() {
            f.L = f.g.remote.state != "disconnected";
          }), this.A.o(this.g.remote, "disconnect", function() {
            f.L = f.g.remote.state != "disconnected";
          }));
        }
        function zk(a, b) {
          a.ua = true;
          if (window7.ManagedMediaSource) {
            a.D || (a.g.disableRemotePlayback = true);
            var c = new ManagedMediaSource();
            a.A.o(c, "startstreaming", function() {
              a.ua = true;
            });
            a.A.o(c, "endstreaming", function() {
              a.ua = false;
            });
          } else c = new MediaSource();
          a.A.qa(c, "sourceopen", function() {
            URL.revokeObjectURL(a.va);
            b.resolve();
          });
          a.A.qa(a.g, "playing", function() {
            a.fb = true;
          });
          a.va = Bk(c);
          a.C.useSourceElements ? (a.g.removeAttribute("src"), a.P && a.g.removeChild(a.P), a.D && a.g.removeChild(a.D), a.P = Pj(a.va), a.g.appendChild(a.P), a.D && a.g.appendChild(a.D), a.g.load()) : a.g.src = a.va;
          return c;
        }
        function Ck(a, b, c) {
          a.g && window7.ManagedMediaSource && a.i && a.C.useSourceElements && (a.D && a.g.removeChild(a.D), a.D = Pj(b, c), a.g.appendChild(a.D), a.g.disableRemotePlayback = false);
        }
        function Ek() {
          var a = 'video/mp4; codecs="avc1.42E01E",video/mp4; codecs="avc3.42E01E",video/mp4; codecs="hev1.1.6.L93.90",video/mp4; codecs="hvc1.1.6.L93.90",video/mp4; codecs="hev1.2.4.L153.B0"; eotf="smpte2084",video/mp4; codecs="hvc1.2.4.L153.B0"; eotf="smpte2084",video/mp4; codecs="vp9",video/mp4; codecs="vp09.00.10.08",video/mp4; codecs="av01.0.01M.08",video/mp4; codecs="dvh1.05.01",video/mp4; codecs="dvh1.20.01",audio/mp4; codecs="mp4a.40.2",audio/mp4; codecs="ac-3",audio/mp4; codecs="ec-3",audio/mp4; codecs="ac-4.02.01.01",audio/mp4; codecs="opus",audio/mp4; codecs="flac",audio/mp4; codecs="dtsc",audio/mp4; codecs="dtse",audio/mp4; codecs="dtsx",audio/mp4; codecs="apac.31.00",video/webm; codecs="vp8",video/webm; codecs="vp9",video/webm; codecs="vp09.00.10.08",audio/webm; codecs="vorbis",audio/webm; codecs="opus",video/mp2t; codecs="avc1.42E01E",video/mp2t; codecs="avc3.42E01E",video/mp2t; codecs="hvc1.1.6.L93.90",video/mp2t; codecs="mp4a.40.2",video/mp2t; codecs="ac-3",video/mp2t; codecs="ec-3",text/vtt,application/mp4; codecs="wvtt",application/ttml+xml,application/mp4; codecs="stpp"'.split(",").concat(x(ff)), b = {};
          Sb();
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) {
            c = c.value;
            vf(c) ? b[c] = true : b[c] = Ji() ? dd(c) || (Ze(c) ? true : false) : Ki().canPlayType(c) != "";
            var d2 = c.split(";")[0];
            b[d2] = b[d2] || b[c];
          }
          return b;
        }
        p = yk.prototype;
        p.destroy = function() {
          return this.I.destroy();
        };
        function Ak(a) {
          var b, c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w;
          return P(function(v) {
            if (v.g == 1) {
              b = [];
              c = t2(a.u);
              for (d2 = c.next(); !d2.done; d2 = c.next()) for (e = d2.value, f = t2(e), g = f.next().value, h = f.next().value, k2 = h[0], l = g, a.u.set(l, h.slice(0, 1)), k2 && b.push(k2.p.catch(Ef)), m = t2(h.slice(1)), n = m.next(); !n.done; n = m.next()) q = n.value, q.p.reject(new U(2, 7, 7003, void 0));
              a.h && b.push(a.h.destroy());
              return G(v, Promise.all(b), 2);
            }
            r2 = t2(a.j.values());
            for (u = r2.next(); !u.done; u = r2.next()) w = u.value, w.destroy();
            a.A && (a.A.release(), a.A = null);
            a.g && a.D && a.g.removeChild(a.D);
            a.g && a.P && (a.g.removeChild(a.P), a.g.load(), a.g.disableRemotePlayback = false);
            a.g = null;
            a.P = null;
            a.D = null;
            a.C = null;
            a.i = null;
            a.h = null;
            a.$ = null;
            a.l.clear();
            a.Ma.clear();
            a.j.clear();
            a.J = null;
            a.u.clear();
            a.M = null;
            a.Z.clear();
            a.O = null;
            H(v);
          });
        }
        p.init = function(a, b, c, d2) {
          b = b === void 0 ? false : b;
          c = c === void 0 ? "UNKNOWN" : c;
          d2 = d2 === void 0 ? false : d2;
          var e = this, f, g, h, k2, l, m;
          return P(function(n) {
            if (n.g == 1) return f = vc, G(n, e.K, 2);
            if (n.g != 3) {
              if (!Fk(e) && !Gk(e)) return n.B(3);
              ab("Expected MediaSource to be open during init(); reopening the media source.");
              e.K = new Mg();
              e.i = zk(e, e.K);
              return G(n, e.K, 3);
            }
            e.H = b;
            e.V = c;
            e.Za = d2;
            e.Va = !e.H && e.V == "HLS" && !e.Za;
            e.Z.clear();
            e.S = null;
            e.oa = null;
            e.R = null;
            e.ea = null;
            e.aa = new Mg();
            g = t2(a.keys());
            for (h = g.next(); !h.done; h = g.next()) k2 = h.value, l = a.get(k2), Hk(e, k2, l, l.codecs), e.m ? (e.u.set(f.na, []), e.u.set(f.Ja, [])) : e.u.set(k2, []);
            (m = a.get(f.na)) && m.isAudioMuxedInVideo && (e.m = true);
            H(n);
          });
        };
        function Hk(a, b, c, d2) {
          b == "audio" && d2 && (d2 = Yf(d2, c.mimeType));
          var e = ef(c.mimeType, d2);
          if (b == tc) Ik(a, e, a.H, c.external);
          else {
            var f = a.C.forceTransmux;
            if (!dd(e) || !a.H && ff.includes(e)) f = true;
            var g = gf(c.mimeType, d2);
            if (f) {
              f = rc("audio", (d2 || "").split(","));
              d2 = rc("video", (d2 || "").split(","));
              if (f && d2) {
                a.m = true;
                Hk(a, "audio", c, f);
                Hk(a, "video", c, d2);
                return;
              }
              if (d2 = Ze(g)) e = d2(), a.j.set(b, e), e = e.convertCodecs(b, g);
            }
            g = e + a.C.addExtraFeaturesToSourceBuffer(e);
            jh(a.I);
            try {
              var h = a.i.addSourceBuffer(g);
            } catch (k2) {
              throw new U(2, 3, 3015, k2, "The mediaSource_ status was " + a.i.readyState + " expected 'open'", null);
            }
            a.H && (h.mode = Jk);
            a.A.o(h, "error", function() {
              var k2 = a.u.get(b)[0];
              k2.p.reject(new U(2, 3, 3014, a.g.error ? a.g.error.code : 0, k2.uri));
            });
            a.A.o(h, "updateend", function() {
              return Kk(a, b);
            });
            a.l.set(b, h);
            a.F.set(b, e);
            a.Ma.set(b, !!c.drmInfos.length);
          }
        }
        p.configure = function(a) {
          this.C = a;
          this.h && (this.h.C = a.modifyCueCallback);
        };
        function Lk(a) {
          return a.ua && !a.L && !a.G;
        }
        function Ik(a, b, c, d2) {
          a.h || (a.h = new qf(a.$), a.h && (a.h.C = a.C.modifyCueCallback));
          var e = a.h;
          d2 = d2 || a.Ia;
          a = a.V;
          b == "application/cea-608" || b == "application/cea-708" ? e.i = null : (e.i = tf.get(b)(), e.i.setSequenceMode ? e.i.setSequenceMode(c) : Wc("Text parsers w/ setSequenceMode", 'Text parsers should have a "setSequenceMode" method!'), e.i.setManifestType ? e.i.setManifestType(a) : Wc("Text parsers w/ setManifestType", 'Text parsers should have a "setManifestType" method!'), e.D = d2);
        }
        function Fk(a) {
          return a.G ? false : a.i ? a.i.readyState == "ended" : true;
        }
        function Gk(a) {
          return a.G ? false : a.i ? a.i.readyState == "closed" : true;
        }
        function Mk(a, b) {
          return a.l.size ? b == tc ? a.h.g : Hj(Nk(a, b)) : null;
        }
        function Ok(a, b) {
          return a.l.size ? b == tc ? a.h.h : Ij(Nk(a, b)) : null;
        }
        function Pk(a, b, c) {
          if (b == tc) return a = a.h, a.h == null || a.h < c ? 0 : a.h - Math.max(c, a.g);
          a = Nk(a, b);
          return Kj(a, c);
        }
        p.cc = function() {
          var a = {
            total: this.G ? [] : Lj(this.g.buffered),
            audio: Lj(Nk(this, "audio")),
            video: Lj(Nk(this, "video")),
            text: []
          };
          if (this.h) {
            var b = this.h.g, c = this.h.h;
            b != null && c != null && a.text.push({
              start: b,
              end: c
            });
          }
          return a;
        };
        function Nk(a, b) {
          if (a.G || a.L) return null;
          try {
            return a.l.get(b).buffered;
          } catch (c) {
            return a.l.has(b), null;
          }
        }
        function Qk(a, b, c, d2, e, f) {
          var g = null, h = [], k2 = Lb(c);
          if (ff.includes(f)) b = bk(k2), b.length && d2 && ((c = b.find(function(r2) {
            return r2.description === "com.apple.streaming.transportStreamTimestamp";
          })) && typeof c.data == "number" && (g = Math.round(c.data) / 1e3), a.O.onMetadata([{
            cueTime: d2.startTime,
            data: k2,
            frames: b,
            dts: d2.startTime,
            pts: d2.startTime
          }], 0, d2.endTime));
          else if (f.includes("/mp4") && d2 && d2.ha && d2.ha.timescale) {
            var l = d2.ha.timescale;
            if (!isNaN(l)) {
              var m = e.emsgSchemeIdUris != null && e.emsgSchemeIdUris.length > 0 || a.C.dispatchAllEmsgBoxes, n = 0, q = false;
              k2 = new ph();
              m && k2.W("emsg", function(r2) {
                var u = e.emsgSchemeIdUris;
                if (r2.version === 0) {
                  var w = r2.reader.nd();
                  var v = r2.reader.nd();
                  var y = r2.reader.X();
                  var z = r2.reader.X();
                  var A = r2.reader.X();
                  var C = r2.reader.X();
                  var D = d2.startTime + z / y;
                } else y = r2.reader.X(), D = r2.reader.Qd() / y + d2.timestampOffset, z = D - d2.startTime, A = r2.reader.X(), C = r2.reader.X(), w = r2.reader.nd(), v = r2.reader.nd();
                r2 = r2.reader.$b(r2.reader.getLength() - r2.reader.Ua());
                if (u && u.includes(w) || a.C.dispatchAllEmsgBoxes) {
                  if (w == "urn:mpeg:dash:event:2012") a.O.Ul();
                  else if (u = D + A / y, a.O.Sl({
                    startTime: D,
                    endTime: u,
                    schemeIdUri: w,
                    value: v,
                    timescale: y,
                    presentationTimeDelta: z,
                    eventDuration: A,
                    id: C,
                    messageData: r2
                  }), w == "https://aomedia.org/emsg/ID3" || w == "https://developer.apple.com/streaming/emsg-id3") {
                    if (y = bk(r2), y.length) a.O.onMetadata([{
                      cueTime: D,
                      data: r2,
                      frames: y,
                      dts: D,
                      pts: D
                    }], 0, u);
                  }
                }
              });
              k2.W("prft", function(r2) {
                var u = r2.reader, w = r2.version;
                u.X();
                r2 = u.X();
                var v = u.X();
                r2 = r2 * 1e3 + v / 4294967296 * 1e3;
                w === 0 ? u = u.X() : (w = u.X(), u = u.X(), u = w * 4294967296 + u);
                r2 = dk(r2);
                u = (/* @__PURE__ */ new Map()).set("detail", {
                  wallClockTime: r2,
                  programStartDate: new Date(r2 - u / l * 1e3)
                });
                u = new T("prft", u);
                a.O.onEvent(u);
              }).box("moof", uh).box("traf", uh).W("tfdt", function(r2) {
                q || (n = Ni(r2.reader, r2.version).baseMediaDecodeTime / l, q = true, m || r2.parser.stop());
              }).parse(c, true);
              q && d2.timestampOffset == 0 && (g = n);
            }
          } else f.includes("/mp4") || f.includes("/webm") || !xk(k2) || (a.Z.has(b) || a.Z.set(b, new pk()), h = a.Z.get(b), h.clearData(), h.gg(d2.i), h.parse(k2), k2 = h.getStartTime(b), k2 != null && (g = k2), h = h.getMetadata());
          return {
            timestamp: g,
            metadata: h
          };
        }
        function Rk(a, b, c, d2, e, f, g, h, k2, l, m) {
          g = g === void 0 ? false : g;
          h = h === void 0 ? false : h;
          k2 = k2 === void 0 ? false : k2;
          l = l === void 0 ? false : l;
          var n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L;
          return P(function(M) {
            switch (M.g) {
              case 1:
                n = vc;
                if (b != n.ab) {
                  M.B(2);
                  break;
                }
                if (a.V != "HLS") {
                  M.B(3);
                  break;
                }
                return G(M, a.Oa, 4);
              case 4:
                q = M.h, a.h.A = q;
              case 3:
                return G(M, wf(a.h, c, d2 ? d2.startTime : null, d2 ? d2.endTime : null, d2 ? d2.T()[0] : null), 5);
              case 5:
                return M.return();
              case 2:
                if (l || !a.m) {
                  M.B(6);
                  break;
                }
                return G(M, Rk(a, n.na, c, d2, e, f, g, h, k2, true), 7);
              case 7:
                return G(M, Rk(a, n.Ja, c, d2, e, f, g, h, k2, true), 8);
              case 8:
                return M.return();
              case 6:
                if (!a.l.has(b)) return M.return();
                r2 = a.l.get(b).timestampOffset;
                u = a.F.get(b);
                a.j.has(b) && (u = a.j.get(b).getOriginalMimeType());
                if (d2 && (w = Qk(a, b, c, d2, e, u), v = w.timestamp, y = w.metadata, v != null && (a.S == null && b == n.Ja && (a.S = v, a.oa = d2.startTime, a.R != null && (z = 0, a.oa == a.ea && (z = a.S - a.R), a.aa.resolve(z))), a.R == null && b == n.na && (a.R = v, a.ea = d2.startTime, a.S != null && (A = 0, a.oa == a.ea && (A = a.S - a.R), a.aa.resolve(A))), C = v, D = ff, !a.H && D.includes(a.F.get(b)) && (C = 0), F = d2.startTime - C, B = Math.abs(r2 - F), (B >= 1e-3 || g || h) && (!k2 || F > 0 || !r2) && (r2 = F, a.Va && (Sk(a, b, function() {
                  return Tk(a, b);
                }, null), Sk(a, b, function() {
                  return Uk(a, b, r2);
                }, null))), (E = b == n.Ja || !a.l.has(n.Ja)) && a.Oa.resolve(r2)), y.length)) a.O.onMetadata(y, r2, d2 ? d2.endTime : null);
                f && b == n.Ja && (a.h || Ik(a, "application/cea-608", a.H, false), a.J || (I = u.split(";", 1)[0], a.J = new ld(I)), d2 ? (J = a.J.Tf(c), J.length && Af(a.h, J, d2.startTime, d2.endTime, r2)) : a.J.init(c, h, m));
                if (!a.j.has(b)) {
                  M.B(9);
                  break;
                }
                return G(M, a.j.get(b).transmux(c, e, d2, a.i.duration, b), 10);
              case 10:
                c = M.h;
              case 9:
                c = Vk(a, e, c, d2, b);
                if (!d2 || !a.H || b == n.ab) {
                  M.B(11);
                  break;
                }
                if (!g && !h) {
                  M.B(11);
                  break;
                }
                K = d2.startTime;
                if (a.V != "HLS" || a.m || b != n.na || !a.l.has(n.Ja)) {
                  M.B(13);
                  break;
                }
                return G(M, a.aa, 14);
              case 14:
                L = M.h, Math.abs(L) > 0.15 && (K -= L);
              case 13:
                Sk(a, b, function() {
                  return Tk(a, b);
                }, null), Sk(a, b, function() {
                  return Uk(a, b, K);
                }, null);
              case 11:
                return G(M, Sk(a, b, function() {
                  var N = c;
                  a.M && ad(a.M, N, r2, e);
                  a.l.get(b).appendBuffer(N);
                }, d2 ? d2.T()[0] : null), 15);
              case 15:
                H(M);
            }
          });
        }
        function Wk(a, b) {
          var c = Ok(a, "video") || 0;
          yf(a.h, b, c);
        }
        function Xk(a) {
          a.h && yf(a.h, "", 0);
        }
        p.remove = function(a, b, c, d2) {
          var e = this, f;
          return P(function(g) {
            return g.g == 1 ? (f = vc, a == f.Ja && e.J && e.J.remove(d2), a == f.ab ? G(g, e.h.remove(b, c), 0) : c > b ? G(g, Sk(e, a, function() {
              return Yk(e, a, b, c);
            }, null), 5) : g.B(0)) : e.m ? G(g, Sk(e, f.na, function() {
              return Yk(e, f.na, b, c);
            }, null), 0) : g.B(0);
          });
        };
        function Zk(a, b) {
          var c;
          return P(function(d2) {
            return d2.g == 1 ? (c = vc, b == c.ab ? a.h ? G(d2, a.h.remove(0, Infinity), 0) : d2.return() : G(d2, Sk(a, b, function() {
              return Yk(a, b, 0, a.i.duration);
            }, null), 4)) : a.m ? G(d2, Sk(a, c.na, function() {
              return Yk(a, c.na, 0, a.i.duration);
            }, null), 0) : d2.B(0);
          });
        }
        p.flush = function(a) {
          var b = this, c;
          return P(function(d2) {
            return d2.g == 1 ? (c = vc, a == c.ab ? d2.return() : G(d2, Sk(b, a, function() {
              b.g.currentTime -= 1e-3;
              Kk(b, a);
            }, null), 2)) : b.m ? G(d2, Sk(b, c.na, function() {
              var e = c.na;
              b.g.currentTime -= 1e-3;
              Kk(b, e);
            }, null), 0) : d2.B(0);
          });
        };
        function $k(a, b, c, d2, e, f, g, h, k2) {
          var l, m, n;
          return P(function(q) {
            if (q.g == 1) {
              l = vc;
              if (b == l.ab) return f || (a.h.A = c), xf(a.h, d2, e), q.return();
              m = [];
              return G(q, al(a, b, g, h, k2), 2);
            }
            n = q.h;
            n || (m.push(Sk(a, b, function() {
              return Tk(a, b);
            }, null)), a.m && m.push(Sk(a, l.na, function() {
              return Tk(a, l.na);
            }, null)));
            f || (m.push(Sk(a, b, function() {
              return Uk(a, b, c);
            }, null)), a.m && m.push(Sk(a, l.na, function() {
              return Uk(a, l.na, c);
            }, null)));
            if (d2 != 0 || e != Infinity) m.push(Sk(a, b, function() {
              return bl(a, b, d2, e);
            }, null)), a.m && m.push(Sk(a, l.na, function() {
              return bl(a, l.na, d2, e);
            }, null));
            return m.length ? G(q, Promise.all(m), 0) : q.B(0);
          });
        }
        function cl(a, b, c) {
          var d2, e;
          return P(function(f) {
            if (f.g == 1) {
              d2 = vc;
              if (b == d2.ab) return f.return();
              b == d2.Ja && (a.Oa = new Mg());
              if (!a.H || (e = Ok(a, b)) && Math.abs(e - c) < 0.15) return f.return();
              Sk(a, b, function() {
                return Tk(a, b);
              }, null);
              a.m && Sk(a, d2.na, function() {
                return Tk(a, d2.na);
              }, null);
              return G(f, Sk(a, b, function() {
                return Uk(a, b, c);
              }, null), 2);
            }
            return a.m ? G(f, Sk(a, d2.na, function() {
              return Uk(a, d2.na, c);
            }, null), 0) : f.B(0);
          });
        }
        p.endOfStream = function(a) {
          var b = this;
          return P(function(c) {
            return G(c, dl(b, function() {
              Fk(b) || Gk(b) || (a ? b.i.endOfStream(a) : b.i.endOfStream());
            }), 0);
          });
        };
        p.yb = function(a) {
          var b = this;
          return P(function(c) {
            return G(c, dl(b, function() {
              if (b.C.durationReductionEmitsUpdateEnd && a < b.i.duration) for (var d2 = t2(b.l.keys()), e = d2.next(); !e.done; e = d2.next()) {
                e = e.value;
                var f = {
                  start: function() {
                  },
                  p: new Mg(),
                  uri: null
                };
                b.u.get(e).unshift(f);
              }
              b.i.duration = a;
              b.sa = a;
            }), 0);
          });
        };
        p.getDuration = function() {
          return this.i.duration;
        };
        function el(a, b, c) {
          P(function(d2) {
            return a.I.g || a.g.error || a.L || a.G || Fk(a) || Gk(a) ? d2.return() : G(d2, dl(a, function() {
              Fk(a) || Gk(a) || a.i.setLiveSeekableRange(b, c);
            }), 0);
          });
        }
        function fl(a) {
          P(function(b) {
            return a.I.g || a.g.error || a.L || a.G || Fk(a) || Gk(a) ? b.return() : G(b, dl(a, function() {
              Fk(a) || Gk(a) || a.i.clearLiveSeekableRange();
            }), 0);
          });
        }
        function Yk(a, b, c, d2) {
          d2 <= c ? Kk(a, b) : a.l.get(b).remove(c, d2);
        }
        function Tk(a, b) {
          var c = a.l.get(b), d2 = c.appendWindowStart, e = c.appendWindowEnd;
          c.abort();
          c.appendWindowStart = d2;
          c.appendWindowEnd = e;
          Kk(a, b);
        }
        function Uk(a, b, c) {
          c < 0 && (c += 1e-3);
          a.l.get(b).timestampOffset = c;
          Kk(a, b);
        }
        function bl(a, b, c, d2) {
          var e = a.l.get(b);
          if (e.appendWindowEnd !== d2 || e.appendWindowStart !== c) e.appendWindowStart = 0, e.appendWindowEnd = d2, e.appendWindowStart = c;
          Kk(a, b);
        }
        function Kk(a, b) {
          if (a.G || a.I.g) {
            var c = a.u.get(b);
            c && c.length && ((c = c[0]) && c.p && c.p.resolve(), a.u.set(b, []));
          } else if (c = a.u.get(b)[0]) c.p.resolve(), gl(a, b);
        }
        function Sk(a, b, c, d2) {
          jh(a.I);
          c = {
            start: c,
            p: new Mg(),
            uri: d2
          };
          a.u.get(b).push(c);
          a.u.get(b).length == 1 && hl(a, b);
          return c.p;
        }
        function dl(a, b) {
          var c, d2, e, f, g, h, k2, l, m, n, q, r2, u;
          return P(function(w) {
            switch (w.g) {
              case 1:
                jh(a.I);
                c = [];
                d2 = Array.from(a.l.keys());
                e = t2(d2);
                f = e.next();
                for (g = {}; !f.done; g = {
                  ready: void 0
                }, f = e.next()) h = f.value, g.ready = new Mg(), k2 = {
                  start: /* @__PURE__ */ function(v) {
                    return function() {
                      return v.ready.resolve();
                    };
                  }(g),
                  p: g.ready,
                  uri: null
                }, l = a.u.get(h), l.push(k2), c.push(g.ready), l.length == 1 && k2.start();
                sa(w, 2);
                return G(w, Promise.all(c), 4);
              case 4:
                ua(w, 3);
                break;
              case 2:
                throw m = va(w), m;
              case 3:
                return sa(w, 5, 6), G(w, b(), 6);
              case 6:
                wa(w);
                n = t2(d2);
                for (q = n.next(); !q.done; q = n.next()) r2 = q.value, gl(a, r2);
                xa(w, 0);
                break;
              case 5:
                throw u = va(w), new U(2, 3, 3015, u, a.g.error || "No error in the media element", null);
            }
          });
        }
        function gl(a, b) {
          a.u.get(b).shift();
          hl(a, b);
        }
        function hl(a, b) {
          var c = a.u.get(b)[0];
          if (c) try {
            c.start();
          } catch (d2) {
            d2.name == "QuotaExceededError" ? c.p.reject(new U(2, 3, 3017, b)) : Lk(a) ? c.p.reject(new U(2, 3, 3015, d2, a.g.error || "No error in the media element", c.uri)) : c.p.reject(new U(2, 3, 3024, b)), gl(a, b);
          }
        }
        function il(a, b) {
          a.$ = b;
          a.h && (a.h.j = b);
        }
        function Vk(a, b, c, d2, e) {
          if (jf(a.F.get(e)) != "mp4") return c;
          var f = d2 === null, g = a.Ma.get(e), h = a.O.Qk(), k2 = false;
          d2 && d2.ha && (k2 = d2.ha.encrypted);
          d2 = d2 ? d2.T()[0] : null;
          var l = Sb();
          a.C.correctEc3Enca && f && e === "audio" && (c = tj(c));
          a.C.insertFakeEncryptionInInit && g && l.Rd(h, e) && (f ? c = uj(b, c, d2) : !k2 && l.zj(e) && (c = wj(c)));
          f && l.Ce() && (c = zj(c));
          return c;
        }
        function jl(a, b, c, d2) {
          return Sk(a, b, function() {
            if (b !== tc) {
              a.F.get(b);
              if (fd()) {
                a.j.has(b) && (a.j.get(b).destroy(), a.j.delete(b));
                d2 && a.j.set(b, d2);
                var e = c + a.C.addExtraFeaturesToSourceBuffer(c);
                a.l.get(b).changeType(e);
                a.F.set(b, c);
              }
              Kk(a, b);
            }
          }, null);
        }
        function kl(a, b) {
          var c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D;
          return P(function(F) {
            if (F.g == 1) {
              if (a.G || a.L) return F.return();
              c = vc;
              a.G = true;
              a.m = false;
              d2 = a.g.currentTime;
              e = a.g.autoplay;
              a.g.paused || (a.hb = true);
              a.fb && (a.g.autoplay = false);
              ta(F, 2);
              a.A.Ta();
              f = t2(a.j.values());
              for (g = f.next(); !g.done; g = f.next()) h = g.value, h.destroy();
              k2 = t2(a.l.values());
              for (l = k2.next(); !l.done; l = k2.next()) {
                m = l.value;
                try {
                  a.i.removeSourceBuffer(m);
                } catch (B) {
                }
              }
              a.j.clear();
              a.l.clear();
              n = a.i.duration;
              a.K = new Mg();
              a.i = zk(a, a.K);
              return G(F, a.K, 4);
            }
            if (F.g != 2) {
              !isNaN(n) && n ? a.i.duration = n : !isNaN(a.sa) && a.sa && (a.i.duration = a.sa);
              q = new Mg();
              r2 = a.i.sourceBuffers;
              u = b.size;
              w = 0;
              v = function() {
                w++;
                w === u && (q.resolve(), a.A.Ea(r2, "addsourcebuffer", v));
              };
              a.A.o(r2, "addsourcebuffer", v);
              y = t2(b.keys());
              for (z = y.next(); !z.done; z = y.next()) A = z.value, C = b.get(A), Hk(a, A, C, C.codecs);
              (D = b.get(c.na)) && D.isAudioMuxedInVideo && (a.m = true);
              a.m && !a.u.has(c.na) && a.u.set(c.na, []);
              a.g.currentTime = d2;
              return G(F, q, 2);
            }
            wa(F);
            a.G = false;
            jh(a.I);
            a.A.qa(a.g, "canplaythrough", function() {
              a.I.g || (a.g.autoplay = e, a.hb && (a.hb = false, a.g.play()));
            });
            return xa(F, 0);
          });
        }
        function tl(a, b) {
          return dl(a, function() {
            return kl(a, b);
          });
        }
        function ul(a, b, c, d2) {
          var e = false, f = rc("audio", (d2 || "").split(",")), g = rc("video", (d2 || "").split(",")), h = g;
          b == "audio" && (h = f);
          h || (h = d2);
          d2 = ef(c, h);
          var k2 = nf(a.F.get(b)), l = a.C.forceTransmux;
          !dd(d2) || !a.H && ff.includes(d2) ? l = true : l || c == k2 || (l = Sb().Ga() === "WEBKIT" && ff.includes(c));
          if (l && (a = gf(c, h), c = Ze(a))) {
            var m = c();
            f && g && (e = true);
            d2 = m.convertCodecs(b, a);
          }
          b = kf(of(d2));
          return {
            qc: m,
            xm: e,
            Ii: nf(d2),
            codec: b,
            mimeType: d2
          };
        }
        function vl(a, b, c, d2, e) {
          if (b == tc) return {
            type: wl,
            Nf: c,
            qc: null
          };
          var f = kf(of(a.F.get(b))), g = nf(a.F.get(b)), h = ul(a, b, c, d2), k2 = h.qc, l = h.xm, m = h.Ii, n = h.codec;
          h = h.mimeType;
          var q = true;
          l && a.F.has("audio") && (c = ul(a, "audio", c, d2), d2 = kf(of(a.F.get("audio"))), q = nf(a.F.get("audio")), q = d2 == c.codec && q == c.Ii, c.qc && c.qc.destroy());
          if (f === n && g === m && q) return {
            type: wl,
            Nf: h,
            qc: k2
          };
          f = true;
          if (a.m && !e.has("audio") || l && k2 && !a.j.has(b)) f = false;
          if (f && a.C.codecSwitchingStrategy === "smooth" && fd()) return {
            type: xl,
            Nf: h,
            qc: k2
          };
          k2 && k2.destroy();
          return {
            type: yl,
            Nf: h,
            qc: null
          };
        }
        function al(a, b, c, d2, e) {
          var f, g, h, k2, l, m;
          return P(function(n) {
            if (n.g == 1) {
              f = vc;
              g = vl(a, b, c, d2, e);
              h = g.type;
              k2 = g.qc;
              l = g.Nf;
              if (m = e.get(f.na)) a.m = m.isAudioMuxedInVideo;
              if (h == wl) return a.j.has(b) && !k2 ? (a.j.get(b).destroy(), a.j.delete(b)) : !a.j.has(b) && k2 ? a.j.set(b, k2) : k2 && (a.j.has(b) && a.j.get(b).transmux !== k2.transmux ? (a.j.get(b).destroy(), a.j.set(b, k2)) : k2.destroy()), n.return(false);
              if (h == xl) return G(n, jl(a, b, l, k2), 3);
              if (h != yl) return n.B(3);
              k2 && k2.destroy();
              return G(n, tl(a, e), 3);
            }
            return n.return(true);
          });
        }
        function zl(a, b, c, d2, e) {
          a = vl(a, b, c, d2, e);
          a.qc && a.qc.destroy();
          return a.type == yl;
        }
        var Bk = window7.URL.createObjectURL, Jk = "sequence", wl = "none", yl = "reset", xl = "changeType";
        function Al(a, b, c) {
          this.i = a;
          this.F = b;
          this.A = this.l = Infinity;
          this.h = 1;
          this.g = this.j = null;
          this.C = 0;
          this.D = true;
          this.J = false;
          this.I = 0;
          this.G = c === void 0 ? true : c;
          this.H = 0;
          this.u = false;
          this.m = a;
        }
        p = Al.prototype;
        p.getDuration = function() {
          return this.l;
        };
        p.Wk = function() {
          return this.h;
        };
        p.Nj = function(a) {
          this.i = a;
        };
        p.yb = function(a) {
          this.l = a;
        };
        p.cl = function() {
          return this.i;
        };
        p.Kj = function(a) {
          this.C = a;
        };
        p.rd = function(a) {
          a && !this.D && (this.J = true);
          this.D = a;
        };
        p.hg = function(a) {
          this.A = a;
        };
        p.wf = function() {
          return this.A;
        };
        p.ci = function(a) {
          this.F = a;
        };
        p.Lk = function() {
          return this.F;
        };
        p.sj = function(a, b) {
          if (a.length != 0) {
            var c = (Date.now() + this.C) / 1e3;
            a = a.filter(function(e) {
              return e.start + b < c;
            });
            if (a.length != 0) {
              var d2 = a[a.length - 1].end + b;
              this.Of(a[0].start + b);
              this.h = a.reduce(function(e, f) {
                return Math.max(e, f.end - f.start);
              }, this.h);
              this.g = Math.max(this.g, d2);
              this.i != null && this.G && !this.u && (this.i = c - this.g - this.h);
            }
          }
        };
        p.ye = function(a) {
          if (a.length != 0) {
            var b = a[0].startTime, c = a[0].endTime, d2 = (Date.now() + this.C) / 1e3;
            a = t2(a);
            for (var e = a.next(); !e.done; e = a.next()) e = e.value, d2 < e.startTime || (b = Math.min(b, e.startTime), c = Math.max(c, e.endTime), this.h = Math.max(this.h, e.endTime - e.startTime));
            this.Of(b);
            this.g = Math.max(this.g, c);
            this.i != null && this.G && !this.u && (this.i = d2 - this.g - this.h);
          }
        };
        p.rj = function(a, b) {
          this.Of(a);
          b == Infinity || this.U() || (this.g = Math.max(this.g, b));
        };
        p.Xk = function() {
          return this.g;
        };
        p.If = function() {
          this.u = true;
        };
        p.Il = function() {
          return this.u;
        };
        p.ei = function(a) {
          this.m = a;
        };
        p.Pk = function() {
          return this.m;
        };
        p.Of = function(a) {
          this.j == null ? this.j = a : this.J || (this.j = Math.min(this.j, a));
        };
        p.Lh = function(a) {
          this.h = Math.max(this.h, a);
        };
        p.offset = function(a) {
          this.j != null && (this.j += a);
          this.g != null && (this.g += a);
        };
        p.U = function() {
          return this.l == Infinity && !this.D;
        };
        p.kd = function() {
          return this.l != Infinity && !this.D;
        };
        p.Nb = function() {
          return Math.max(this.I, this.Mc() - this.A);
        };
        p.Pj = function(a) {
          this.I = a;
        };
        p.Mc = function() {
          return this.U() || this.kd() ? Math.min(Math.max(0, (Date.now() + this.C) / 1e3 - this.h - this.i) + this.H, this.l) : this.g ? Math.min(this.g, this.l) : this.l;
        };
        p.le = function(a) {
          var b = Math.max(this.j, this.I);
          return this.A == Infinity ? Math.ceil(b * 1e3) / 1e3 : Math.max(b, Math.min(this.Mc() - this.A + a, this.Mb()));
        };
        p.ec = function() {
          return this.le(0);
        };
        p.Mb = function() {
          return Math.max(0, this.Mc() - (this.U() || this.kd() ? this.F : 0));
        };
        p.ck = function() {
          return this.i == null || this.g != null && this.G ? false : true;
        };
        p.Jj = function(a) {
          this.H = a;
        };
        p.Bk = function() {
          return this.H;
        };
        S("shaka.media.PresentationTimeline", Al);
        Al.prototype.getAvailabilityTimeOffset = Al.prototype.Bk;
        Al.prototype.setAvailabilityTimeOffset = Al.prototype.Jj;
        Al.prototype.usingPresentationStartTime = Al.prototype.ck;
        Al.prototype.getSeekRangeEnd = Al.prototype.Mb;
        Al.prototype.getSeekRangeStart = Al.prototype.ec;
        Al.prototype.getSafeSeekRangeStart = Al.prototype.le;
        Al.prototype.getSegmentAvailabilityEnd = Al.prototype.Mc;
        Al.prototype.setUserSeekStart = Al.prototype.Pj;
        Al.prototype.getSegmentAvailabilityStart = Al.prototype.Nb;
        Al.prototype.isInProgress = Al.prototype.kd;
        Al.prototype.isLive = Al.prototype.U;
        Al.prototype.offset = Al.prototype.offset;
        Al.prototype.notifyMaxSegmentDuration = Al.prototype.Lh;
        Al.prototype.notifyMinSegmentStartTime = Al.prototype.Of;
        Al.prototype.getInitialProgramDateTime = Al.prototype.Pk;
        Al.prototype.setInitialProgramDateTime = Al.prototype.ei;
        Al.prototype.isStartTimeLocked = Al.prototype.Il;
        Al.prototype.lockStartTime = Al.prototype.If;
        Al.prototype.getMaxSegmentEndTime = Al.prototype.Xk;
        Al.prototype.notifyPeriodDuration = Al.prototype.rj;
        Al.prototype.notifySegments = Al.prototype.ye;
        Al.prototype.notifyTimeRange = Al.prototype.sj;
        Al.prototype.getDelay = Al.prototype.Lk;
        Al.prototype.setDelay = Al.prototype.ci;
        Al.prototype.getSegmentAvailabilityDuration = Al.prototype.wf;
        Al.prototype.setSegmentAvailabilityDuration = Al.prototype.hg;
        Al.prototype.setStatic = Al.prototype.rd;
        Al.prototype.setClockOffset = Al.prototype.Kj;
        Al.prototype.getPresentationStartTime = Al.prototype.cl;
        Al.prototype.setDuration = Al.prototype.yb;
        Al.prototype.setPresentationStartTime = Al.prototype.Nj;
        Al.prototype.getMaxSegmentDuration = Al.prototype.Wk;
        Al.prototype.getDuration = Al.prototype.getDuration;
        function Bl(a, b, c, d2) {
          var e = this;
          this.A = d2;
          this.g = a;
          this.F = b;
          this.h = c;
          this.j = new Qc();
          this.m = false;
          this.l = 0;
          this.D = false;
          this.H = this.G = 0;
          this.u = Cl(this);
          this.C = false;
          this.j.o(a, "waiting", function() {
            return Dl(e);
          });
          this.i = new Cf(function() {
            Dl(e);
          }).za(this.h.gapJumpTimerTime);
        }
        Bl.prototype.release = function() {
          this.j && (this.j.release(), this.j = null);
          this.i != null && (this.i.stop(), this.i = null);
          this.u && (this.u.release(), this.u = null);
          this.g = this.F = this.A = null;
        };
        Bl.prototype.Rf = function() {
          this.C = true;
          this.i && this.i.za(this.h.gapJumpTimerTime);
          Dl(this);
        };
        function Dl(a) {
          if (a.g.readyState != 0) {
            if (a.g.seeking) {
              if (!a.m) return;
            } else a.m = false;
            if (!a.g.paused || a.g.currentTime == a.l && (a.g.autoplay || a.g.currentTime != a.l)) {
              var b;
              if (!(b = !a.u)) {
                b = a.u;
                var c = b.h, d2 = El(c), e = c.g.currentTime, f = Date.now() / 1e3;
                if (b.g != e || b.m != d2) b.l = f, b.g = e, b.m = d2, b.i = false;
                e = f - b.l;
                if (d2 = e >= b.u && d2 && !b.i) b.j && b.j(b.g, e), b.i = true, b.g = c.g.currentTime;
                b = !d2;
              }
              b && (b = a.g.currentTime, c = a.g.buffered, d2 = Mj(c, b, a.h.gapDetectionThreshold), d2 == null || d2 == 0 && !a.C || (e = c.start(d2), (f = a.h.gapPadding) && (e = Math.ceil((e + f) * 100) / 100), e >= a.F.Mb() || e - b < 1e-3 || (d2 != 0 && c.end(d2 - 1), Fl(a, e), b == a.l && (a.l = e), a.G++, a.A(new T("gapjumped")))));
            }
          }
        }
        function Fl(a, b) {
          a.D = true;
          a.j.qa(a.g, "seeked", function() {
            a.D = false;
          });
          a.g.currentTime = b;
        }
        function Cl(a) {
          if (!a.h.stallEnabled) return null;
          var b = a.h.stallThreshold, c = a.h.stallSkip;
          return new Gl(new Hl(a.g), b, function() {
            var d2;
            return P(function(e) {
              if (e.g == 1) return d2 = Lj(a.g.buffered), d2.length ? c ? (a.g.currentTime += c, e.B(2)) : G(e, a.g.play(), 3) : e.return();
              if (e.g != 2) {
                if (!a.g) return e.return();
                a.g.pause();
                a.g.play();
              }
              a.H++;
              a.A(new T("stalldetected"));
              H(e);
            });
          });
        }
        function Gl(a, b, c) {
          this.h = a;
          this.m = El(a);
          this.g = a.g.currentTime;
          this.l = Date.now() / 1e3;
          this.i = false;
          this.u = b;
          this.j = c;
        }
        Gl.prototype.release = function() {
          this.h && this.h.release();
          this.j = this.h = null;
        };
        function Hl(a) {
          var b = this;
          this.g = a;
          this.h = new Qc();
          this.i = false;
          this.h.o(this.g, "audiofocuspaused", function() {
            b.i = true;
          });
          this.h.o(this.g, "audiofocusgranted", function() {
            b.i = false;
          });
          this.h.o(this.g, "audiofocuslost", function() {
            b.i = true;
          });
        }
        function El(a) {
          if (a.g.paused || a.g.playbackRate == 0 || a.i || a.g.buffered.length == 0) var b = false;
          else a: {
            b = a.g.currentTime;
            a = t2(Lj(a.g.buffered));
            for (var c = a.next(); !c.done; c = a.next()) if (c = c.value, !(b < c.start - 0.1 || b > c.end - 0.5)) {
              b = true;
              break a;
            }
            b = false;
          }
          return b;
        }
        Hl.prototype.release = function() {
          this.h && this.h.release();
          this.h = null;
        };
        function Il(a, b, c, d2) {
          b == HTMLMediaElement.HAVE_NOTHING || a.readyState >= b ? d2() : (b = Jl.value().get(b), c.qa(a, b, d2));
        }
        var Jl = new Rb(function() {
          return /* @__PURE__ */ new Map([[HTMLMediaElement.HAVE_METADATA, "loadedmetadata"], [HTMLMediaElement.HAVE_CURRENT_DATA, "loadeddata"], [HTMLMediaElement.HAVE_FUTURE_DATA, "canplay"], [HTMLMediaElement.HAVE_ENOUGH_DATA, "canplaythrough"]]);
        });
        function Kl(a, b, c, d2) {
          var e = this;
          this.g = a;
          this.m = b;
          this.A = c;
          this.l = null;
          this.j = function() {
            e.l == null && (e.l = d2());
            return e.l;
          };
          this.u = false;
          this.h = new Qc();
          this.i = new Ll(a);
          Il(this.g, HTMLMediaElement.HAVE_METADATA, this.h, function() {
            Ml(e, e.j());
          });
        }
        Kl.prototype.release = function() {
          this.h && (this.h.release(), this.h = null);
          this.i != null && (this.i.release(), this.i = null);
          this.m = function() {
          };
          this.g = null;
        };
        function Nl(a) {
          return a.u ? a.g.currentTime : a.j();
        }
        function Ol(a, b) {
          a.g.readyState > 0 ? Pl(a.i, b) : Il(a.g, HTMLMediaElement.HAVE_METADATA, a.h, function() {
            Ml(a, a.j());
          });
        }
        function Ml(a, b) {
          Math.abs(a.g.currentTime - b) < 1e-3 ? Ql(a) : (a.h.qa(a.g, "seeking", function() {
            Ql(a);
          }), Pl(a.i, a.g.currentTime && a.g.currentTime != 0 ? a.g.currentTime : b));
        }
        function Ql(a) {
          a.u = true;
          a.h.o(a.g, "seeking", function() {
            return a.m();
          });
          a.A(a.g.currentTime);
        }
        function Ll(a) {
          var b = this;
          this.g = a;
          this.m = 10;
          this.j = this.l = this.i = 0;
          this.h = new Cf(function() {
            b.i <= 0 ? b.h.stop() : b.g.currentTime != b.l || b.g.currentTime === b.j ? b.h.stop() : (b.g.currentTime = b.j, b.i--);
          });
        }
        Ll.prototype.release = function() {
          this.h && (this.h.stop(), this.h = null);
          this.g = null;
        };
        function Pl(a, b) {
          a.l = a.g.currentTime;
          a.j = b;
          a.i = a.m;
          a.g.currentTime = b;
          a.h.za(0.1);
        }
        ;
        function Rl(a) {
          this.g = a;
          this.i = false;
          this.h = null;
          this.j = new Qc();
        }
        p = Rl.prototype;
        p.ready = function() {
          function a() {
            if (b.h == null || b.h == 0 && b.g.duration != Infinity) b.i = true;
            else {
              var c = b.g.currentTime, d2 = null;
              if (typeof b.h === "number") d2 = b.h;
              else if (b.h instanceof Date) {
                var e = Sl(b);
                e !== null && (d2 = b.h.getTime() / 1e3 - e, d2 = Tl(b, d2));
              }
              d2 == null ? b.i = true : (d2 < 0 && (d2 = Math.max(0, c + d2)), c != d2 ? (b.j.qa(b.g, "seeking", function() {
                b.i = true;
              }), b.g.currentTime = d2) : b.i = true);
            }
          }
          var b = this;
          Il(this.g, HTMLMediaElement.HAVE_FUTURE_DATA, this.j, function() {
            a();
          });
        };
        p.release = function() {
          this.j && (this.j.release(), this.j = null);
          this.g = null;
        };
        p.Ag = function(a) {
          this.h = this.i ? this.h : a;
        };
        p.Xe = function() {
          var a = this.i ? this.g.currentTime : this.h;
          a instanceof Date && (a = a.getTime() / 1e3 - (Sl(this) || 0), a = Tl(this, a));
          return a || 0;
        };
        p.Ci = function() {
          return 0;
        };
        p.Ai = function() {
          return 0;
        };
        p.Bi = function() {
          return false;
        };
        p.qj = function() {
        };
        p.ej = function() {
          var a = Ij(this.g.buffered);
          return a != null && a >= this.g.duration - 1;
        };
        function Sl(a) {
          return a.g.getStartDate && (a = a.g.getStartDate().getTime(), !isNaN(a)) ? a / 1e3 : null;
        }
        function Tl(a, b) {
          a = a.g.seekable;
          a.length > 0 && (b = Math.max(a.start(0), b), b = Math.min(a.end(a.length - 1), b));
          return b;
        }
        function Ul(a, b, c, d2, e, f) {
          var g = this;
          this.h = a;
          this.g = b.presentationTimeline;
          this.l = c;
          this.A = e;
          this.u = null;
          this.i = new Bl(a, b.presentationTimeline, c, f);
          this.j = new Kl(a, function() {
            a: {
              var h = g.i;
              h.m = true;
              h.C = false;
              h.i && h.i.za(h.h.gapJumpTimerTime);
              Dl(h);
              var k2 = Nl(g.j);
              h = Vl(g, k2);
              if (!hd() && Math.abs(h - k2) > 1e-3) {
                k2 = false;
                var l = Sb().Ej();
                if (l) {
                  var m = Date.now() / 1e3;
                  if (!g.u || g.u < m - l) g.u = m, k2 = true;
                } else k2 = true;
                if (k2) {
                  Ol(g.j, h);
                  h = void 0;
                  break a;
                }
              }
              g.A();
              h = void 0;
            }
            return h;
          }, function(h) {
            var k2 = g.i;
            k2.g.seeking && !k2.m && (k2.m = true, k2.l = h);
            k2.i && k2.i.za(k2.h.gapJumpTimerTime);
            Dl(k2);
          }, function() {
            return Wl(g, d2);
          });
          this.m = new Cf(function() {
            if (g.h.readyState != 0 && !g.h.paused) {
              var h = Nl(g.j), k2 = g.g.ec(), l = g.g.Mb();
              l - k2 < 3 && (k2 = l - 3);
              h < k2 && (h = Vl(g, h), g.h.currentTime = h);
            }
          });
        }
        p = Ul.prototype;
        p.ready = function() {
          this.m.za(0.25);
        };
        p.release = function() {
          this.j && (this.j.release(), this.j = null);
          this.i && (this.i.release(), this.i = null);
          this.m && (this.m.stop(), this.m = null);
          this.h = this.j = this.g = this.l = null;
          this.A = function() {
          };
        };
        p.Ag = function(a) {
          Ol(this.j, Wl(this, a));
        };
        p.Xe = function() {
          var a = Nl(this.j);
          return this.h.readyState > 0 && !this.h.paused ? Xl(this, a) : a;
        };
        p.Ci = function() {
          return this.i.H;
        };
        p.Ai = function() {
          return this.i.G;
        };
        p.Bi = function() {
          return this.i.D;
        };
        function Wl(a, b) {
          b == null ? b = a.g.getDuration() < Infinity ? a.g.ec() : a.g.Mb() : b instanceof Date ? b = b.getTime() / 1e3 - (a.g.m || a.g.i) : b < 0 && (b = a.g.Mb() + b);
          return Yl(a, Xl(a, b));
        }
        p.qj = function() {
          this.i.Rf();
        };
        p.ej = function() {
          if (this.g.U()) {
            var a = this.g.Mc(), b = Ij(this.h.buffered);
            if (b != null && b >= a) return true;
          }
          return false;
        };
        function Yl(a, b) {
          var c = a.g.getDuration();
          return b >= c ? c - a.l.durationBackoff : b;
        }
        function Vl(a, b) {
          var c = a.l.rebufferingGoal, d2 = a.l.safeSeekOffset, e = a.g.ec(), f = a.g.Mb(), g = a.g.getDuration();
          f - e < 3 && (e = f - 3);
          var h = a.g.le(c), k2 = a.g.le(d2);
          c = a.g.le(c + d2);
          return b >= g ? Yl(a, b) : b > f ? f - a.l.safeSeekEndOffset : b < e ? a.g.U() && a.l.returnToEndOfLiveWindowWhenOutside ? f - a.l.safeSeekEndOffset : Jj(a.h.buffered, k2) ? k2 : c : b >= h || Jj(a.h.buffered, b) ? b : c;
        }
        function Xl(a, b) {
          var c = a.g.ec();
          if (b < c) return c;
          a = a.g.Mb();
          return b > a ? a : b;
        }
        ;
        function Zl(a) {
          this.g = a;
          this.m = null;
          this.i = 0;
          this.u = false;
        }
        p = Zl.prototype;
        p.getNumReferences = function() {
          return this.g.length;
        };
        p.getNumEvicted = function() {
          return this.i;
        };
        p.release = function() {
          this.u || (this.g = [], this.m && this.m.stop(), this.m = null);
        };
        p.Pl = function() {
          this.u = true;
        };
        p.Kb = function(a) {
          for (var b = t2(this.g), c = b.next(); !c.done; c = b.next()) a(c.value);
        };
        function fg(a) {
          return a.g[0] || null;
        }
        p.find = function(a) {
          for (var b = this.g.length - 1, c = b; c >= 0; --c) {
            var d2 = this.g[c], e = c < b ? this.g[c + 1].startTime : d2.endTime;
            if (a >= d2.startTime && a < e) return c + this.i;
          }
          return this.g.length && a < this.g[0].startTime ? this.i : null;
        };
        p.get = function(a) {
          if (this.g.length == 0) return null;
          a -= this.i;
          return a < 0 || a >= this.g.length ? null : this.g[a];
        };
        p.offset = function(a) {
          if (!this.u) for (var b = t2(this.g), c = b.next(); !c.done; c = b.next()) c.value.offset(a);
        };
        p.Kf = function(a) {
          if (!this.u && a.length) {
            var b = Math.round(a[0].startTime * 1e3) / 1e3;
            this.g = this.g.filter(function(c) {
              return Math.round(c.startTime * 1e3) / 1e3 < b;
            });
            this.g.push.apply(this.g, x(a));
          }
        };
        p.we = function(a, b) {
          var c = this;
          a = a.filter(function(d2) {
            return d2.endTime > b && (c.g.length == 0 || d2.endTime > c.g[0].startTime);
          });
          this.Kf(a);
          this.ib(b);
        };
        p.ib = function(a) {
          if (!this.u) {
            var b = this.g.length;
            this.g = this.g.filter(function(c) {
              return c.endTime > a;
            });
            this.i += b - this.g.length;
          }
        };
        p.Ed = function(a, b, c) {
          c = c === void 0 ? false : c;
          if (!this.u) {
            for (; this.g.length; ) if (this.g[this.g.length - 1].startTime >= b) this.g.pop();
            else break;
            for (; this.g.length; ) if (this.g[0].endTime <= a) this.g.shift(), c || this.i++;
            else break;
            this.g.length != 0 && (a = this.g[this.g.length - 1], b = new Cj(a.startTime, b, a.F, a.startByte, a.endByte, a.ha, a.timestampOffset, a.appendWindowStart, a.appendWindowEnd, a.g, a.tilesLayout, a.D, a.h, a.status, a.aesKey), b.mimeType = a.mimeType, b.codecs = a.codecs, b.i = a.i, this.g[this.g.length - 1] = b);
          }
        };
        p.pg = function(a, b) {
          var c = this;
          this.u || (this.m && this.m.stop(), this.m = new Cf(function() {
            var d2 = b();
            d2 ? c.g.push.apply(c.g, x(d2)) : (c.m.stop(), c.m = null);
          }), this.m.za(a));
        };
        Zl.prototype[Symbol.iterator] = function() {
          return this.dc(0);
        };
        Zl.prototype.dc = function(a, b, c) {
          b = b === void 0 ? false : b;
          c = c === void 0 ? false : c;
          var d2 = this.find(a);
          if (d2 == null) return null;
          var e = this.get(d2);
          c ? d2++ : d2--;
          var f = -1;
          if (e && e.g.length > 0) for (var g = e.g.length - 1; g >= 0; --g) {
            var h = e.g[g];
            if (a >= h.startTime && a < h.endTime) {
              if (!b) {
                for (; g && !h.l; ) g--, h = e.g[g];
                if (!h.l) return ab("No independent partial segment found!"), null;
              }
              c ? d2-- : d2++;
              f = g - 1;
              break;
            }
          }
          return new $l(this, d2, f, c);
        };
        Zl.prototype.mf = function() {
          return -1;
        };
        function am(a, b, c) {
          a = new Cj(a, a + b, function() {
            return c;
          }, 0, null, null, a, a, a + b);
          return new Zl([a]);
        }
        S("shaka.media.SegmentIndex", Zl);
        Zl.forSingleSegment = am;
        Zl.prototype.getIteratorForTime = Zl.prototype.dc;
        Zl.prototype.updateEvery = Zl.prototype.pg;
        Zl.prototype.fit = Zl.prototype.Ed;
        Zl.prototype.evict = Zl.prototype.ib;
        Zl.prototype.mergeAndEvict = Zl.prototype.we;
        Zl.prototype.offset = Zl.prototype.offset;
        Zl.prototype.get = Zl.prototype.get;
        Zl.prototype.find = Zl.prototype.find;
        Zl.prototype.markImmutable = Zl.prototype.Pl;
        Zl.prototype.release = Zl.prototype.release;
        Zl.prototype.getNumEvicted = Zl.prototype.getNumEvicted;
        Zl.prototype.getNumReferences = Zl.prototype.getNumReferences;
        function $l(a, b, c, d2) {
          this.i = a;
          this.h = b;
          this.g = c;
          this.reverse = d2;
        }
        p = $l.prototype;
        p.Vd = function(a) {
          this.reverse = a;
        };
        p.wk = function() {
          return this.h;
        };
        p.current = function() {
          var a = this.i.get(this.h);
          a && a.g.length > 0 && a.C && this.g >= a.g.length && (this.h++, this.g = 0, a = this.i.get(this.h));
          return a && a.g.length > 0 ? a.g[this.g] : a;
        };
        p.next = function() {
          var a = this.i.get(this.h);
          this.reverse ? a && a.g.length > 0 ? (this.g--, this.g < 0 && (this.h--, this.g = (a = this.i.get(this.h)) && a.g.length > 0 ? a.g.length - 1 : 0)) : (this.h--, this.g = 0) : a && a.g.length > 0 ? (this.g++, a.C && this.g == a.g.length && (this.h++, this.g = 0)) : (this.h++, this.g = 0);
          a = this.current();
          return {
            value: a,
            done: !a
          };
        };
        p.Wh = function() {
          var a = this.current();
          if (a.u && !a.l && (a = this.i.get(this.h)) && a.g.length > 0) for (var b = a.g[this.g]; b.l && !(this.g <= 0); ) this.g--, b = a.g[this.g];
        };
        S("shaka.media.SegmentIterator", $l);
        $l.prototype.resetToLastIndependent = $l.prototype.Wh;
        $l.prototype.next = $l.prototype.next;
        $l.prototype.current = $l.prototype.current;
        $l.prototype.currentPosition = $l.prototype.wk;
        $l.prototype.setReverse = $l.prototype.Vd;
        function bm() {
          Zl.call(this, []);
          this.h = [];
        }
        ma(bm, Zl);
        p = bm.prototype;
        p.clone = function() {
          var a = new bm();
          a.h = this.h.slice();
          a.i = this.i;
          return a;
        };
        p.release = function() {
          for (var a = t2(this.h), b = a.next(); !b.done; b = a.next()) b.value.release();
          this.h = [];
        };
        p.Kb = function(a) {
          for (var b = t2(this.h), c = b.next(); !c.done; c = b.next()) c.value.Kb(a);
        };
        function cm(a, b) {
          a = t2(a.h);
          for (var c = a.next(); !c.done; c = a.next()) b(c.value);
        }
        p.find = function(a) {
          for (var b = this.i, c = t2(this.h), d2 = c.next(); !d2.done; d2 = c.next()) {
            d2 = d2.value;
            var e = d2.find(a);
            if (e != null) return e + b;
            b += d2.getNumEvicted() + d2.getNumReferences();
          }
          return null;
        };
        function dm(a, b) {
          a = t2(a.h);
          for (var c = a.next(); !c.done; c = a.next()) if (c = c.value, c.find(b) != null) return c.mf();
          return -1;
        }
        p.get = function(a) {
          for (var b = this.i, c = t2(this.h), d2 = c.next(); !d2.done; d2 = c.next()) {
            d2 = d2.value;
            var e = d2.get(a - b);
            if (e) return e;
            e = d2.getNumReferences();
            b += d2.getNumEvicted() + e;
          }
          return null;
        };
        p.offset = function() {
        };
        p.Kf = function() {
        };
        p.ib = function(a) {
          for (var b = t2(this.h), c = b.next(); !c.done; c = b.next()) c.value.ib(a);
          for (; this.h.length > 1 && this.h[0].getNumReferences() == 0; ) a = this.h.shift(), this.i += a.getNumEvicted(), a.release();
        };
        p.we = function() {
        };
        p.Ed = function() {
        };
        p.pg = function() {
        };
        S("shaka.media.MetaSegmentIndex", bm);
        bm.prototype.updateEvery = bm.prototype.pg;
        bm.prototype.fit = bm.prototype.Ed;
        bm.prototype.mergeAndEvict = bm.prototype.we;
        bm.prototype.evict = bm.prototype.ib;
        bm.prototype.merge = bm.prototype.Kf;
        bm.prototype.offset = bm.prototype.offset;
        bm.prototype.get = bm.prototype.get;
        bm.prototype.find = bm.prototype.find;
        bm.prototype.forEachTopLevelReference = bm.prototype.Kb;
        bm.prototype.release = bm.prototype.release;
        function em(a) {
          var b = this;
          this.g = a;
          this.j = false;
          this.i = this.g.vf();
          this.h = new Cf(function() {
            b.g.oj(b.i * 0.25);
          });
        }
        em.prototype.release = function() {
          this.set(this.fd());
          this.h && (this.h.stop(), this.h = null);
          this.g = null;
        };
        em.prototype.set = function(a) {
          this.i = a;
          fm(this);
        };
        em.prototype.fd = function() {
          return this.g.fd();
        };
        function fm(a) {
          a.h.stop();
          var b = a.j ? 0 : a.i;
          if (b >= 0) try {
            a.g.vf() != b && a.g.gi(b);
            return;
          } catch (c) {
          }
          a.h.za(0.25);
          a.g.vf() != 0 && a.g.gi(0);
        }
        ;
        function gm(a) {
          var b = this;
          this.j = a;
          this.h = new Qc();
          this.g = /* @__PURE__ */ new Set();
          this.i = new Cf(function() {
            hm(b, false);
          }).La();
          a.paused || this.i.za(0.25);
          this.h.o(a, "playing", function() {
            b.i.La().za(0.25);
          });
          this.h.o(a, "pause", function() {
            b.i.stop();
          });
        }
        gm.prototype.release = function() {
          this.h && (this.h.release(), this.h = null);
          this.i.stop();
          for (var a = t2(this.g), b = a.next(); !b.done; b = a.next()) b.value.release();
          this.g.clear();
        };
        function hm(a, b) {
          var c = a.j.currentTime;
          a = t2(a.g);
          for (var d2 = a.next(); !d2.done; d2 = a.next()) d2.value.j(c, b);
        }
        ;
        function im(a) {
          lb.call(this);
          this.g = /* @__PURE__ */ new Map();
          this.h = a;
        }
        ma(im, lb);
        im.prototype.release = function() {
          this.g.clear();
          lb.prototype.release.call(this);
        };
        function jm(a, b) {
          var c = a.g.get(b);
          c || (c = {
            Be: [],
            Tg: null,
            contentType: b
          }, a.g.set(b, c));
          return c;
        }
        function km(a, b, c) {
          var d2 = jm(a, b.contentType);
          lm(a, d2);
          a = {
            Kd: b,
            position: c
          };
          d2 = d2.Be;
          b = d2.findIndex(function(e) {
            return e.position >= c;
          });
          b >= 0 ? d2.splice(b, d2[b].position == c ? 1 : 0, a) : d2.push(a);
        }
        im.prototype.j = function(a) {
          for (var b = t2(this.g.values()), c = b.next(); !c.done; c = b.next()) {
            c = c.value;
            var d2 = c.Tg;
            a: {
              var e = c.Be;
              for (var f = e.length - 1; f >= 0; f--) {
                var g = e[f];
                if (g.position <= a) {
                  e = g.Kd;
                  break a;
                }
              }
              e = null;
            }
            f = e && !(d2 === e || d2 && e && d2.bandwidth == e.bandwidth && d2.audioSamplingRate == e.audioSamplingRate && d2.codecs == e.codecs && d2.contentType == e.contentType && d2.frameRate == e.frameRate && d2.height == e.height && d2.mimeType == e.mimeType && d2.channelsCount == e.channelsCount && d2.pixelAspectRatio == e.pixelAspectRatio && d2.width == e.width);
            g = e && d2 && e.label && d2.label && d2.label !== e.label;
            var h = e && d2 && e.language && d2.language && d2.language !== e.language;
            d2 = e && d2 && e.roles && d2.roles && !wd(d2.roles, e.roles);
            (g || h || d2) && mm(this, a, e.contentType) && (c.Tg = e, d2 = new T("audiotrackchange", /* @__PURE__ */ new Map([["quality", e], ["position", a]])), this.dispatchEvent(d2));
            f && mm(this, a, e.contentType) && (c.Tg = e, JSON.stringify(e), c = new T("qualitychange", /* @__PURE__ */ new Map([["quality", e], ["position", a]])), this.dispatchEvent(c));
          }
        };
        function mm(a, b, c) {
          return (a = a.h()[c]) && a.length > 0 && (c = a[a.length - 1].end, b >= a[0].start && b < c) ? true : false;
        }
        function lm(a, b) {
          if ((a = a.h()[b.contentType]) && a.length > 0) {
            var c = a[0].start, d2 = a[a.length - 1].end, e = b.Be;
            b.Be = e.filter(function(f, g) {
              return f.position <= c && g + 1 < e.length && e[g + 1].position <= c || f.position >= d2 ? false : true;
            });
          } else b.Be = [];
        }
        function nm(a) {
          var b = {
            bandwidth: a.bandwidth || 0,
            audioSamplingRate: null,
            codecs: a.codecs,
            contentType: a.type,
            frameRate: null,
            height: null,
            mimeType: a.mimeType,
            channelsCount: null,
            pixelAspectRatio: null,
            width: null,
            label: null,
            roles: a.roles,
            language: null
          };
          a.type == "video" && (b.frameRate = a.frameRate || null, b.height = a.height || null, b.pixelAspectRatio = a.pixelAspectRatio || null, b.width = a.width || null);
          a.type == "audio" && (b.audioSamplingRate = a.audioSamplingRate, b.channelsCount = a.channelsCount, b.label = a.label || null, b.language = a.language);
          return b;
        }
        ;
        function om(a) {
          lb.call(this);
          this.h = /* @__PURE__ */ new Map();
          this.i = a;
          this.g = null;
        }
        ma(om, lb);
        om.prototype.release = function() {
          this.h.clear();
          this.g && (this.g.stop(), this.g = null);
          lb.prototype.release.call(this);
        };
        function pm(a, b) {
          var c = b.schemeIdUri + "_" + b.id + "_" + (b.startTime.toFixed(1) + "_" + b.endTime.toFixed(1));
          a.h.has(c) || (a.h.set(c, b), b = new T("regionadd", /* @__PURE__ */ new Map([["region", b]])), a.dispatchEvent(b), qm(a));
        }
        function qm(a) {
          a.g || (a.g = new Cf(function() {
            for (var b = a.i(), c = t2(a.h), d2 = c.next(); !d2.done; d2 = c.next()) {
              var e = t2(d2.value);
              d2 = e.next().value;
              e = e.next().value;
              e.endTime < b.start && (a.h.delete(d2), d2 = new T("regionremove", /* @__PURE__ */ new Map([["region", e]])), a.dispatchEvent(d2));
            }
            !a.h.size && a.g && (a.g.stop(), a.g = null);
          }).za(2));
        }
        ;
        function rm(a, b, c, d2) {
          this.m = a;
          this.i = b;
          this.l = c;
          this.h = /* @__PURE__ */ new Map();
          this.j = /* @__PURE__ */ new Map();
          this.g = null;
          this.u = d2;
        }
        function sm(a, b) {
          a.l = b;
          a = t2(a.h.values());
          for (var c = a.next(); !c.done; c = a.next()) c.value.g = b;
        }
        function tm(a, b, c) {
          c = c === void 0 ? false : c;
          if (!a.i.segmentIndex) return Promise.resolve();
          a.g || (a.g = a.i.segmentIndex.dc(b, true, a.u));
          if (!a.g) return Promise.resolve();
          c && a.g.next();
          for (b = []; a.h.size < a.m; ) {
            c = a.g.next().value;
            if (!c) break;
            var d2 = true;
            c.isPreload() && c.endByte != null && (d2 = false);
            c.Oc() == 2 && (d2 = false);
            c.fc(false) && (d2 = false);
            d2 && c.ha && b.push(um(a, c.ha));
            d2 && !a.h.has(c) && (d2 = new vm(a.l), b.push(wm(d2, c, a.i)), a.h.set(c, d2));
          }
          xm(a);
          return Promise.all(b);
        }
        function um(a, b) {
          if (!a.i.segmentIndex || b.fc() || Array.from(a.j.keys()).some(function(e) {
            return Bj(e, b);
          })) return Promise.resolve();
          var c = new vm(a.l), d2 = wm(c, b, a.i);
          a.j.set(b, c);
          return d2;
        }
        function ym(a, b) {
          b = t2(b.keys());
          for (var c = b.next(); !c.done; c = b.next()) (c = c.value) && zm(a, c);
        }
        function Am(a) {
          ym(a, a.h);
          ym(a, a.j);
          a.g = null;
        }
        rm.prototype.ib = function(a, b) {
          b = b === void 0 ? false : b;
          for (var c = t2(this.h.keys()), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, a > d2.endTime && zm(this, d2);
          b && xm(this);
        };
        rm.prototype.Vd = function(a) {
          this.u = a;
          this.g && this.g.Vd(a);
        };
        function xm(a) {
          for (var b = Array.from(a.h.keys()), c = t2(a.j.keys()), d2 = c.next(), e = {}; !d2.done; e = {
            Eh: void 0
          }, d2 = c.next()) e.Eh = d2.value, b.some(/* @__PURE__ */ function(f) {
            return function(g) {
              return Bj(g.ha, f.Eh);
            };
          }(e)) || zm(a, e.Eh);
        }
        function Bm(a, b) {
          a.m = b;
          for (var c = Array.from(a.h.keys()); c.length > b; ) {
            var d2 = c.pop();
            d2 && zm(a, d2);
          }
          xm(a);
        }
        function Cm(a, b) {
          b && b !== a.i && (Am(a), a.i = b);
        }
        function zm(a, b) {
          var c = a.h;
          b instanceof Aj && (c = a.j);
          a = c.get(b);
          c.delete(b);
          a && a.abort();
        }
        function vm(a) {
          this.g = a;
          this.ze = this.ni = null;
        }
        function wm(a, b, c) {
          var d2 = new Uint8Array(0);
          a.ze = a.g(b, c, function(e) {
            return P(function(f) {
              if (f.g == 1) return d2.byteLength > 0 ? d2 = mc(d2, e) : d2 = e, a.ni ? G(f, a.ni(d2), 3) : f.B(0);
              d2 = new Uint8Array(0);
              H(f);
            });
          });
          return a.ze.promise.catch(function(e) {
            return e instanceof U && e.code == 7001 ? Promise.resolve() : Promise.reject(e);
          });
        }
        vm.prototype.abort = function() {
          this.ze && this.ze.abort();
        };
        function Dm(a) {
          var b = nf(a), c = b.split("/")[0];
          a = of(a);
          return {
            type: c,
            mimeType: b,
            codecs: a,
            language: null,
            height: null,
            width: null,
            channelCount: null,
            sampleRate: null,
            closedCaptions: /* @__PURE__ */ new Map(),
            Ke: null,
            colorGamut: null,
            frameRate: null
          };
        }
        function Em(a, b, c) {
          function d2(B) {
            y = B.name;
            var E = B.reader;
            E.skip(24);
            var I = E.Ha(), J = E.Ha();
            E.skip(50);
            q = String(I);
            n = String(J);
            B.reader.Pa() && uh(B);
          }
          function e(B) {
            var E = Qi(B.reader);
            r2 = E.channelCount;
            u = E.sampleRate;
            f(B.name);
          }
          function f(B) {
            B = B.toLowerCase();
            switch (B) {
              case "avc1":
              case "avc3":
                h.push(B + ".42E01E");
                l = true;
                break;
              case "hev1":
              case "hvc1":
                h.push(B + ".1.6.L93.90");
                l = true;
                break;
              case "dvh1":
              case "dvhe":
                h.push(B + ".05.04");
                l = true;
                break;
              case "vp09":
                h.push(B + ".00.10.08");
                l = true;
                break;
              case "av01":
                h.push(B + ".0.01M.08");
                l = true;
                break;
              case "mp4a":
                g.push("mp4a.40.2");
                k2 = true;
                break;
              case "ac-3":
              case "ec-3":
              case "ac-4":
              case "opus":
              case "flac":
                g.push(B);
                k2 = true;
                break;
              case "apac":
                g.push("apac.31.00"), k2 = true;
            }
          }
          var g = [], h = [], k2 = false, l = false, m = null, n = null, q = null, r2 = null, u = null, w = null, v = null, y;
          new ph().box("moov", uh).box("trak", uh).box("mdia", uh).W("mdhd", function(B) {
            m = Oi(B.reader, B.version).language;
          }).box("minf", uh).box("stbl", uh).W("stsd", wh).box("mp4a", function(B) {
            var E = Qi(B.reader);
            r2 = E.channelCount;
            u = E.sampleRate;
            B.reader.Pa() ? uh(B) : f(B.name);
          }).box("esds", function(B) {
            B = B.reader;
            for (var E = "mp4a", I, J; B.Pa(); ) {
              I = B.ba();
              for (var K = B.ba(); K & 128; ) K = B.ba();
              if (I == 3) B.Ha(), K = B.ba(), K & 128 && B.Ha(), K & 64 && B.skip(B.ba()), K & 32 && B.Ha();
              else if (I == 4) J = B.ba(), B.skip(12);
              else if (I == 5) break;
            }
            J && (E += "." + Ti(J), I == 5 && B.Pa() && (I = B.ba(), J = (I & 248) >> 3, J === 31 && B.Pa() && (J = 32 + ((I & 7) << 3) + ((B.ba() & 224) >> 5)), E += "." + J));
            g.push(E);
            k2 = true;
          }).box("ac-3", e).box("ec-3", e).box("ac-4", e).box("Opus", e).box("fLaC", e).box("apac", e).box("avc1", d2).box("avc3", d2).box("hev1", d2).box("hvc1", d2).box("dva1", d2).box("dvav", d2).box("dvh1", d2).box("dvhe", d2).box("vp09", d2).box("av01", d2).box("avcC", function(B) {
            var E = y || "";
            switch (y) {
              case "dvav":
                E = "avc3";
                break;
              case "dva1":
                E = "avc1";
            }
            B = B.reader;
            B.skip(1);
            B = E + "." + Ti(B.ba()) + Ti(B.ba()) + Ti(B.ba());
            h.push(B);
            l = true;
          }).box("hvcC", function(B) {
            var E = y || "";
            switch (y) {
              case "dvh1":
                E = "hvc1";
                break;
              case "dvhe":
                E = "hev1";
            }
            var I = B.reader;
            I.skip(1);
            B = I.ba();
            var J = ["", "A", "B", "C"][B >> 6], K = B & 31, L = I.X(), M = (B & 32) >> 5 ? "H" : "L";
            B = [I.ba(), I.ba(), I.ba(), I.ba(), I.ba(), I.ba()];
            I = I.ba();
            for (var N = 0, O = 0; O < 32; O++) {
              N |= L & 1;
              if (O == 31) break;
              N <<= 1;
              L >>= 1;
            }
            E = E + ("." + J + K) + ("." + Ti(N, true));
            E += "." + M + I;
            J = "";
            for (K = B.length; K--; ) if ((M = B[K]) || J) J = "." + M.toString(16).toUpperCase() + J;
            E += J;
            h.push(E);
            l = true;
          }).box("dvcC", function(B) {
            var E = y || "";
            switch (y) {
              case "hvc1":
                E = "dvh1";
                break;
              case "hev1":
                E = "dvhe";
                break;
              case "avc1":
                E = "dva1";
                break;
              case "avc3":
                E = "dvav";
                break;
              case "av01":
                E = "dav1";
            }
            var I = B.reader;
            I.skip(2);
            B = I.ba();
            I = I.ba();
            h.push(E + "." + Ui(B >> 1 & 127) + "." + Ui(B << 5 & 32 | I >> 3 & 31));
            l = true;
          }).box("dvvC", function(B) {
            var E = y || "";
            switch (y) {
              case "hvc1":
                E = "dvh1";
                break;
              case "hev1":
                E = "dvhe";
                break;
              case "avc1":
                E = "dva1";
                break;
              case "avc3":
                E = "dvav";
                break;
              case "av01":
                E = "dav1";
            }
            var I = B.reader;
            I.skip(2);
            B = I.ba();
            I = I.ba();
            h.push(E + "." + Ui(B >> 1 & 127) + "." + Ui(B << 5 & 32 | I >> 3 & 31));
            l = true;
          }).W("vpcC", function(B) {
            var E = y || "", I = B.reader;
            B = I.ba();
            var J = I.ba();
            I = I.ba() >> 4 & 15;
            h.push(E + "." + Ui(B) + "." + Ui(J) + "." + Ui(I));
            l = true;
          }).box("av1C", function(B) {
            var E = y || "";
            switch (y) {
              case "dav1":
                E = "av01";
            }
            var I = B.reader;
            I.skip(1);
            B = I.ba();
            I = I.ba();
            var J = B >>> 5, K = (I & 64) >> 6;
            h.push(E + "." + J + "." + Ui(B & 31) + (I >>> 7 ? "H" : "M") + "." + Ui(J === 2 && K ? (I & 32) >> 5 ? 12 : 10 : K ? 10 : 8) + "." + ((I & 16) >> 4) + "." + ((I & 8) >> 3) + ((I & 4) >> 2) + (I & 3) + "." + Ui(1) + "." + Ui(1) + "." + Ui(1) + ".0");
            l = true;
          }).box("enca", yh).box("encv", xh).box("sinf", uh).box("frma", function(B) {
            B = Ri(B.reader).codec;
            f(B);
          }).box("colr", function(B) {
            h = h.map(function(J) {
              if (J.startsWith("av01.")) {
                var K = B.reader, L = K.Ua(), M = K.$b(4);
                var N = String.fromCharCode(M[0]);
                N += String.fromCharCode(M[1]);
                N += String.fromCharCode(M[2]);
                N += String.fromCharCode(M[3]);
                if (N === "nclx") {
                  M = K.Ha();
                  N = K.Ha();
                  var O = K.Ha(), Q = K.ba() >> 7, R = J.split(".");
                  R.length == 10 && (R[6] = Ui(M), R[7] = Ui(N), R[8] = Ui(O), R[9] = String(Q), J = R.join("."));
                }
                K.seek(L);
              }
              return J;
            });
            var E = Si(B.reader), I = E.colorGamut;
            w = E.Ke;
            v = I;
          }).parse(a || b, true, true);
          if (!g.length && !h.length) return null;
          var z = k2 && !l, A = /* @__PURE__ */ new Map();
          if (l && !c) {
            c = new ld("video/mp4");
            a && c.init(a);
            try {
              c.Tf(b);
              for (var C = t2(c.zg()), D = C.next(); !D.done; D = C.next()) {
                var F = D.value;
                A.set(F, F);
              }
            } catch (B) {
            }
            c.$d();
          }
          return {
            type: z ? "audio" : "video",
            mimeType: z ? "audio/mp4" : "video/mp4",
            codecs: Fm(g.concat(h)).join(", "),
            language: m,
            height: n,
            width: q,
            channelCount: r2,
            sampleRate: u,
            closedCaptions: A,
            Ke: w,
            colorGamut: v,
            frameRate: null
          };
        }
        function Fm(a) {
          var b = /* @__PURE__ */ new Set(), c = [];
          a = t2(a);
          for (var d2 = a.next(); !d2.done; d2 = a.next()) {
            d2 = d2.value;
            var e = mf(d2);
            b.has(e) || (c.push(d2), b.add(e));
          }
          b = uc("audio", c);
          d2 = uc("video", c);
          a = uc(tc, c);
          d2 = Gm(d2);
          b = b.concat(d2).concat(a);
          return c.length && !b.length ? c : b;
        }
        function Gm(a) {
          if (a.length <= 1) return a;
          var b = a.find(function(c) {
            return c.startsWith("dvav.") || c.startsWith("dva1.") || c.startsWith("dvh1.") || c.startsWith("dvhe.") || c.startsWith("dav1.") || c.startsWith("dvc1.") || c.startsWith("dvi1.");
          });
          return b ? dd('video/mp4; codecs="' + b + '"') ? [b] : a.filter(function(c) {
            return c != b;
          }) : a;
        }
        function Hm(a) {
          var b = null;
          new ph().box("moov", uh).box("trak", uh).box("mdia", uh).box("minf", uh).box("stbl", uh).W("stsd", wh).box("encv", xh).box("enca", yh).box("sinf", uh).box("schi", uh).W("tenc", function(c) {
            c = c.reader;
            c.ba();
            c.ba();
            c.ba();
            c.ba();
            b = lc(c.$b(16));
          }).parse(a, true);
          return b;
        }
        function Im(a, b, c) {
          var d2, e, f, g, h;
          return P(function(k2) {
            if (k2.g == 1) return d2 = b, d2.cryptoKey ? k2.B(2) : G(k2, d2.fetchKey(), 3);
            e = d2.iv;
            if (!e) for (e = Lb(new ArrayBuffer(16)), f = d2.firstMediaSequenceNumber + c, g = e.byteLength - 1; g >= 0; g--) e[g] = f & 255, f >>= 8;
            b.blockCipherMode == "CBC" ? h = {
              name: "AES-CBC",
              iv: e
            } : h = {
              name: "AES-CTR",
              counter: e,
              length: 64
            };
            return k2.return(window7.crypto.subtle.decrypt(h, d2.cryptoKey, a));
          });
        }
        ;
        function Jm(a, b, c, d2, e) {
          a = ah(a, d2, e);
          if (b != 0 || c != null) a.headers.Range = c ? "bytes=" + b + "-" + c : "bytes=" + b + "-";
          return a;
        }
        ;
        function Km(a, b) {
          var c = this;
          this.g = b;
          this.j = a;
          this.i = null;
          this.K = /* @__PURE__ */ new Map();
          this.F = 1;
          this.C = this.u = null;
          this.P = 0;
          this.h = /* @__PURE__ */ new Map();
          this.J = false;
          this.R = null;
          this.D = false;
          this.l = new ih(function() {
            return Lm(c);
          });
          this.M = Date.now() / 1e3;
          this.m = /* @__PURE__ */ new Map();
          this.O = {
            projection: null,
            hfov: null
          };
          this.V = 0;
          this.S = Infinity;
          this.G = null;
          this.L = [];
          this.A = new Cf(function() {
            if (c.j && c.g) {
              if (c.j.presentationTimeline.U()) {
                var d2 = c.j.presentationTimeline.ec(), e = c.j.presentationTimeline.Mb();
                e - d2 > 1 ? el(c.g.ia, d2, e) : fl(c.g.ia);
              } else fl(c.g.ia), c.A && c.A.stop();
            } else c.A && c.A.stop();
          });
          this.H = null;
          this.I = new Cf(function() {
            var d2 = c.g.video;
            !d2.ended && c.H && (d2.currentTime = c.H, c.H = null);
          });
        }
        p = Km.prototype;
        p.destroy = function() {
          return this.l.destroy();
        };
        function Lm(a) {
          var b, c, d2, e, f, g, h;
          return P(function(k2) {
            if (k2.g == 1) {
              a.A && a.A.stop();
              a.A = null;
              a.I && a.I.stop();
              a.I = null;
              b = [];
              c = t2(a.h.values());
              for (d2 = c.next(); !d2.done; d2 = c.next()) e = d2.value, Mm(e), b.push(Nm(e)), e.ka && (Am(e.ka), e.ka = null);
              f = t2(a.m.values());
              for (g = f.next(); !g.done; g = f.next()) h = g.value, Am(h);
              return G(k2, Promise.all(b), 2);
            }
            a.h.clear();
            a.m.clear();
            a.g = null;
            a.j = null;
            a.i = null;
            a.H = null;
            H(k2);
          });
        }
        p.configure = function(a) {
          this.i = a;
          this.R = new Jg({
            maxAttempts: Math.max(a.retryParameters.maxAttempts, 2),
            baseDelay: a.retryParameters.baseDelay,
            backoffFactor: a.retryParameters.backoffFactor,
            fuzzFactor: a.retryParameters.fuzzFactor,
            timeout: 0,
            stallTimeout: 0,
            connectionTimeout: 0
          }, true);
          if (a.disableAudioPrefetch) {
            var b = this.h.get("audio");
            b && b.ka && (Am(b.ka), b.ka = null);
            b = t2(this.m.keys());
            for (var c = b.next(); !c.done; c = b.next()) c = c.value, Am(this.m.get(c)), this.m.delete(c);
          }
          a.disableTextPrefetch && (b = this.h.get(tc)) && b.ka && (Am(b.ka), b.ka = null);
          a.disableVideoPrefetch && (b = this.h.get("video")) && b.ka && (Am(b.ka), b.ka = null);
          b = t2(this.h.keys());
          for (c = b.next(); !c.done; c = b.next()) c = this.h.get(c.value), c.ka ? (Bm(c.ka, a.segmentPrefetchLimit), a.segmentPrefetchLimit > 0 || (Am(c.ka), c.ka = null)) : a.segmentPrefetchLimit > 0 && (c.ka = Om(this, c.stream));
          a.disableAudioPrefetch || Pm(this);
        };
        function Qm(a, b, c) {
          a.j.presentationTimeline.U() || (a.V = b, a.S = c);
        }
        p.start = function(a) {
          var b = this;
          return P(function(c) {
            if (c.g == 1) return G(c, Rm(b, a || /* @__PURE__ */ new Map()), 2);
            jh(b.l);
            b.J = true;
            H(c);
          });
        };
        function Sm(a, b) {
          var c, d2, e, f, g, h, k2;
          P(function(l) {
            switch (l.g) {
              case 1:
                return c = vc, a.P++, d2 = a.P, sa(l, 2), G(l, Zk(a.g.ia, c.ab), 4);
              case 4:
                ua(l, 3);
                break;
              case 2:
                if (e = va(l), a.g) a.g.onError(e);
              case 3:
                f = ef(b.mimeType, b.codecs), Ik(a.g.ia, f, a.j.sequenceMode, b.external), g = a.g.ia.$, (h = g.isTextVisible() || a.i.alwaysStreamText) && a.P == d2 && (k2 = Tm(a, b), a.h.set(c.ab, k2), Um(a, k2, 0)), H(l);
            }
          });
        }
        function Vm(a) {
          var b = a.h.get(tc);
          b && (Mm(b), Nm(b).catch(function() {
          }), a.G = a.h.get(tc), a.h.delete(tc), b.stream && b.stream.closeSegmentIndex && b.stream.closeSegmentIndex());
          a.C = null;
        }
        function Wm(a, b) {
          for (var c = a.g.Ya() < 0, d2 = t2(a.h.values()), e = d2.next(); !e.done; e = d2.next()) e = e.value, e.Ba && e.Ba.Vd(c), e.ka && e.ka.Vd(c);
          d2 = t2(a.m.values());
          for (e = d2.next(); !e.done; e = d2.next()) e.value.Vd(c);
          if (c = a.h.get("video")) {
            if (d2 = c.stream) {
              if (b) (b = d2.trickModeVideo) && !c.Sc && (Xm(a, b, false, 0, false), c.Sc = d2);
              else if (b = c.Sc) c.Sc = null, Xm(a, b, true, 0, false);
            }
          }
        }
        function Ym(a, b, c, d2, e, f) {
          c = c === void 0 ? false : c;
          d2 = d2 === void 0 ? 0 : d2;
          e = e === void 0 ? false : e;
          f = f === void 0 ? false : f;
          a.u = b;
          a.J && (b.video && Xm(a, b.video, c, d2, e, f), b.audio && Xm(a, b.audio, c, d2, e, f));
        }
        function Zm(a, b) {
          P(function(c) {
            if (c.g == 1) return a.G = null, a.C = b, a.J ? b.segmentIndex ? c.B(2) : G(c, b.createSegmentIndex(), 2) : c.return();
            Xm(a, b, true, 0, false);
            H(c);
          });
        }
        function $m(a) {
          var b = a.h.get(tc);
          b && Xm(a, b.stream, true, 0, true);
        }
        function an(a, b) {
          for (var c = t2(a.K.entries()), d2 = c.next(); !d2.done; d2 = c.next()) {
            var e = t2(d2.value);
            d2 = e.next().value;
            e = e.next().value;
            d2.includes(b.type) && (e(), a.K.delete(d2));
          }
        }
        function Xm(a, b, c, d2, e, f) {
          var g = a.h.get(b.type);
          g || b.type != tc ? g && (g.Sc && (b.trickModeVideo ? (g.Sc = b, b = b.trickModeVideo) : g.Sc = null), g.stream != b || e) && (a.m.has(b) ? g.ka = a.m.get(b) : g.ka && Cm(g.ka, b), b.type == tc && g.stream != b && (e = ef(b.mimeType, b.codecs), Ik(a.g.ia, e, a.j.sequenceMode, b.external)), !a.m.has(g.stream) && g.stream.closeSegmentIndex && (g.$a ? (e = "(" + g.type + ":" + g.stream.id + ")", a.K.has(e) || a.K.set(e, g.stream.closeSegmentIndex)) : g.stream.closeSegmentIndex()), e = g.stream.isAudioMuxedInVideo != b.isAudioMuxedInVideo, g.stream = b, g.Ba = null, g.Gg = !!f, b.dependencyStream ? g.Kc = Tm(a, b.dependencyStream) : g.Kc = null, e && (g.wb = null, g.yc = null, g.xc = null, b.isAudioMuxedInVideo && (b = null, g.type === "video" ? b = a.h.get("audio") : g.type === "audio" && (b = a.h.get("video")), b && (Nm(b).catch(function() {
          }), b.wb = null, b.yc = null, b.xc = null, bn(a, b), cn(a, b).catch(function(h) {
            if (a.g) a.g.onError(h);
          })))), c ? g.$c ? g.xg = true : g.$a ? (g.Yc = true, g.lf = d2, g.xg = true) : (Mm(g), dn(a, g, true, d2).catch(function(h) {
            if (a.g) a.g.onError(h);
          })) : g.$a || g.Fb || Um(a, g, 0), cn(a, g).catch(function(h) {
            if (a.g) a.g.onError(h);
          })) : Sm(a, b);
        }
        function cn(a, b) {
          var c, d2, e;
          return P(function(f) {
            if (f.g == 1) {
              if (!b.Pb) return f.return();
              c = b.stream;
              d2 = b.Pb;
              return c.segmentIndex ? f.B(2) : G(f, c.createSegmentIndex(), 2);
            }
            if (f.g != 4) return e = c.dependencyStream, !e || e.segmentIndex ? f.B(4) : G(f, e.createSegmentIndex(), 4);
            if (b.Pb != d2 || b.stream != c) return f.return();
            var g = a.g.gd();
            var h = Ok(a.g.ia, b.type), k2 = b.stream.segmentIndex.find(b.Sa ? b.Sa.endTime : g), l = k2 == null ? null : b.stream.segmentIndex.get(k2);
            k2 = l ? l.endByte ? l.endByte - l.startByte : null : null;
            l && !k2 && (k2 = (l.endTime - l.getStartTime()) * (b.stream.bandwidth || 0) / 8);
            k2 ? ((l = l.ha) && (k2 += (l.endByte ? l.endByte - l.startByte : null) || 0), l = a.g.getBandwidthEstimate(), g = k2 * 8 / l < (h || 0) - g - a.i.rebufferingGoal || b.Pb.h.g > k2 ? true : false) : g = false;
            g && b.Pb.abort();
            H(f);
          });
        }
        p.qd = function() {
          if (this.g) {
            for (var a = this.g.gd(), b = t2(this.h.keys()), c = b.next(); !c.done; c = b.next()) {
              var d2 = c.value;
              c = this.h.get(d2);
              var e = this.g.ia;
              d2 == tc ? (e = e.h, e = e.g == null || e.h == null ? false : a >= e.g && a < e.h) : (e = Nk(e, d2), e = Jj(e, a));
              if (!e) {
                this.M = 0;
                c.ka && (c.ka.g = null);
                if (c.type === "audio") {
                  e = t2(this.m.values());
                  for (var f = e.next(); !f.done; f = e.next()) f.value.g = null;
                }
                c.Ba = null;
                (Ok(this.g.ia, d2) != null || c.$a) && bn(this, c);
                c.Pb && (c.Pb.abort(), c.Pb = null);
                d2 === tc && (d2 = this.g.ia, d2.J && d2.J.$d());
                c.qd = true;
              }
            }
            en(this) && fn(this);
          }
        };
        function bn(a, b) {
          b.$c || b.Yc || (b.$a ? (b.Yc = true, b.lf = 0) : Mk(a.g.ia, b.type) == null ? b.Fb == null && Um(a, b, 0) : (Mm(b), dn(a, b, false, 0).catch(function(c) {
            if (a.g) a.g.onError(c);
          })));
        }
        function Rm(a, b) {
          var c, d2, e, f, g, h, k2, l;
          return P(function(m) {
            if (m.g == 1) {
              if (!a.u) throw new U(2, 5, 5006);
              c = gn(a, true);
              d2 = a.g.ia;
              return G(m, d2.init(c, a.j.sequenceMode, a.j.type, a.j.ignoreManifestTimestampsInSegmentsMode), 2);
            }
            jh(a.l);
            a.updateDuration();
            e = t2(c.keys());
            for (f = e.next(); !f.done; f = e.next()) g = f.value, h = c.get(g), a.h.has(g) || (k2 = Tm(a, h), b.has(h.id) && (l = b.get(h.id), sm(l, function(n, q, r2) {
              return hn(n, q, r2 || null, a.i.retryParameters, a.g.Bc);
            }), k2.ka = l), a.h.set(g, k2), Um(a, k2, 0));
            H(m);
          });
        }
        function Tm(a, b) {
          var c = {
            stream: b,
            type: b.type,
            Ba: null,
            ka: Om(a, b),
            Sa: null,
            wb: null,
            Hf: null,
            yc: null,
            xc: null,
            Ff: null,
            Gf: null,
            Sc: null,
            endOfStream: false,
            $a: false,
            Fb: null,
            Yc: false,
            lf: 0,
            xg: false,
            $c: false,
            qd: true,
            Gg: false,
            Th: false,
            oe: false,
            Pb: null,
            Kc: null
          };
          b.dependencyStream && (c.Kc = Tm(a, b.dependencyStream));
          return c;
        }
        function Om(a, b) {
          if (b.type === "video" && a.i.disableVideoPrefetch || b.type === "audio" && a.i.disableAudioPrefetch || b.type === tc && (b.mimeType == "application/cea-608" || b.mimeType == "application/cea-708") || b.type === tc && a.i.disableTextPrefetch) return null;
          if (a.m.has(b)) return a.m.get(b);
          var c = a.h.get(b.type);
          return (c = c && c.ka) && b === c.i ? c : a.i.segmentPrefetchLimit > 0 ? new rm(a.i.segmentPrefetchLimit, b, function(d2, e, f) {
            return hn(d2, e, f || null, a.i.retryParameters, a.g.Bc);
          }, a.g.Ya() < 0) : null;
        }
        function Pm(a) {
          for (var b = a.i.segmentPrefetchLimit, c = a.i.prefetchAudioLanguages, d2 = t2(a.j.variants), e = d2.next(), f = {}; !e.done; f = {
            Tb: void 0
          }, e = d2.next()) if (f.Tb = e.value, f.Tb.audio) if (a.m.has(f.Tb.audio)) {
            if (e = a.m.get(f.Tb.audio), Bm(e, b), !(b > 0 && c.some(/* @__PURE__ */ function(h) {
              return function(k2) {
                return yc(h.Tb.audio.language, k2);
              };
            }(f)))) {
              var g = a.h.get(f.Tb.audio.type);
              e !== (g && g.ka) && Am(e);
              a.m.delete(f.Tb.audio);
            }
          } else b <= 0 || !c.some(/* @__PURE__ */ function(h) {
            return function(k2) {
              return yc(h.Tb.audio.language, k2);
            };
          }(f)) || !(e = Om(a, f.Tb.audio)) || (f.Tb.audio.segmentIndex || f.Tb.audio.createSegmentIndex(), a.m.set(f.Tb.audio, e));
        }
        p.updateDuration = function() {
          var a = hd(), b = this.j.presentationTimeline.getDuration();
          b < Infinity ? (a && (this.A && this.A.stop(), fl(this.g.ia)), this.g.ia.yb(b)) : a ? (this.A && this.A.za(0.5), this.g.ia.yb(Infinity)) : this.g.ia.yb(4294967296);
        };
        function jn(a, b) {
          var c, d2, e, f, g, h, k2, l, m;
          return P(function(n) {
            switch (n.g) {
              case 1:
                jh(a.l);
                c = vc;
                if (b.$a || b.Fb == null || b.$c) return n.return();
                b.Fb = null;
                if (!b.Yc) {
                  n.B(2);
                  break;
                }
                return G(n, dn(a, b, b.xg, b.lf), 3);
              case 3:
                return n.return();
              case 2:
                an(a, b);
                if (b.stream.segmentIndex) {
                  n.B(4);
                  break;
                }
                d2 = b.stream;
                sa(n, 5);
                return G(n, b.stream.createSegmentIndex(), 7);
              case 7:
                ua(n, 6);
                break;
              case 5:
                return e = va(n), G(n, kn(a, b, e), 8);
              case 8:
                return n.return();
              case 6:
                if (d2 != b.stream) return d2.closeSegmentIndex && d2.closeSegmentIndex(), b.$a || b.Fb || Um(a, b, 0), n.return();
              case 4:
                if (!b.Kc) {
                  n.B(9);
                  break;
                }
                if (b.Kc.stream.segmentIndex) {
                  n.B(9);
                  break;
                }
                sa(n, 11);
                return G(n, b.Kc.stream.createSegmentIndex(), 13);
              case 13:
                ua(n, 9);
                break;
              case 11:
                va(n);
              case 9:
                sa(n, 14);
                f = ln(a, b);
                f != null && (Um(a, b, f), b.oe = false);
                ua(n, 15);
                break;
              case 14:
                return g = va(n), G(n, kn(a, b, g), 16);
              case 16:
                return n.return();
              case 15:
                if (b.type === c.ab) return n.return();
                h = [b];
                k2 = b.type === c.na ? c.Ja : c.na;
                (l = a.h.get(k2)) && h.push(l);
                if (!a.J || !h.every(function(q) {
                  return q.endOfStream;
                })) {
                  n.B(0);
                  break;
                }
                return G(n, a.g.ia.endOfStream(), 18);
              case 18:
                jh(a.l), m = a.g.ia.getDuration(), m != 0 && m < a.j.presentationTimeline.getDuration() && a.j.presentationTimeline.yb(m), H(n);
            }
          });
        }
        function ln(a, b) {
          if (mn(b)) return Wk(a.g.ia, b.stream.originalId || ""), null;
          b.type == tc && Xk(a.g.ia);
          if (b.stream.isAudioMuxedInVideo && b.type == "audio") return null;
          if (b.type != tc && Gk(a.g.ia)) return nn(a, true), null;
          var c = a.i.updateIntervalSeconds / Math.max(1, Math.abs(a.g.Ya()));
          if (!Lk(a.g.ia) && b.type != tc) return c / 2;
          var d2 = a.g.gd();
          if (b.type === "audio") for (var e = t2(a.m.keys()), f = e.next(); !f.done; f = e.next()) f = a.m.get(f.value), f.ib(d2, true), tm(f, d2);
          e = b.Sa ? b.Sa.endTime : d2;
          var g = Pk(a.g.ia, b.type, d2);
          f = Math.max(1, Math.max(a.i.rebufferingGoal, a.i.bufferingGoal) * a.F);
          var h = a.j.presentationTimeline.getDuration() - e, k2 = Ok(a.g.ia, b.type);
          if (h < 1e-6 && k2) return b.endOfStream = true, b.type == "video" && (a = a.h.get(tc)) && mn(a) && (a.endOfStream = true), null;
          b.endOfStream = false;
          if (g >= f) return c / 2;
          h = !b.Ba;
          k2 = on3(a, b, d2, k2);
          if (!k2) return c;
          g = b.wb;
          var l = k2.ha;
          g && l && Bj(l, g) && (g.g = l.g);
          g = false;
          h && b.Gg && (g = true, b.Gg = false);
          h = Infinity;
          l = Array.from(a.h.values());
          l = t2(l);
          for (var m = l.next(); !m.done; m = l.next()) m = m.value, mn(m) || m.Ba && !m.Ba.current() || (h = Math.min(h, m.Sa ? m.Sa.endTime : d2));
          if (e >= h + a.j.presentationTimeline.h) return c;
          b.ka && b.Ba && !a.m.has(b.stream) && (b.ka.ib(k2.startTime + 1e-3), tm(b.ka, k2.startTime).catch(function() {
          }));
          if (en(a) && pn(a, b, k2)) return null;
          qn(a, b, d2, k2, g).catch(function() {
          });
          b.Kc && rn(a, b.Kc, d2, f);
          return null;
        }
        function on3(a, b, c, d2) {
          if (b.Ba) return (c = b.Ba.current()) && b.Sa && Math.abs(b.Sa.startTime - c.startTime) < 1e-3 && (c = b.Ba.next().value), c;
          if (b.Sa || d2) return c = b.Sa ? b.Sa.endTime : d2, a = a.g.Ya() < 0, b.stream.segmentIndex && (b.Ba = b.stream.segmentIndex.dc(c, false, a)), b.Ba && b.Ba.next().value;
          d2 = a.j.sequenceMode || en(a) ? 0 : a.i.inaccurateManifestTolerance;
          var e = Math.max(c - d2, 0);
          a = a.g.Ya() < 0;
          var f = null;
          d2 && (b.stream.segmentIndex && (b.Ba = b.stream.segmentIndex.dc(e, false, a)), f = b.Ba && b.Ba.next().value);
          f || (b.stream.segmentIndex && (b.Ba = b.stream.segmentIndex.dc(c, false, a)), f = b.Ba && b.Ba.next().value);
          return f;
        }
        function qn(a, b, c, d2, e) {
          var f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F;
          return P(function(B) {
            switch (B.g) {
              case 1:
                f = vc;
                g = b.stream;
                h = b.Ba;
                b.$a = true;
                sa(B, 2);
                if (d2.Oc() == 2) throw new U(1, 1, 1011);
                return G(B, sn(a, b, d2, e), 4);
              case 4:
                jh(a.l);
                if (a.D) return B.return();
                k2 = g.mimeType == "video/mp4" || g.mimeType == "audio/mp4";
                l = window7.ReadableStream;
                if ((m = a.i.lowLatencyMode && a.j.isLowLatency) && l && k2 && (a.j.type != "HLS" || d2.m)) return r2 = new Uint8Array(0), w = u = false, y = function(E) {
                  var I, J, K, L;
                  return P(function(M) {
                    switch (M.g) {
                      case 1:
                        if (u) return M.return();
                        w = true;
                        jh(a.l);
                        if (a.D) return M.return();
                        sa(M, 2);
                        r2 = mc(r2, E);
                        I = false;
                        J = 0;
                        new ph().box("mdat", function(N) {
                          J = N.size + N.start;
                          I = true;
                        }).parse(r2, false, true);
                        if (!I) {
                          M.B(4);
                          break;
                        }
                        K = r2.subarray(0, J);
                        r2 = r2.subarray(J);
                        return G(M, tn(a, b, c, g, d2, K, true, e), 5);
                      case 5:
                        b.ka && b.Ba && tm(b.ka, d2.startTime, true);
                      case 4:
                        ua(M, 0);
                        break;
                      case 2:
                        v = L = va(M), H(M);
                    }
                  });
                }, G(B, un(a, b, d2, y), 9);
                n = un(a, b, d2);
                return G(B, n, 7);
              case 7:
                q = B.h;
                jh(a.l);
                if (a.D) return B.return();
                jh(a.l);
                return b.Yc ? (b.$a = false, Um(a, b, 0), B.return()) : G(B, tn(a, b, c, g, d2, q, false, e), 6);
              case 9:
                z = B.h;
                if (v) throw v;
                if (w) {
                  B.B(10);
                  break;
                }
                u = true;
                jh(a.l);
                return a.D ? B.return() : b.Yc ? (b.$a = false, Um(a, b, 0), B.return()) : G(B, tn(a, b, c, g, d2, z, false, e), 10);
              case 10:
                b.ka && b.Ba && tm(b.ka, d2.startTime, true);
              case 6:
                jh(a.l);
                if (a.D) return B.return();
                b.Sa = d2;
                h.next();
                b.$a = false;
                b.Th = false;
                A = a.g.ia.cc();
                C = A[b.type];
                gb(JSON.stringify(C));
                b.Yc || (D = null, b.type === f.Ja ? D = a.h.get(f.na) : b.type === f.na && (D = a.h.get(f.Ja)), D && D.type == f.na ? a.g.Rf(d2, b.stream, D.stream.isAudioMuxedInVideo) : a.g.Rf(d2, b.stream, b.stream.codecs.includes(",")));
                Mm(b);
                Um(a, b, 0);
                ua(B, 0);
                break;
              case 2:
                F = va(B);
                jh(a.l, F);
                if (a.D) return B.return();
                b.$a = false;
                if (F.code == 7001) b.$a = false, Mm(b), Um(a, b, 0), B.B(0);
                else if (b.type == f.ab && a.i.ignoreTextStreamFailures) a.h.delete(f.ab), B.B(0);
                else {
                  if (F.code == 3017) return G(B, vn(a, b, F), 0);
                  b.oe = true;
                  F.category == 1 && b.ka && zm(b.ka, d2);
                  F.severity = 2;
                  return G(B, kn(a, b, F), 0);
                }
            }
          });
        }
        function rn(a, b, c, d2) {
          var e, f, g, h, k2, l, m, n, q, r2, u;
          return P(function(w) {
            switch (w.g) {
              case 1:
                e = b.stream;
                for (h = (g = (f = e.segmentIndex) && f.dc(c)) && g.next().value; h && a.L.includes(h.startTime); ) h = g && g.next().value;
                if (!h) {
                  w.B(0);
                  break;
                }
                k2 = h.ha;
                if (!k2 || Bj(k2, b.wb)) {
                  w.B(3);
                  break;
                }
                b.wb = k2;
                sa(w, 4);
                return G(w, un(a, b, k2), 6);
              case 6:
                l = w.h;
                var v = a.g.ia;
                v.M && ad(v.M, l, 0, e);
                a.L = [];
                ua(w, 3);
                break;
              case 4:
                throw m = va(w), b.wb = null, m;
              case 3:
                if (b.Sa && b.Sa == h) {
                  w.B(0);
                  break;
                }
                b.Sa = h;
                sa(w, 8);
                return G(w, un(a, b, h), 10);
              case 10:
                n = w.h;
                v = a.g.ia;
                v.M && ad(v.M, n, 0, e);
                a.L.push(h.startTime);
                ua(w, 9);
                break;
              case 8:
                throw q = va(w), b.Sa = null, q;
              case 9:
                r2 = Math.max.apply(Math, [0].concat(x(a.L)));
                u = a.g.gd();
                if (u + d2 > r2) return G(w, rn(a, b, h.startTime, d2), 0);
                w.B(0);
            }
          });
        }
        function vn(a, b, c) {
          var d2, e, f, g, h, k2;
          return P(function(l) {
            if (l.g == 1) {
              d2 = Array.from(a.h.values());
              if (e = d2.some(function(m) {
                return m != b && m.Th;
              })) return l.B(2);
              f = a.i.maxDisabledTime === 0 && c.code == 1011 ? 1 : a.i.maxDisabledTime;
              if (g = a.g.disableStream(b.stream, f)) return l.return();
              if (a.i.avoidEvictionOnQuotaExceededError) return Um(a, b, 4), l.return();
              h = Math.round(100 * a.F);
              if (h > 20) a.F -= 0.2;
              else if (h > 4) a.F -= 0.04;
              else return b.oe = true, a.D = true, a.g.onError(c), l.return();
              b.Th = true;
              k2 = a.g.gd();
              return G(l, wn(a, b, k2), 2);
            }
            Um(a, b, 4);
            H(l);
          });
        }
        function sn(a, b, c, d2) {
          var e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A;
          return P(function(C) {
            switch (C.g) {
              case 1:
                e = vc;
                f = b.Sa == null;
                g = [];
                h = Math.max(0, Math.max(c.appendWindowStart, a.V) - 0.1);
                k2 = Math.min(c.appendWindowEnd, a.S) + 0.1;
                l = c.codecs || b.stream.codecs;
                m = mf(l);
                n = nf(c.mimeType || b.stream.mimeType);
                q = c.timestampOffset;
                if (q == b.Hf && h == b.yc && k2 == b.xc && m == b.Ff && n == b.Gf) {
                  C.B(2);
                  break;
                }
                r2 = b.Ff && b.Gf && zl(a.g.ia, b.type, n, l, gn(a));
                if (!r2) {
                  C.B(3);
                  break;
                }
                u = null;
                b.type === e.Ja ? u = a.h.get(e.na) : b.type === e.na && (u = a.h.get(e.Ja));
                if (!u) {
                  C.B(3);
                  break;
                }
                return G(C, Nm(u).catch(function() {
                }), 5);
              case 5:
                u.wb = null, u.yc = null, u.xc = null, bn(a, u);
              case 3:
                return G(C, xn(a, b, q, h, k2, c, m, n), 2);
              case 2:
                return Bj(c.ha, b.wb) || (b.wb = c.ha, c.l && c.ha && (w = un(a, b, c.ha), v = function() {
                  var D, F, B, E, I, J, K, L, M;
                  return P(function(N) {
                    switch (N.g) {
                      case 1:
                        return sa(N, 2), G(N, w, 4);
                      case 4:
                        return D = N.h, jh(a.l), F = null, B = /* @__PURE__ */ new Map(), E = {
                          projection: null,
                          hfov: null
                        }, I = new ph(), I.box("moov", uh).box("trak", uh).box("mdia", uh).W("mdhd", function(O) {
                          F = Oi(O.reader, O.version).timescale;
                        }).box("hdlr", function(O) {
                          O = O.reader;
                          O.skip(8);
                          switch (O.nd()) {
                            case "soun":
                              B.set(e.na, F);
                              break;
                            case "vide":
                              B.set(e.Ja, F);
                          }
                          F = null;
                        }), b.type === e.Ja && I.box("minf", uh).box("stbl", uh).W("stsd", wh).box("encv", xh).box("avc1", xh).box("avc3", xh).box("hev1", xh).box("hvc1", xh).box("dvav", xh).box("dva1", xh).box("dvh1", xh).box("dvhe", xh).box("dvc1", xh).box("dvi1", xh).box("vexu", uh).box("proj", uh).W("prji", function(O) {
                          O = O.reader.nd();
                          E.projection = O;
                        }).box("hfov", function(O) {
                          O = O.reader.X() / 1e3;
                          E.hfov = O;
                        }), I.parse(D, true, true), b.type === e.Ja && yn(a, E), B.has(b.type) ? c.ha.timescale = B.get(b.type) : F != null && (c.ha.timescale = F), J = b.stream.segmentIndex, J instanceof bm && (K = dm(J, c.startTime)), L = b.stream.closedCaptions && b.stream.closedCaptions.size > 0, G(N, a.g.Ji(b.type, D), 5);
                      case 5:
                        return G(N, Rk(a.g.ia, b.type, D, null, b.stream, L, b.qd, d2, false, false, K), 6);
                      case 6:
                        ua(N, 0);
                        break;
                      case 2:
                        throw M = va(N), b.wb = null, M;
                    }
                  });
                }, y = c.startTime, f && (z = Ok(a.g.ia, b.type), z != null && (y = z)), a.g.Tl(y, c.ha), g.push(v()))), A = b.Sa ? b.Sa.i : -1, c.i != A && g.push(cl(a.g.ia, b.type, c.startTime)), G(C, Promise.all(g), 0);
            }
          });
        }
        function xn(a, b, c, d2, e, f, g, h) {
          var k2, l, m, n, q;
          return P(function(r2) {
            switch (r2.g) {
              case 1:
                k2 = vc;
                l = gn(a);
                sa(r2, 2);
                b.yc = d2;
                b.xc = e;
                g && (b.Ff = g);
                h && (b.Gf = h);
                b.Hf = c;
                m = a.j.sequenceMode || a.j.type == "HLS";
                n = null;
                b.type === k2.Ja ? n = a.h.get(k2.na) : b.type === k2.na && (n = a.h.get(k2.Ja));
                if (!(n && n.stream && n.stream.isAudioMuxedInVideo)) {
                  r2.B(4);
                  break;
                }
                return G(r2, $k(a.g.ia, n.type, c, d2, e, m, n.stream.mimeType, n.stream.codecs, l), 4);
              case 4:
                return G(r2, $k(a.g.ia, b.type, c, d2, e, m, f.mimeType || b.stream.mimeType, f.codecs || b.stream.codecs, l), 6);
              case 6:
                ua(r2, 0);
                break;
              case 2:
                throw q = va(r2), b.yc = null, b.xc = null, b.Ff = null, b.Gf = null, b.Hf = null, q;
            }
          });
        }
        function tn(a, b, c, d2, e, f, g, h) {
          g = g === void 0 ? false : g;
          h = h === void 0 ? false : h;
          var k2, l, m, n, q;
          return P(function(r2) {
            switch (r2.g) {
              case 1:
                return k2 = d2.closedCaptions && d2.closedCaptions.size > 0, a.i.shouldFixTimestampOffset && (l = d2.mimeType == "video/mp4" || d2.mimeType == "audio/mp4", m = null, e.ha && (m = e.ha.timescale), (n = l && m && d2.type === "video" && a.j.type == "DASH") && new ph().box("moof", uh).box("traf", uh).W("tfdt", function(u) {
                  var w, v, y, z, A, C;
                  return P(function(D) {
                    w = Ni(u.reader, u.version);
                    v = w.baseMediaDecodeTime;
                    if (!v) return D.return();
                    y = -v / m;
                    z = Number(b.Hf) || 0;
                    if (!(z < y)) return D.B(0);
                    A = b.yc;
                    C = b.xc;
                    return G(D, xn(a, b, y, A, C, e), 0);
                  });
                }).parse(f, false, g)), G(r2, wn(a, b, c), 2);
              case 2:
                return jh(a.l), q = b.qd, b.qd = false, G(r2, a.g.Ji(b.type, f), 3);
              case 3:
                return G(r2, Rk(a.g.ia, b.type, f, e, d2, k2, q, h, g), 4);
              case 4:
                jh(a.l), H(r2);
            }
          });
        }
        function wn(a, b, c) {
          var d2, e, f, g, h, k2, l, m, n;
          return P(function(q) {
            if (q.g == 1) {
              d2 = b.stream.segmentIndex;
              d2 instanceof bm && (d2.ib(a.j.presentationTimeline.Nb()), e = [], cm(d2, function(r2) {
                e.push(r2.mf());
              }));
              f = Math.max(a.i.bufferBehind * a.F, a.j.presentationTimeline.h);
              g = Mk(a.g.ia, b.type);
              if (g == null) return a.G == b && (a.G = null), q.return();
              h = c - g;
              k2 = a.i.evictionGoal;
              l = a.j.presentationTimeline.ec();
              m = a.j.presentationTimeline.Mb();
              n = h - f;
              m - l > k2 && (n = Math.max(h - f, l - k2 - g));
              return n <= k2 ? q.return() : G(q, a.g.ia.remove(b.type, g, g + n, e), 2);
            }
            if (q.g != 4) return jh(a.l), a.G ? G(q, wn(a, a.G, c), 4) : q.B(0);
            jh(a.l);
            H(q);
          });
        }
        function mn(a) {
          return a && a.type == tc && (a.stream.mimeType == "application/cea-608" || a.stream.mimeType == "application/cea-708");
        }
        function un(a, b, c, d2) {
          var e, f, g, h, k2;
          return P(function(l) {
            switch (l.g) {
              case 1:
                if (e = c.fc()) return l.return(e);
                f = null;
                if (b.ka) {
                  var m = b.ka, n = m.h;
                  c instanceof Aj && (n = m.j);
                  n.has(c) ? (m = n.get(c), d2 && (m.ni = d2), f = m.ze) : f = null;
                }
                f || (f = hn(c, b.stream, d2 || null, a.i.retryParameters, a.g.Bc));
                g = 0;
                b.Ba && (g = b.Ba.h);
                b.Pb = f;
                return G(l, f.promise, 2);
              case 2:
                h = l.h;
                b.Pb = null;
                k2 = h.data;
                if (!c.aesKey) {
                  l.B(3);
                  break;
                }
                return G(l, Im(k2, c.aesKey, g), 4);
              case 4:
                k2 = l.h;
              case 3:
                return l.return(k2);
            }
          });
        }
        function hn(a, b, c, d2, e, f) {
          f = f === void 0 ? false : f;
          var g = a instanceof Cj ? a : void 0, h = g ? 1 : 0;
          a = Jm(a.T(), a.startByte, a.endByte, d2, c);
          a.contentType = b.type;
          return e.request(gh, a, {
            type: h,
            stream: b,
            segment: g,
            isPreload: f
          });
        }
        function dn(a, b, c, d2) {
          var e, f;
          return P(function(g) {
            if (g.g == 1) return b.Yc = false, b.xg = false, b.lf = 0, b.$c = true, b.Sa = null, b.Ba = null, b.ka && !a.m.has(b.stream) && Am(b.ka), d2 ? (e = a.g.gd(), f = a.g.ia.getDuration(), G(g, a.g.ia.remove(b.type, e + d2, f), 3)) : G(g, Zk(a.g.ia, b.type), 4);
            if (g.g != 3) return jh(a.l), c ? G(g, a.g.ia.flush(b.type), 3) : g.B(3);
            jh(a.l);
            b.$c = false;
            b.endOfStream = false;
            b.$a || b.Fb || Um(a, b, 0);
            H(g);
          });
        }
        function Um(a, b, c) {
          var d2 = b.type;
          if (d2 != tc || a.h.has(d2)) b.Fb = new Bf(function() {
            var e;
            return P(function(f) {
              if (f.g == 1) return sa(f, 2), G(f, jn(a, b), 4);
              if (f.g != 2) return ua(f, 0);
              e = va(f);
              if (a.g) a.g.onError(e);
              H(f);
            });
          }).Y(c);
        }
        function Mm(a) {
          a.Fb != null && (a.Fb.stop(), a.Fb = null);
        }
        function Nm(a) {
          return P(function(b) {
            return a.Pb ? G(b, a.Pb.abort(), 0) : b.B(0);
          });
        }
        function kn(a, b, c) {
          var d2;
          return P(function(e) {
            if (e.g == 1) return c.code == 3024 ? (b.$a = false, Mm(b), Um(a, b, 0), e.return()) : G(e, Lg(a.R), 2);
            jh(a.l);
            if (c.category === 1 && c.code != 1003) {
              if (b.Sc) return Wm(a, false), e.return();
              d2 = a.i.maxDisabledTime === 0 && c.code == 1011 ? 1 : a.i.maxDisabledTime;
              c.handled = a.g.disableStream(b.stream, d2);
              c.handled && (c.severity = 1);
            }
            if (!c.handled || c.code != 1011) a.g.onError(c);
            c.handled || a.i.failureCallback(c);
            H(e);
          });
        }
        function nn(a, b) {
          b = b === void 0 ? false : b;
          var c = c === void 0 ? true : c;
          var d2, e, f, g, h;
          return P(function(k2) {
            if (k2.g == 1) {
              d2 = Date.now() / 1e3;
              e = a.i.minTimeBetweenRecoveries;
              if (!b) {
                if (!a.i.allowMediaSourceRecoveries || d2 - a.M < e) return k2.return(false);
                a.M = d2;
              }
              f = vc;
              if (g = a.h.get(f.na)) g.wb = null, g.yc = null, g.xc = null, c && bn(a, g), Nm(g).catch(function() {
              }), g.Ba && g.Ba.Wh(), Mm(g);
              if (h = a.h.get(f.Ja)) h.wb = null, h.yc = null, h.xc = null, c && bn(a, h), Nm(h).catch(function() {
              }), h.Ba && h.Ba.Wh(), Mm(h);
              return G(k2, tl(a.g.ia, gn(a)), 2);
            }
            !h || h.$c || h.$a || h.Fb || Um(a, h, 0);
            !g || g.$c || g.$a || g.Fb || Um(a, g, 0);
            return k2.return(true);
          });
        }
        function yn(a, b) {
          if (a.O.projection != b.projection || a.O.hfov != b.hfov) {
            if (b.projection != null || b.hfov != null) {
              var c = (/* @__PURE__ */ new Map()).set("detail", b);
              c = new T("spatialvideoinfo", c);
            } else c = new T("nospatialvideoinfo");
            c.cancelable = true;
            a.g.onEvent(c);
            a.O = b;
          }
        }
        function en(a) {
          return a.i.crossBoundaryStrategy !== "keep" ? true : false;
        }
        function fn(a) {
          if (en(a)) {
            a.I.stop();
            var b = a.g.gd(), c = a.h.get("video") || a.h.get("audio");
            c && (c = c.wb) && c.g !== null && (b = c.g - b, b < 0 || b > 1 || (a.H = c.g + 0.1, a.I.Y(b)));
          }
        }
        function pn(a, b, c) {
          if (b.type === tc) return false;
          var d2 = b.wb;
          if (!d2) return false;
          var e = c.ha;
          c = d2.g !== e.g;
          a.i.crossBoundaryStrategy === "reset_to_encrypted" && (d2.encrypted || e.encrypted || (c = false), d2.encrypted && (a.i.crossBoundaryStrategy = "keep"));
          a.i.crossBoundaryStrategy === "RESET_ON_ENCRYPTION_CHANGE" && d2.encrypted == e.encrypted && (c = false);
          if (c && b.qd) {
            var f = a.g.video, g = f.paused;
            nn(a, true).then(function() {
              var h = (/* @__PURE__ */ new Map()).set("oldEncrypted", d2.encrypted).set("newEncrypted", e.encrypted);
              a.g.onEvent(new T("boundarycrossed", h));
              g || f.play();
            });
          }
          return c;
        }
        function gn(a, b) {
          b = b === void 0 ? false : b;
          var c = /* @__PURE__ */ new Map();
          a.u.audio && c.set("audio", a.u.audio);
          a.u.video && c.set("video", a.u.video);
          b && a.C && c.set(tc, a.C);
          return c;
        }
        ;
        function zn() {
        }
        function An(a, b, c, d2, e) {
          var f = e in d2;
          var g = f ? c.constructor == Object && Object.keys(d2).length == 0 : c.constructor == Object && Object.keys(c).length == 0;
          var h = f || g, k2 = true, l;
          for (l in b) {
            var m = e + "." + l, n = f ? d2[e] : c[l];
            h || l in c ? b[l] === void 0 ? n === void 0 || h ? delete a[l] : a[l] = Hd(n) : g ? a[l] = b[l] : n.constructor == Object && b[l] && b[l].constructor == Object ? (a[l] || (a[l] = Hd(n)), m = An(a[l], b[l], n, d2, m), k2 = k2 && m) : typeof b[l] != typeof n || b[l] == null || typeof b[l] != "function" && b[l].constructor != n.constructor ? (ab("Invalid config, wrong type for " + m), k2 = false) : typeof c[l] == "function" && c[l].length != b[l].length ? (bb("Unexpected number of arguments for " + m), a[l] = b[l]) : a[l] = Array.isArray(a[l]) ? b[l].slice() : b[l] : (ab("Invalid config, unrecognized key " + m), k2 = false);
          }
          return k2;
        }
        function Bn(a, b) {
          for (var c = {}, d2 = c, e = 0, f = 0; ; ) {
            e = a.indexOf(".", e);
            if (e < 0) break;
            if (e == 0 || a[e - 1] != "\\") f = a.substring(f, e).replace(/\\\./g, "."), d2[f] = {}, d2 = d2[f], f = e + 1;
            e += 1;
          }
          d2[a.substring(f).replace(/\\\./g, ".")] = b;
          return c;
        }
        function Cn(a, b) {
          return a && b;
        }
        function Dn(a, b) {
          function c(f) {
            for (var g = t2(Object.keys(f)), h = g.next(); !h.done; h = g.next()) if (h = h.value, !(f[h] instanceof HTMLElement)) if (e(f[h]) && Object.keys(f[h]).length === 0) delete f[h];
            else {
              var k2 = f[h];
              Array.isArray(k2) && k2.length === 0 ? delete f[h] : typeof f[h] == "function" ? delete f[h] : e(f[h]) && (c(f[h]), Object.keys(f[h]).length === 0 && delete f[h]);
            }
          }
          function d2(f, g) {
            return Object.keys(f).reduce(function(h, k2) {
              var l = f[k2];
              if (g.hasOwnProperty(k2)) {
                if (l instanceof HTMLElement && g[k2] instanceof HTMLElement) l.isEqualNode(g[k2]) || (h[k2] = l);
                else if (e(l) && e(g[k2])) {
                  if (l = d2(l, g[k2]), Object.keys(l).length > 0 || !e(l)) h[k2] = l;
                } else Array.isArray(l) && Array.isArray(g[k2]) ? vd(l, g[k2]) || (h[k2] = l) : Number.isNaN(l) && Number.isNaN(g[k2]) || l !== g[k2] && (h[k2] = l);
              } else h[k2] = l;
              return h;
            }, {});
          }
          function e(f) {
            return f && typeof f === "object" && !Array.isArray(f);
          }
          a = d2(a, b);
          c(a);
          return a;
        }
        S("shaka.util.ConfigUtils", zn);
        zn.getDifferenceFromConfigObjects = Dn;
        zn.convertToConfigObject = Bn;
        zn.mergeConfigObjects = An;
        S("shaka.config.RepeatMode", {
          OFF: 0,
          ALL: 1,
          SINGLE: 2
        });
        function En() {
        }
        function Fn(a) {
          a = $b(a);
          return new rb(a).Ib;
        }
        function Gn(a, b, c) {
          function d2(h) {
            Pb(f).setUint32(g, h.byteLength, true);
            g += 4;
            f.set(Lb(h), g);
            g += h.byteLength;
          }
          if (!c || !c.byteLength) throw new U(2, 6, 6015);
          var e;
          typeof b == "string" ? e = bc(b, true) : e = b;
          a = $b(a);
          a = bc(a, true);
          var f = new Uint8Array(12 + a.byteLength + e.byteLength + c.byteLength), g = 0;
          d2(a);
          d2(e);
          d2(c);
          return f;
        }
        function Hn(a, b, c) {
          if (b !== "skd") return a;
          b = c.serverCertificate;
          c = $b(a).split("skd://").pop();
          return Gn(a, c, b);
        }
        function In(a, b) {
          a === 2 && (a = b.drmInfo) && Cg(a.keySystem) && (b.headers["Content-Type"] = "application/octet-stream");
        }
        S("shaka.drm.FairPlay", En);
        En.commonFairPlayResponse = function(a, b) {
          if (a === 2 && (a = b.originalRequest.drmInfo) && Cg(a.keySystem)) {
            try {
              var c = Xb(b.data);
            } catch (e) {
              return;
            }
            a = false;
            c = c.trim();
            c.substr(0, 5) === "<ckc>" && c.substr(-6) === "</ckc>" && (c = c.slice(5, -6), a = true);
            if (!a) try {
              var d2 = JSON.parse(c);
              d2.ckc && (c = d2.ckc, a = true);
              d2.CkcMessage && (c = d2.CkcMessage, a = true);
              d2.License && (c = d2.License, a = true);
            } catch (e) {
            }
            a && (b.data = Mb(jc(c)));
          }
        };
        En.muxFairPlayRequest = function(a, b) {
          In(a, b);
        };
        En.expressplayFairPlayRequest = function(a, b) {
          if (a === 2) {
            var c = b.drmInfo;
            c && Cg(c.keySystem) && In(a, b);
          }
        };
        En.conaxFairPlayRequest = function(a, b) {
          In(a, b);
        };
        En.ezdrmFairPlayRequest = function(a, b) {
          In(a, b);
        };
        En.verimatrixFairPlayRequest = function(a, b) {
          a === 2 && (a = b.drmInfo) && Cg(a.keySystem) && (a = Lb(b.body), a = ic(a), b.headers["Content-Type"] = "application/x-www-form-urlencoded", b.body = ac("spc=" + a));
        };
        En.muxInitDataTransform = function(a, b, c) {
          return Hn(a, b, c);
        };
        En.expressplayInitDataTransform = function(a, b, c) {
          return Hn(a, b, c);
        };
        En.conaxInitDataTransform = function(a, b, c) {
          if (b !== "skd") return a;
          b = c.serverCertificate;
          c = $b(a).split("skd://").pop().split("?").shift();
          c = window7.atob(c);
          var d2 = new ArrayBuffer(c.length * 2);
          d2 = Ob(d2);
          for (var e = 0, f = c.length; e < f; e++) d2[e] = c.charCodeAt(e);
          return Gn(a, d2, b);
        };
        En.ezdrmInitDataTransform = function(a, b, c) {
          if (b !== "skd") return a;
          b = c.serverCertificate;
          c = $b(a).split(";").pop();
          return Gn(a, c, b);
        };
        En.verimatrixInitDataTransform = function(a, b, c) {
          return Hn(a, b, c);
        };
        En.initDataTransform = Gn;
        En.defaultGetContentId = Fn;
        En.isFairPlaySupported = function() {
          var a;
          return P(function(b) {
            if (b.g == 1) return a = {
              initDataTypes: ["cenc", "sinf", "skd"],
              videoCapabilities: [{
                contentType: 'video/mp4; codecs="avc1.42E01E"'
              }]
            }, sa(b, 2), G(b, navigator.requestMediaKeySystemAccess("com.apple.fps", [a]), 4);
            if (b.g != 2) return b.return(true);
            va(b);
            return b.return(false);
          });
        };
        function Jn() {
          this.g = null;
        }
        Jn.prototype.configure = function(a) {
          this.g = a;
        };
        Jn.prototype.getConfiguration = function() {
          return this.g;
        };
        Jn.prototype.create = function(a) {
          var b;
          if (this.g.language) {
            var c = Kn(a, this.g.language);
            c.length && (b = c);
          }
          b || (b = a.filter(function(f) {
            return f.primary;
          }), b = b.length ? b : a);
          a = Ln(b, this.g.role);
          a.length && (b = a);
          this.g.videoLayout && (a = Mn(b, this.g.videoLayout), a.length && (b = a));
          this.g.Qc && (a = Nn(b, this.g.Qc), a.length && (b = a));
          var d2 = [this.g.channelCount, this.g.preferredAudioChannelCount];
          a = d2.filter(function(f, g) {
            return f && d2.indexOf(f) === g;
          });
          if (a.length) {
            for (a = t2(a), c = a.next(); !c.done; c = a.next()) if (c = On(b, c.value), c.length) {
              b = c;
              break;
            }
          }
          this.g.Zc && (a = Pn(b, this.g.Zc), a.length && (b = a));
          this.g.Yd && (a = Qn(b, this.g.Yd), a.length && (b = a));
          a = Rn(b, this.g.spatialAudio);
          a.length && (b = a);
          var e = [this.g.audioCodec, this.g.ae].concat(x(this.g.preferredAudioCodecs));
          a = e.filter(function(f, g) {
            return f && e.indexOf(f) === g;
          });
          if (a.length) {
            for (a = t2(a), c = a.next(); !c.done; c = a.next()) if (c = Sn(b, c.value), c.length) {
              b = c;
              break;
            }
          }
          return new ri(b[0], b, !(this.g.codecSwitchingStrategy == "smooth" && fd()));
        };
        function Kn(a, b) {
          b = zc(b);
          var c = Hc(b, a.map(function(d2) {
            return Gc(d2);
          }));
          return c ? a.filter(function(d2) {
            return c == Gc(d2);
          }) : [];
        }
        function Ln(a, b) {
          return a.filter(function(c) {
            return c.audio ? b ? c.audio.roles.includes(b) : c.audio.roles.length == 0 : false;
          });
        }
        function Pn(a, b) {
          return a.filter(function(c) {
            return c.audio && c.audio.label ? c.audio.label.toLowerCase() == b.toLowerCase() : false;
          });
        }
        function Qn(a, b) {
          return a.filter(function(c) {
            return c.video && c.video.label ? c.video.label.toLowerCase() == b.toLowerCase() : false;
          });
        }
        function On(a, b) {
          return a.filter(function(c) {
            return c.audio && c.audio.channelsCount && c.audio.channelsCount > b ? false : true;
          }).sort(function(c, d2) {
            return c.audio || d2.audio ? c.audio ? d2.audio ? (d2.audio.channelsCount || 0) - (c.audio.channelsCount || 0) : 1 : -1 : 0;
          });
        }
        function Nn(a, b) {
          if (b == "AUTO") {
            var c = a.some(function(d2) {
              return d2.video && d2.video.hdr && d2.video.hdr == "HLG" ? true : false;
            });
            b = Tn(c);
          }
          return a.filter(function(d2) {
            return d2.video && d2.video.hdr && d2.video.hdr != b ? false : true;
          });
        }
        function Mn(a, b) {
          return a.filter(function(c) {
            return c.video && c.video.videoLayout && c.video.videoLayout != b ? false : true;
          });
        }
        function Rn(a, b) {
          return a.filter(function(c) {
            return c.audio && c.audio.spatialAudio != b ? false : true;
          });
        }
        function Sn(a, b) {
          return a.filter(function(c) {
            return c.audio && c.audio.codecs != b ? false : true;
          });
        }
        ;
        function Un() {
        }
        function Vn() {
          var a = Infinity, b = Sb();
          navigator.connection && navigator.connection.saveData && (a = 360);
          var c = {
            retryParameters: Kg(),
            servers: {},
            clearKeys: {},
            advanced: {},
            delayLicenseRequestUntilPlayed: false,
            persistentSessionOnlinePlayback: false,
            persistentSessionsMetadata: [],
            initDataTransform: function(h, k2, l) {
              "apple" === window7.shakaMediaKeysPolyfill && k2 == "skd" && (k2 = l.serverCertificate, l = Fn(h), h = Gn(h, l, k2));
              return h;
            },
            logLicenseExchange: false,
            updateExpirationTime: 1,
            preferredKeySystems: [],
            keySystemsMapping: {},
            parseInbandPsshEnabled: false,
            minHdcpVersion: "",
            ignoreDuplicateInitData: true,
            defaultAudioRobustnessForWidevine: "SW_SECURE_CRYPTO",
            defaultVideoRobustnessForWidevine: "SW_SECURE_DECODE"
          }, d2 = "reload", e = false;
          fd() && b.ud() && (d2 = "smooth", e = true);
          e = {
            retryParameters: Kg(),
            availabilityWindowOverride: NaN,
            disableAudio: false,
            disableVideo: false,
            disableText: false,
            disableThumbnails: false,
            disableIFrames: false,
            defaultPresentationDelay: 0,
            segmentRelativeVttTiming: false,
            raiseFatalErrorOnManifestUpdateRequestFailure: false,
            continueLoadingWhenPaused: true,
            ignoreSupplementalCodecs: false,
            updatePeriod: -1,
            ignoreDrmInfo: false,
            dash: {
              clockSyncUri: "",
              disableXlinkProcessing: true,
              xlinkFailGracefully: false,
              ignoreMinBufferTime: false,
              autoCorrectDrift: true,
              initialSegmentLimit: 1e3,
              ignoreSuggestedPresentationDelay: false,
              ignoreEmptyAdaptationSet: false,
              ignoreMaxSegmentDuration: false,
              keySystemsByURI: {
                "urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b": "org.w3.clearkey",
                "urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e": "org.w3.clearkey",
                "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed": "com.widevine.alpha",
                "urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95": "com.microsoft.playready",
                "urn:uuid:79f0049a-4098-8642-ab92-e65be0885f95": "com.microsoft.playready",
                "urn:uuid:94ce86fb-07ff-4f43-adb8-93d2fa968ca2": "com.apple.fps",
                "urn:uuid:3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c": "com.huawei.wiseplay"
              },
              manifestPreprocessor: Wn,
              manifestPreprocessorTXml: Xn,
              sequenceMode: false,
              multiTypeVariantsAllowed: e,
              useStreamOnceInPeriodFlattening: false,
              enableFastSwitching: true
            },
            hls: {
              ignoreTextStreamFailures: false,
              ignoreImageStreamFailures: false,
              defaultAudioCodec: "mp4a.40.2",
              defaultVideoCodec: "avc1.42E01E",
              ignoreManifestProgramDateTime: false,
              ignoreManifestProgramDateTimeForTypes: [],
              mediaPlaylistFullMimeType: 'video/mp2t; codecs="avc1.42E01E, mp4a.40.2"',
              liveSegmentsDelay: 3,
              sequenceMode: b.td(),
              ignoreManifestTimestampsInSegmentsMode: false,
              disableCodecGuessing: false,
              disableClosedCaptionsDetection: false,
              allowLowLatencyByteRangeOptimization: true,
              allowRangeRequestsToGuessMimeType: false
            },
            mss: {
              manifestPreprocessor: Wn,
              manifestPreprocessorTXml: Xn,
              sequenceMode: false,
              keySystemsBySystemId: {
                "9a04f079-9840-4286-ab92-e65be0885f95": "com.microsoft.playready",
                "79f0049a-4098-8642-ab92-e65be0885f95": "com.microsoft.playready"
              }
            }
          };
          var f = {
            trackSelectionCallback: function(h) {
              return P(function(k2) {
                return k2.return(h);
              });
            },
            downloadSizeCallback: function(h) {
              var k2;
              return P(function(l) {
                if (l.g == 1) return navigator.storage && navigator.storage.estimate ? G(l, navigator.storage.estimate(), 3) : l.return(true);
                k2 = l.h;
                return l.return(k2.usage + h < k2.quota * 0.95);
              });
            },
            progressCallback: function(h, k2) {
              return Cn([h, k2]);
            },
            usePersistentLicense: true,
            numberOfParallelDownloads: 5
          }, g = {
            drm: c,
            manifest: e,
            streaming: {
              retryParameters: Kg(),
              failureCallback: function(h) {
                return Cn([h]);
              },
              rebufferingGoal: 0,
              bufferingGoal: 10,
              bufferBehind: 30,
              evictionGoal: 1,
              ignoreTextStreamFailures: false,
              alwaysStreamText: false,
              startAtSegmentBoundary: false,
              gapDetectionThreshold: 0.5,
              gapPadding: 0,
              gapJumpTimerTime: 0.25,
              durationBackoff: 1,
              safeSeekOffset: 5,
              safeSeekEndOffset: 0,
              stallEnabled: true,
              stallThreshold: 1,
              stallSkip: 0.1,
              useNativeHlsForFairPlay: true,
              inaccurateManifestTolerance: 2,
              lowLatencyMode: false,
              preferNativeDash: false,
              preferNativeHls: false,
              updateIntervalSeconds: 1,
              observeQualityChanges: false,
              maxDisabledTime: 30,
              segmentPrefetchLimit: 1,
              prefetchAudioLanguages: [],
              disableAudioPrefetch: false,
              disableTextPrefetch: false,
              disableVideoPrefetch: false,
              liveSync: {
                enabled: false,
                targetLatency: 0.5,
                targetLatencyTolerance: 0.5,
                maxPlaybackRate: 1.1,
                minPlaybackRate: 0.95,
                panicMode: false,
                panicThreshold: 60,
                dynamicTargetLatency: {
                  enabled: false,
                  stabilityThreshold: 60,
                  rebufferIncrement: 0.5,
                  maxAttempts: 10,
                  maxLatency: 4,
                  minLatency: 1
                }
              },
              allowMediaSourceRecoveries: true,
              minTimeBetweenRecoveries: 5,
              vodDynamicPlaybackRate: false,
              vodDynamicPlaybackRateLowBufferRate: 0.95,
              vodDynamicPlaybackRateBufferRatio: 0.5,
              preloadNextUrlWindow: 30,
              loadTimeout: 30,
              clearDecodingCache: false,
              dontChooseCodecs: false,
              shouldFixTimestampOffset: false,
              avoidEvictionOnQuotaExceededError: false,
              crossBoundaryStrategy: "keep",
              returnToEndOfLiveWindowWhenOutside: false
            },
            networking: {
              forceHTTP: false,
              forceHTTPS: false,
              minBytesForProgressEvents: 16e3
            },
            mediaSource: {
              codecSwitchingStrategy: d2,
              addExtraFeaturesToSourceBuffer: function(h) {
                return Cn([h], "");
              },
              forceTransmux: false,
              insertFakeEncryptionInInit: true,
              correctEc3Enca: false,
              modifyCueCallback: function(h, k2) {
                return Cn([h, k2]);
              },
              dispatchAllEmsgBoxes: false,
              useSourceElements: true,
              durationReductionEmitsUpdateEnd: true
            },
            offline: f,
            abrFactory: function() {
              return new sg();
            },
            adaptationSetCriteriaFactory: function() {
              return new (Function.prototype.bind.apply(Jn, [null].concat(x(Na.apply(0, arguments)))))();
            },
            abr: {
              enabled: true,
              useNetworkInformation: true,
              defaultBandwidthEstimate: 1e6,
              switchInterval: 8,
              bandwidthUpgradeTarget: 0.85,
              bandwidthDowngradeTarget: 0.95,
              restrictions: {
                minWidth: 0,
                maxWidth: Infinity,
                minHeight: 0,
                maxHeight: a,
                minPixels: 0,
                maxPixels: Infinity,
                minFrameRate: 0,
                maxFrameRate: Infinity,
                minBandwidth: 0,
                maxBandwidth: Infinity,
                minChannelsCount: 0,
                maxChannelsCount: Infinity
              },
              advanced: {
                minTotalBytes: 128e3,
                minBytes: 16e3,
                fastHalfLife: 2,
                slowHalfLife: 5
              },
              restrictToElementSize: false,
              restrictToScreenSize: false,
              ignoreDevicePixelRatio: false,
              clearBufferSwitch: false,
              safeMarginSwitch: 0,
              cacheLoadThreshold: 5,
              minTimeToSwitch: 0,
              preferNetworkInformationBandwidth: false,
              removeLatencyFromFirstPacketTime: true
            },
            autoShowText: 3,
            preferredAudioLanguage: "",
            preferredAudioLabel: "",
            preferredTextLanguage: "",
            preferredVariantRole: "",
            preferredTextRole: "",
            preferredAudioChannelCount: 2,
            preferredVideoHdrLevel: "AUTO",
            preferredVideoLayout: "",
            preferredVideoLabel: "",
            preferredVideoCodecs: [],
            preferredAudioCodecs: [],
            preferredTextFormats: [],
            preferForcedSubs: false,
            preferSpatialAudio: false,
            preferredDecodingAttributes: [],
            restrictions: {
              minWidth: 0,
              maxWidth: Infinity,
              minHeight: 0,
              maxHeight: Infinity,
              minPixels: 0,
              maxPixels: Infinity,
              minFrameRate: 0,
              maxFrameRate: Infinity,
              minBandwidth: 0,
              maxBandwidth: Infinity,
              minChannelsCount: 0,
              maxChannelsCount: Infinity
            },
            playRangeStart: 0,
            playRangeEnd: Infinity,
            textDisplayer: {
              captionsUpdatePeriod: 0.25,
              fontScaleFactor: 1
            },
            textDisplayFactory: function() {
              return null;
            },
            cmcd: {
              enabled: false,
              sessionId: "",
              contentId: "",
              rtpSafetyFactor: 5,
              useHeaders: false,
              includeKeys: [],
              version: 1
            },
            cmsd: {
              enabled: true,
              applyMaximumSuggestedBitrate: true,
              estimatedThroughputWeightRatio: 0.5
            },
            lcevc: {
              enabled: false,
              dynamicPerformanceScaling: true,
              logLevel: 0,
              drawLogo: false,
              poster: true
            },
            ads: {
              customPlayheadTracker: false,
              skipPlayDetection: false,
              supportsMultipleMediaElements: true,
              disableHLSInterstitial: false,
              disableDASHInterstitial: false,
              allowPreloadOnDomElements: true,
              allowStartInMiddleOfInterstitial: true
            },
            ignoreHardwareResolution: false,
            queue: {
              preloadNextUrlWindow: 30,
              repeatMode: 0
            }
          };
          f.trackSelectionCallback = function(h) {
            return P(function(k2) {
              return k2.return(Yn(h, g.preferredAudioLanguage, g.preferredVideoHdrLevel));
            });
          };
          return b.bb(g);
        }
        function Zn() {
          return {
            streaming: {
              inaccurateManifestTolerance: 0,
              segmentPrefetchLimit: 2,
              updateIntervalSeconds: 0.1,
              maxDisabledTime: 1,
              retryParameters: {
                baseDelay: 100
              }
            },
            manifest: {
              dash: {
                autoCorrectDrift: false
              },
              retryParameters: {
                baseDelay: 100
              }
            },
            drm: {
              retryParameters: {
                baseDelay: 100
              }
            }
          };
        }
        function $n(a, b, c) {
          var d2 = {
            ".drm.keySystemsMapping": "",
            ".drm.servers": "",
            ".drm.clearKeys": "",
            ".drm.advanced": {
              distinctiveIdentifierRequired: false,
              persistentStateRequired: false,
              videoRobustness: [],
              audioRobustness: [],
              sessionType: "",
              serverCertificate: new Uint8Array(0),
              serverCertificateUri: "",
              individualizationServer: "",
              headers: {}
            }
          };
          return An(a, b, c || Vn(), d2, "");
        }
        function Yn(a, b, c) {
          var d2 = c;
          d2 == "AUTO" && (c = a.some(function(h) {
            return h.hdr && h.hdr == "HLG" ? true : false;
          }), d2 = Tn(c));
          var e = a.filter(function(h) {
            return h.type != "variant" || h.hdr && h.hdr != d2 ? false : true;
          });
          c = [];
          var f = Hc(b, e.map(function(h) {
            return h.language;
          }));
          f && (c = e.filter(function(h) {
            return zc(h.language) == f;
          }));
          c.length == 0 && (c = e.filter(function(h) {
            return h.primary;
          }));
          c.length == 0 && (e.map(function(h) {
            return h.language;
          }), c = e);
          var g = c.filter(function(h) {
            return h.height && h.height <= 480;
          });
          g.length && (g.sort(function(h, k2) {
            return k2.height - h.height;
          }), c = g.filter(function(h) {
            return h.height == g[0].height;
          }));
          b = [];
          c.length && (e = Math.floor(c.length / 2), c.sort(function(h, k2) {
            return h.bandwidth - k2.bandwidth;
          }), b.push(c[e]));
          a = t2(a);
          for (c = a.next(); !c.done; c = a.next()) c = c.value, c.type != tc && c.type != "image" || b.push(c);
          return b;
        }
        function Wn(a) {
          return Cn([a], a);
        }
        function Xn(a) {
          return Cn([a], a);
        }
        S("shaka.util.PlayerConfiguration", Un);
        Un.mergeConfigObjects = $n;
        Un.createDefaultForLL = Zn;
        Un.createDefault = Vn;
        function ao() {
          this.g = null;
          this.h = [];
        }
        function bo(a, b) {
          var c = 0;
          a.g && a.g.state == b && (c += a.g.duration);
          a = t2(a.h);
          for (var d2 = a.next(); !d2.done; d2 = a.next()) d2 = d2.value, c += d2.state == b ? d2.duration : 0;
          return c;
        }
        function co(a) {
          function b(f) {
            return {
              timestamp: f.timestamp,
              state: f.state,
              duration: f.duration
            };
          }
          for (var c = [], d2 = t2(a.h), e = d2.next(); !e.done; e = d2.next()) c.push(b(e.value));
          a.g && c.push(b(a.g));
          return c;
        }
        ;
        function eo() {
          this.i = this.h = null;
          this.g = [];
        }
        function fo(a, b, c) {
          a.i != b && (a.i = b, a.g.push({
            timestamp: Date.now() / 1e3,
            id: b.id,
            type: "text",
            fromAdaptation: c,
            bandwidth: null
          }));
        }
        ;
        function go() {
          this.D = this.V = NaN;
          this.l = "";
          this.j = this.ij = this.A = this.C = this.K = this.F = this.u = this.m = this.J = this.G = this.i = this.R = this.S = this.M = this.O = this.P = NaN;
          this.L = 0;
          this.H = this.I = NaN;
          this.g = new ao();
          this.h = new eo();
        }
        function ho(a, b, c) {
          a.P = b;
          a.O = c;
        }
        function io(a, b, c) {
          a.V = b;
          a.D = c;
        }
        function jo(a, b) {
          a.i = isNaN(a.i) ? b : Math.max(a.i, b);
        }
        function ko(a, b) {
          a.j = isNaN(a.j) ? b : a.j + b;
        }
        function lo(a) {
          var b = a.V, c = a.D, d2 = a.l, e = a.C, f = a.O, g = a.P, h = a.M, k2 = a.S, l = a.R, m = a.A, n = a.i, q = a.G, r2 = a.J, u = a.m, w = bo(a.g, "playing"), v = bo(a.g, "paused"), y = bo(a.g, "buffering"), z = a.u, A = a.F, C = a.K, D = a.ij, F = a.j, B = a.L, E = a.I, I = a.H, J = co(a.g), K = [];
          a = t2(a.h.g);
          for (var L = a.next(); !L.done; L = a.next()) L = L.value, K.push({
            timestamp: L.timestamp,
            id: L.id,
            type: L.type,
            fromAdaptation: L.fromAdaptation,
            bandwidth: L.bandwidth
          });
          return {
            width: b,
            height: c,
            currentCodecs: d2,
            streamBandwidth: e,
            decodedFrames: f,
            droppedFrames: g,
            corruptedFrames: h,
            stallsDetected: k2,
            gapsJumped: l,
            estimatedBandwidth: m,
            completionPercent: n,
            loadLatency: q,
            manifestTimeSeconds: r2,
            drmTimeSeconds: u,
            playTime: w,
            pauseTime: v,
            bufferingTime: y,
            licenseTime: z,
            liveLatency: A,
            maxSegmentDuration: C,
            manifestSizeBytes: D,
            bytesDownloaded: F,
            nonFatalErrorCount: B,
            manifestPeriodCount: E,
            manifestGapCount: I,
            stateHistory: J,
            switchHistory: K
          };
        }
        ;
        function mo(a, b, c, d2) {
          lb.call(this);
          this.O = a;
          this.V = b;
          this.Ma = d2.networkingEngine;
          this.m = c;
          this.D = null;
          this.Ia = 0;
          this.Za = d2.Bd;
          this.H = d2.Ml;
          this.fb = d2.Nl;
          this.g = d2.config;
          this.l = this.I = this.h = null;
          this.sa = false;
          this.J = d2.Yl;
          this.ua = false;
          this.i = null;
          this.ea = false;
          this.j = this.G = null;
          this.$ = false;
          this.M = /* @__PURE__ */ new Map();
          this.va = false;
          this.Oa = d2.Xl;
          this.Z = new go();
          this.oa = new Mg();
          this.C = new Mg();
          this.P = null;
          this.A = false;
          this.aa = d2.lk;
          this.S = this.u = null;
          this.Va = d2.kk;
          this.R = false;
          this.L = [];
          this.K = [];
          this.F = true;
        }
        ma(mo, lb);
        function no(a, b, c) {
          (a = b ? a.K : a.L) ? a.push(c) : c();
        }
        function oo(a) {
          if (a.K) for (var b = t2(a.K), c = b.next(); !c.done; c = b.next()) c = c.value, c();
          a.K = null;
        }
        function po(a, b) {
          a.P = b;
          a.R = true;
          if (a.L) {
            b = t2(a.L);
            for (var c = b.next(); !c.done; c = b.next()) c = c.value, c();
          }
          a.L = null;
        }
        p = mo.prototype;
        p.getStartTime = function() {
          return this.m;
        };
        p.ed = function() {
          return this.O;
        };
        p.qh = function() {
          return this.h;
        };
        function qo(a) {
          a.$ = true;
          return a.j;
        }
        function ro(a) {
          a.ua = true;
          return a.J;
        }
        p.getStats = function() {
          return this.Z;
        };
        function so(a) {
          a.ea = true;
          return a.i;
        }
        p.al = function() {
          return this.u ? cg(this.u) : null;
        };
        p.$k = function() {
          return this.S ? dg(this.S) : null;
        };
        function to(a) {
          a.va = true;
          return a.M;
        }
        function uo(a, b, c) {
          a.j = b;
          a.G = c;
        }
        p.start = function() {
          var a = this;
          (function() {
            var b;
            return P(function(c) {
              switch (c.g) {
                case 1:
                  return G(c, Promise.resolve(), 2);
                case 2:
                  return sa(c, 3), G(c, vo(a), 5);
                case 5:
                  wo(a);
                  if ("webkit" === window7.shakaMediaKeysPolyfill) {
                    c.B(6);
                    break;
                  }
                  return G(c, xo(a), 7);
                case 7:
                  wo(a);
                case 6:
                  if (!a.aa) {
                    c.B(8);
                    break;
                  }
                  return G(c, yo(a), 9);
                case 9:
                  wo(a);
                case 8:
                  if (!a.aa || !a.i) {
                    c.B(10);
                    break;
                  }
                  return G(c, ji(a.i), 11);
                case 11:
                  wo(a);
                case 10:
                  a.C.resolve();
                  ua(c, 0);
                  break;
                case 3:
                  b = va(c), b instanceof U && (b.code == 7001 || b.code == 7003) || a.C.reject(b), H(c);
              }
            });
          })();
        };
        p.dispatchEvent = function(a) {
          return this.P ? this.P.dispatchEvent(a) : lb.prototype.dispatchEvent.call(this, a);
        };
        p.onError = function(a) {
          a.severity === 2 && (this.C.reject(a), this.destroy());
          var b = (/* @__PURE__ */ new Map()).set("detail", a);
          b = new T("error", b);
          this.dispatchEvent(b);
          b.defaultPrevented && (a.handled = true);
        };
        function wo(a) {
          if (a.A) throw new U(2, 7, 7003);
        }
        function zo(a, b) {
          a.dispatchEvent(new T("onstatechange", (/* @__PURE__ */ new Map()).set("state", b)));
        }
        function vo(a) {
          var b, c, d2, e, f, g;
          return P(function(h) {
            switch (h.g) {
              case 1:
                zo(a, "manifest-parser");
                a.l || (a.I = Li(a.O, a.V), a.l = a.I(), a.l.configure(a.g.manifest, function() {
                  return a.F;
                }));
                b = Date.now() / 1e3;
                zo(a, "manifest");
                if (a.h) {
                  h.B(2);
                  break;
                }
                return G(h, a.l.start(a.O, a.fb), 3);
              case 3:
                return a.h = h.h, G(h, Ao(a), 2);
              case 2:
                return a.oa.resolve(), c = new T("manifestparsed", void 0), G(h, Promise.resolve(), 5);
              case 5:
                a.dispatchEvent(c);
                if (a.h.variants.length == 0) throw new U(2, 4, 4036);
                Bo(a.h);
                d2 = Bi(a.H, a.h);
                if (!d2) {
                  h.B(6);
                  break;
                }
                e = new T("trackschanged", void 0);
                return G(h, Promise.resolve(), 7);
              case 7:
                wo(a), a.dispatchEvent(e);
              case 6:
                f = Date.now() / 1e3, g = f - b, a.Z.J = g, H(h);
            }
          });
        }
        function xo(a, b) {
          var c, d2, e, f;
          return P(function(g) {
            switch (g.g) {
              case 1:
                if (!a.h || a.i) return g.return();
                zo(a, "drm-engine");
                a.Ia = Date.now() / 1e3;
                a.i = a.Za();
                a.H.h = a.i;
                a.i.configure(a.g.drm, function() {
                  return a.F;
                });
                c = lg(a.h.variants);
                d2 = true;
                a.h && a.h.presentationTimeline && (d2 = a.h.presentationTimeline.U());
                return G(g, Jh(a.i, c, a.h.offlineSessionIds, d2), 2);
              case 2:
                wo(a);
                if (!b) {
                  g.B(3);
                  break;
                }
                return G(g, a.i.bc(b), 4);
              case 4:
                wo(a);
              case 3:
                return G(g, zi(a.H, a.h), 5);
              case 5:
                e = g.h;
                if (!e) {
                  g.B(0);
                  break;
                }
                f = new T("trackschanged", void 0);
                return G(g, Promise.resolve(), 7);
              case 7:
                a.dispatchEvent(f), H(g);
            }
          });
        }
        p.configure = function(a, b) {
          a = Bn(a, b);
          $n(this.g, a);
        };
        p.getConfiguration = function() {
          return Hd(this.g);
        };
        function Ao(a) {
          var b, c, d2, e, f, g;
          return P(function(h) {
            a.D || (a.D = a.g.adaptationSetCriteriaFactory(), a.D.configure({
              language: a.g.preferredAudioLanguage,
              role: a.g.preferredVariantRole,
              channelCount: a.g.preferredAudioChannelCount,
              Qc: a.g.preferredVideoHdrLevel,
              spatialAudio: a.g.preferSpatialAudio,
              videoLayout: a.g.preferredVideoLayout,
              Zc: a.g.preferredAudioLabel,
              Yd: a.g.preferredVideoLabel,
              codecSwitchingStrategy: a.g.mediaSource.codecSwitchingStrategy,
              audioCodec: "",
              ae: "",
              $e: 0,
              preferredAudioCodecs: a.g.preferredAudioCodecs,
              preferredAudioChannelCount: a.g.preferredAudioChannelCount
            }));
            a.Va && (b = a.g.abrFactory, a.G = b, a.j = b(), a.j.configure(a.g.abr));
            c = Co(a);
            if (!c || a.h.variants.length != 1 && a.h.type != "HLS") return h.B(0);
            d2 = [];
            e = t2([c.video, c.audio]);
            for (f = e.next(); !f.done; f = e.next()) (g = f.value) && !g.segmentIndex && d2.push(g.createSegmentIndex());
            return d2.length > 0 ? G(h, Promise.all(d2), 0) : h.B(0);
          });
        }
        function yo(a) {
          var b, c, d2, e, f;
          return P(function(g) {
            !a.u && (b = Co(a)) && (a.u = b);
            if (!a.u) return g.B(0);
            c = a.h.presentationTimeline.U();
            d2 = [];
            e = a.u;
            e.video && d2.push(Do(a, e.video, c));
            e.audio && d2.push(Do(a, e.audio, c));
            (f = mg(a.h.textStreams, a.g.preferredTextLanguage, a.g.preferredTextRole, a.g.preferForcedSubs)[0] || null) && qg(e.audio, f, a.g) && (d2.push(Do(a, f, c)), a.S = f);
            return G(g, Promise.all(d2), 0);
          });
        }
        function Co(a) {
          var b = lg(a.h.variants);
          b = a.D.create(b);
          a.j.configure(a.g.abr);
          a.j.setVariants(Array.from(b.values()));
          return a.j.chooseVariant();
        }
        function Do(a, b, c) {
          var d2, e, f, g, h;
          return P(function(k2) {
            if (k2.g == 1) return d2 = a.g.streaming.segmentPrefetchLimit || 2, e = new rm(d2, b, function(l, m, n) {
              return hn(l, m, n || null, a.g.streaming.retryParameters, a.Ma, a.F);
            }, false), a.M.set(b.id, e), b.segmentIndex ? k2.B(2) : G(k2, b.createSegmentIndex(), 2);
            f = typeof a.m === "number" ? a.m : 0;
            g = b.segmentIndex.dc(f);
            h = null;
            g && (h = g.current(), h || (h = g.next().value));
            h || (h = fg(b.segmentIndex));
            return h ? c ? h.ha ? G(k2, um(e, h.ha), 0) : k2.B(0) : G(k2, tm(e, h.startTime), 0) : k2.B(0);
          });
        }
        p.Dm = function() {
          return this.C;
        };
        p.destroy = function() {
          var a = this, b, c, d2;
          return P(function(e) {
            switch (e.g) {
              case 1:
                a.A = true;
                if (!a.l || a.sa) {
                  e.B(2);
                  break;
                }
                return G(e, a.l.stop(), 2);
              case 2:
                if (!a.j || a.$) {
                  e.B(4);
                  break;
                }
                return G(e, a.j.stop(), 4);
              case 4:
                a.J && !a.ua && a.J.release();
                if (!a.i || a.ea) {
                  e.B(6);
                  break;
                }
                return G(e, a.i.destroy(), 6);
              case 6:
                if (a.M.size > 0 && !a.va) for (b = t2(a.M.values()), c = b.next(); !c.done; c = b.next()) d2 = c.value, Am(d2);
                H(e);
            }
          });
        };
        function Bo(a) {
          function b(c) {
            return c.video && c.audio || c.video && c.video.codecs.includes(",");
          }
          a.variants.some(b) && (a.variants = a.variants.filter(b));
        }
        S("shaka.media.PreloadManager", mo);
        mo.prototype.destroy = mo.prototype.destroy;
        mo.prototype.waitForFinish = mo.prototype.Dm;
        mo.prototype.getPrefetchedTextTrack = mo.prototype.$k;
        mo.prototype.getPrefetchedVariantTrack = mo.prototype.al;
        function Eo(a, b) {
          lb.call(this);
          var c = this;
          this.i = a;
          this.l = b;
          this.g = /* @__PURE__ */ new Map();
          this.m = [{
            yd: null,
            xd: Fo,
            jd: function(d2, e) {
              return Go(c, "enter", d2, e);
            }
          }, {
            yd: Ho,
            xd: Fo,
            jd: function(d2, e) {
              return Go(c, "enter", d2, e);
            }
          }, {
            yd: Io,
            xd: Fo,
            jd: function(d2, e) {
              return Go(c, "enter", d2, e);
            }
          }, {
            yd: Fo,
            xd: Ho,
            jd: function(d2, e) {
              return Go(c, "exit", d2, e);
            }
          }, {
            yd: Fo,
            xd: Io,
            jd: function(d2, e) {
              return Go(c, "exit", d2, e);
            }
          }, {
            yd: Ho,
            xd: Io,
            jd: function(d2, e) {
              e ? Go(c, "skip", d2, e) : (Go(c, "enter", d2, e), Go(c, "exit", d2, e));
            }
          }, {
            yd: Io,
            xd: Ho,
            jd: function(d2, e) {
              return Go(c, "skip", d2, e);
            }
          }];
          this.h = new Qc();
          this.h.o(this.i, "regionremove", function(d2) {
            c.g.delete(d2.region);
          });
        }
        ma(Eo, lb);
        Eo.prototype.release = function() {
          this.i = null;
          this.g.clear();
          this.h.release();
          this.h = null;
          lb.prototype.release.call(this);
        };
        Eo.prototype.j = function(a, b) {
          if (!this.l || a != 0) {
            this.l = false;
            for (var c = t2(this.i.h.values()), d2 = c.next(); !d2.done; d2 = c.next()) {
              d2 = d2.value;
              var e = this.g.get(d2), f = a < d2.startTime ? Ho : a > d2.endTime ? Io : Fo;
              this.g.set(d2, f);
              for (var g = t2(this.m), h = g.next(); !h.done; h = g.next()) h = h.value, h.yd == e && h.xd == f && h.jd(d2, b);
            }
          }
        };
        function Go(a, b, c, d2) {
          b = new T(b, /* @__PURE__ */ new Map([["region", c], ["seeking", d2]]));
          a.dispatchEvent(b);
        }
        var Ho = 1, Fo = 2, Io = 3;
        function Jo(a, b, c) {
          var d2, e, f, g, h, k2, l;
          return P(function(m) {
            switch (m.g) {
              case 1:
                var n = new rb(a).xb.split("/").pop().split(".");
                d2 = n.length == 1 ? "" : n.pop().toLowerCase();
                if (e = Ko.get(d2)) return m.return(e);
                f = 0;
                g = ah([a], c);
                sa(m, 2);
                g.method = "HEAD";
                return G(m, b.request(f, g).promise, 4);
              case 4:
                h = m.h;
                e = h.headers["content-type"];
                ua(m, 3);
                break;
              case 2:
                k2 = va(m);
                if (!k2 || k2.code != 1002 && k2.code != 1001) {
                  m.B(3);
                  break;
                }
                g.method = "GET";
                return G(m, b.request(f, g).promise, 6);
              case 6:
                l = m.h, e = l.headers["content-type"];
              case 3:
                return m.return(e ? e.toLowerCase().split(";").shift() : "");
            }
          });
        }
        var Ko = (/* @__PURE__ */ new Map()).set("mp4", "video/mp4").set("m4v", "video/mp4").set("m4a", "audio/mp4").set("webm", "video/webm").set("weba", "audio/webm").set("mkv", "video/webm").set("ts", "video/mp2t").set("ogv", "video/ogg").set("ogg", "audio/ogg").set("mpg", "video/mpeg").set("mpeg", "video/mpeg").set("mov", "video/quicktime").set("m3u8", "application/x-mpegurl").set("mpd", "application/dash+xml").set("ism", "application/vnd.ms-sstr+xml").set("mp3", "audio/mpeg").set("aac", "audio/aac").set("flac", "audio/flac").set("wav", "audio/wav").set("sbv", "text/x-subviewer").set("srt", "text/srt").set("vtt", "text/vtt").set("webvtt", "text/vtt").set("ttml", "application/ttml+xml").set("lrc", "application/x-subtitle-lrc").set("ssa", "text/x-ssa").set("ass", "text/x-ssa").set("jpeg", "image/jpeg").set("jpg", "image/jpeg").set("png", "image/png").set("svg", "image/svg+xml").set("webp", "image/webp").set("avif", "image/avif").set("html", "text/html").set("htm", "text/html");
        for (var Lo = {
          ach: "Lwo",
          ady: "\u0410\u0434\u044B\u0433\u044D\u0431\u0437\u044D",
          af: "Afrikaans",
          "af-NA": "Afrikaans (Namibia)",
          "af-ZA": "Afrikaans (South Africa)",
          ak: "T\u0255\u0265i",
          ar: "\u0627\u0644\u0639\u0631\u0628\u064A\u0629",
          "ar-AR": "\u0627\u0644\u0639\u0631\u0628\u064A\u0629",
          "ar-MA": "\u0627\u0644\u0639\u0631\u0628\u064A\u0629",
          "ar-SA": "\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u0633\u0639\u0648\u062F\u064A\u0629)",
          "ay-BO": "Aymar aru",
          az: "Az\u0259rbaycan dili",
          "az-AZ": "Az\u0259rbaycan dili",
          "be-BY": "\u0411\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0430\u044F",
          bg: "\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",
          "bg-BG": "\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",
          bn: "\u09AC\u09BE\u0982\u09B2\u09BE",
          "bn-IN": "\u09AC\u09BE\u0982\u09B2\u09BE (\u09AD\u09BE\u09B0\u09A4)",
          "bn-BD": "\u09AC\u09BE\u0982\u09B2\u09BE(\u09AC\u09BE\u0982\u09B2\u09BE\u09A6\u09C7\u09B6)",
          "bs-BA": "Bosanski",
          ca: "Catal\xE0",
          "ca-ES": "Catal\xE0",
          cak: "Maya Kaqchikel",
          "ck-US": "\u13E3\u13B3\u13A9 (tsalagi)",
          cs: "\u010Ce\u0161tina",
          "cs-CZ": "\u010Ce\u0161tina",
          cy: "Cymraeg",
          "cy-GB": "Cymraeg",
          da: "Dansk",
          "da-DK": "Dansk",
          de: "Deutsch",
          "de-AT": "Deutsch (\xD6sterreich)",
          "de-DE": "Deutsch (Deutschland)",
          "de-CH": "Deutsch (Schweiz)",
          dsb: "Dolnoserb\u0161\u0107ina",
          el: "\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",
          "el-GR": "\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",
          en: "English",
          "en-GB": "English (UK)",
          "en-AU": "English (Australia)",
          "en-CA": "English (Canada)",
          "en-IE": "English (Ireland)",
          "en-IN": "English (India)",
          "en-PI": "English (Pirate)",
          "en-UD": "English (Upside Down)",
          "en-US": "English (US)",
          "en-ZA": "English (South Africa)",
          "en@pirate": "English (Pirate)",
          eo: "Esperanto",
          "eo-EO": "Esperanto",
          es: "Espa\xF1ol",
          "es-AR": "Espa\xF1ol (Argentine)",
          "es-419": "Espa\xF1ol (Latinoam\xE9rica)",
          "es-CL": "Espa\xF1ol (Chile)",
          "es-CO": "Espa\xF1ol (Colombia)",
          "es-EC": "Espa\xF1ol (Ecuador)",
          "es-ES": "Espa\xF1ol (Espa\xF1a)",
          "es-LA": "Espa\xF1ol (Latinoam\xE9rica)",
          "es-NI": "Espa\xF1ol (Nicaragua)",
          "es-MX": "Espa\xF1ol (M\xE9xico)",
          "es-US": "Espa\xF1ol (Estados Unidos)",
          "es-VE": "Espa\xF1ol (Venezuela)",
          et: "eesti keel",
          "et-EE": "Eesti (Estonia)",
          eu: "Euskara",
          "eu-ES": "Euskara",
          fa: "\u0641\u0627\u0631\u0633\u06CC",
          "fa-IR": "\u0641\u0627\u0631\u0633\u06CC",
          "fb-LT": "Leet Speak",
          ff: "Fulah",
          fi: "Suomi",
          "fi-FI": "Suomi",
          "fo-FO": "F\xF8royskt",
          fr: "Fran\xE7ais",
          "fr-CA": "Fran\xE7ais (Canada)",
          "fr-FR": "Fran\xE7ais (France)",
          "fr-BE": "Fran\xE7ais (Belgique)",
          "fr-CH": "Fran\xE7ais (Suisse)",
          "fy-NL": "Frysk",
          ga: "Gaeilge",
          "ga-IE": "Gaeilge (Gaelic)",
          gl: "Galego",
          "gl-ES": "Galego",
          "gn-PY": "Ava\xF1e'\u1EBD",
          "gu-IN": "\u0A97\u0AC1\u0A9C\u0AB0\u0ABE\u0AA4\u0AC0",
          "gx-GR": "\u1F19\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AE \u1F00\u03C1\u03C7\u03B1\u03AF\u03B1",
          he: "\u05E2\u05D1\u05E8\u05D9\u05EA\u200F",
          "he-IL": "\u05E2\u05D1\u05E8\u05D9\u05EA\u200F",
          hi: "\u0939\u093F\u0928\u094D\u0926\u0940",
          "hi-IN": "\u0939\u093F\u0928\u094D\u0926\u0940",
          hr: "Hrvatski",
          "hr-HR": "Hrvatski",
          hsb: "Hornjoserb\u0161\u0107ina",
          ht: "Krey\xF2l",
          hu: "Magyar",
          "hu-HU": "Magyar",
          "hy-AM": "\u0540\u0561\u0575\u0565\u0580\u0565\u0576",
          id: "Bahasa Indonesia",
          "id-ID": "Bahasa Indonesia",
          is: "\xCDslenska",
          "is-IS": "\xCDslenska (Iceland)",
          it: "Italiano",
          "it-IT": "Italiano",
          ja: "\u65E5\u672C\u8A9E",
          "ja-JP": "\u65E5\u672C\u8A9E",
          "jv-ID": "Basa Jawa",
          "ka-GE": "\u10E5\u10D0\u10E0\u10D7\u10E3\u10DA\u10D8",
          "kk-KZ": "\u049A\u0430\u0437\u0430\u049B\u0448\u0430",
          km: "\u1797\u17B6\u179F\u17B6\u1781\u17D2\u1798\u17C2\u179A",
          "km-KH": "\u1797\u17B6\u179F\u17B6\u1781\u17D2\u1798\u17C2\u179A",
          kab: "Taqbaylit",
          kn: "\u0C95\u0CA8\u0CCD\u0CA8\u0CA1",
          "kn-IN": "\u0C95\u0CA8\u0CCD\u0CA8\u0CA1 (India)",
          ko: "\uD55C\uAD6D\uC5B4",
          "ko-KR": "\uD55C\uAD6D\uC5B4 (\u97E9\u56FD)",
          ku: "Kurd\xEE",
          "ku-TR": "Kurd\xEE",
          la: "Latin",
          "la-VA": "Latin",
          lb: "L\xEBtzebuergesch",
          "li-NL": "L\xE8mb\xF6rgs",
          lt: "Lietuvi\u0173",
          "lt-LT": "Lietuvi\u0173",
          lv: "Latvie\u0161u",
          "lv-LV": "Latvie\u0161u",
          mai: "\u092E\u0948\u0925\u093F\u0932\u0940, \u09AE\u09C8\u09A5\u09BF\u09B2\u09C0",
          "mg-MG": "Malagasy",
          mk: "\u041C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438",
          "mk-MK": "\u041C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438 (\u041C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438)",
          ml: "\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02",
          "ml-IN": "\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02",
          "mn-MN": "\u041C\u043E\u043D\u0433\u043E\u043B",
          mr: "\u092E\u0930\u093E\u0920\u0940",
          "mr-IN": "\u092E\u0930\u093E\u0920\u0940",
          ms: "Bahasa Melayu",
          "ms-MY": "Bahasa Melayu",
          mt: "Malti",
          "mt-MT": "Malti",
          my: "\u1017\u1019\u102C\u1005\u1000\u102C",
          nb: "Norsk (bokm\xE5l)",
          "nb-NO": "Norsk (bokm\xE5l)",
          ne: "\u0928\u0947\u092A\u093E\u0932\u0940",
          "ne-NP": "\u0928\u0947\u092A\u093E\u0932\u0940",
          nl: "Nederlands",
          "nl-BE": "Nederlands (Belgi\xEB)",
          "nl-NL": "Nederlands (Nederland)",
          "nn-NO": "Norsk (nynorsk)",
          no: "Norsk",
          oc: "Occitan",
          "or-IN": "\u0B13\u0B21\u0B3C\u0B3F\u0B06",
          pa: "\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40",
          "pa-IN": "\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40 (\u0A2D\u0A3E\u0A30\u0A24 \u0A28\u0A42\u0A70)",
          pl: "Polski",
          "pl-PL": "Polski",
          "ps-AF": "\u067E\u069A\u062A\u0648",
          pt: "Portugu\xEAs",
          "pt-BR": "Portugu\xEAs (Brasil)",
          "pt-PT": "Portugu\xEAs (Portugal)",
          "qu-PE": "Qhichwa",
          "rm-CH": "Rumantsch",
          ro: "Rom\xE2n\u0103",
          "ro-RO": "Rom\xE2n\u0103",
          ru: "\u0420\u0443\u0441\u0441\u043A\u0438\u0439",
          "ru-RU": "\u0420\u0443\u0441\u0441\u043A\u0438\u0439",
          "sa-IN": "\u0938\u0902\u0938\u094D\u0915\u0943\u0924\u092E\u094D",
          "se-NO": "Davvis\xE1megiella",
          "si-LK": "\u0DB4\u0DC5\u0DCF\u0DAD",
          sk: "Sloven\u010Dina",
          "sk-SK": "Sloven\u010Dina (Slovakia)",
          sl: "Sloven\u0161\u010Dina",
          "sl-SI": "Sloven\u0161\u010Dina",
          "so-SO": "Soomaaliga",
          sq: "Shqip",
          "sq-AL": "Shqip",
          sr: "\u0421\u0440\u043F\u0441\u043A\u0438",
          "sr-RS": "\u0421\u0440\u043F\u0441\u043A\u0438 (Serbia)",
          su: "Basa Sunda",
          sv: "Svenska",
          "sv-SE": "Svenska",
          sw: "Kiswahili",
          "sw-KE": "Kiswahili",
          ta: "\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD",
          "ta-IN": "\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD",
          te: "\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41",
          "te-IN": "\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41",
          tg: "\u0437\u0430\u0431\u043E\u0301\u043D\u0438 \u0442\u043E\u04B7\u0438\u043A\u04E3\u0301",
          "tg-TJ": "\u0442\u043E\u04B7\u0438\u043A\u04E3",
          th: "\u0E20\u0E32\u0E29\u0E32\u0E44\u0E17\u0E22",
          "th-TH": "\u0E20\u0E32\u0E29\u0E32\u0E44\u0E17\u0E22 (\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28\u0E44\u0E17\u0E22)",
          tl: "Filipino",
          "tl-PH": "Filipino",
          tlh: "tlhIngan-Hol",
          tr: "T\xFCrk\xE7e",
          "tr-TR": "T\xFCrk\xE7e",
          "tt-RU": "\u0442\u0430\u0442\u0430\u0440\u0447\u0430",
          uk: "\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",
          "uk-UA": "\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",
          ur: "\u0627\u0631\u062F\u0648",
          "ur-PK": "\u0627\u0631\u062F\u0648",
          uz: "O'zbek",
          "uz-UZ": "O'zbek",
          vi: "Ti\u1EBFng Vi\u1EC7t",
          "vi-VN": "Ti\u1EBFng Vi\u1EC7t",
          "xh-ZA": "isiXhosa",
          yi: "\u05D9\u05D9\u05B4\u05D3\u05D9\u05E9",
          "yi-DE": "\u05D9\u05D9\u05B4\u05D3\u05D9\u05E9 (German)",
          zh: "\u4E2D\u6587",
          "zh-HANS": "\u4E2D\u6587\u7B80\u4F53",
          "zh-HANT": "\u4E2D\u6587\u7E41\u9AD4",
          "zh-CN": "\u4E2D\u6587\uFF08\u4E2D\u56FD\uFF09",
          "zh-HK": "\u4E2D\u6587\uFF08\u9999\u6E2F\uFF09",
          "zh-SG": "\u4E2D\u6587\uFF08\u65B0\u52A0\u5761\uFF09",
          "zh-TW": "\u4E2D\u6587\uFF08\u53F0\u7063\uFF09",
          "zu-ZA": "isiZulu"
        }, Mo = t2(Object.keys(Lo)), No = Mo.next(); !No.done; No = Mo.next()) {
          var Oo = No.value;
          Lo[Oo.toLowerCase()] = Lo[Oo];
        }
        ;
        function Po(a, b) {
          if (a.lineBreak) return "\n";
          if (a.nestedCues.length) return a.nestedCues.map(function(g) {
            return Po(g, a);
          }).join("");
          if (!a.payload) return a.payload;
          var c = [], d2 = a.fontWeight >= Pe, e = a.fontStyle == Qe, f = a.textDecoration.includes(Re);
          d2 && c.push(["b"]);
          e && c.push(["i"]);
          f && c.push(["u"]);
          e = a.color;
          e == "" && b && (e = b.color);
          d2 = "";
          (e = Qo(e)) && (d2 += "." + e);
          e = a.backgroundColor;
          e == "" && b && (e = b.backgroundColor);
          (b = Qo(e)) && (d2 += ".bg_" + b);
          d2 && c.push(["c", d2]);
          return c.reduceRight(function(g, h) {
            var k2 = t2(h);
            h = k2.next().value;
            k2 = k2.next().value;
            return "<" + h + (k2 === void 0 ? "" : k2) + ">" + g + "</" + h + ">";
          }, a.payload);
        }
        function Qo(a) {
          a = a.toLowerCase();
          var b = a.replace(/\s/g, "").match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i);
          b ? a = "#" + (parseInt(b[1], 10) | 256).toString(16).slice(1) + (parseInt(b[2], 10) | 256).toString(16).slice(1) + (parseInt(b[3], 10) | 256).toString(16).slice(1) : a.startsWith("#") && a.length > 7 && (a = a.slice(0, 7));
          switch (a) {
            case "white":
            case "#fff":
            case "#ffffff":
              return "white";
            case "lime":
            case "#0f0":
            case "#00ff00":
              return "lime";
            case "cyan":
            case "#0ff":
            case "#00ffff":
              return "cyan";
            case "red":
            case "#f00":
            case "#ff0000":
              return "red";
            case "yellow":
            case "#ff0":
            case "#ffff00":
              return "yellow";
            case "magenta":
            case "#f0f":
            case "#ff00ff":
              return "magenta";
            case "blue":
            case "#00f":
            case "#0000ff":
              return "blue";
            case "black":
            case "#000":
            case "#000000":
              return "black";
          }
          return null;
        }
        function Ro(a, b) {
          var c = [];
          a = t2(So(a));
          for (var d2 = a.next(); !d2.done; d2 = a.next()) if (d2 = d2.value, d2.isContainer) c.push.apply(c, x(Ro(d2.nestedCues, d2)));
          else {
            var e = d2.clone();
            e.nestedCues = [];
            e.payload = Po(d2, b);
            c.push(e);
          }
          return c;
        }
        function So(a) {
          var b = [];
          a = t2(a);
          for (var c = a.next(), d2 = {}; !c.done; d2 = {
            Qg: void 0
          }, c = a.next()) d2.Qg = c.value, b.some(/* @__PURE__ */ function(e) {
            return function(f) {
              return De(e.Qg, f);
            };
          }(d2)) || b.push(d2.Qg);
          return b;
        }
        function To(a) {
          function b(d2) {
            for (var e = 5381, f = d2.length; f; ) e = e * 33 ^ d2.charCodeAt(--f);
            return (e >>> 0).toString();
          }
          if (a.startTime >= a.endTime) return null;
          var c = new VTTCue(a.startTime, a.endTime, a.payload);
          c.id = b(a.startTime.toString()) + b(a.endTime.toString()) + b(a.payload);
          c.lineAlign = a.lineAlign;
          c.positionAlign = a.positionAlign;
          a.size && (c.size = a.size);
          try {
            c.align = a.textAlign;
          } catch (d2) {
          }
          a.textAlign == "center" && c.align != "center" && (c.align = "middle");
          a.writingMode == "vertical-lr" ? c.vertical = "lr" : a.writingMode == "vertical-rl" && (c.vertical = "rl");
          a.lineInterpretation == 1 && (c.snapToLines = false);
          a.line != null && (c.line = a.line);
          a.position != null && (c.position = a.position);
          return c;
        }
        function Uo(a, b) {
          var c = Ro(b), d2 = [];
          b = a.cues ? Array.from(a.cues) : [];
          c = t2(c);
          for (var e = c.next(), f = {}; !e.done; f = {
            Gd: void 0
          }, e = c.next()) f.Gd = e.value, !b.some(/* @__PURE__ */ function(g) {
            return function(h) {
              return h.startTime == g.Gd.startTime && h.endTime == g.Gd.endTime && h.text == g.Gd.payload ? true : false;
            };
          }(f)) && f.Gd.payload && (e = To(f.Gd)) && d2.push(e);
          b = d2.slice().sort(function(g, h) {
            return g.startTime != h.startTime ? g.startTime - h.startTime : g.endTime != h.endTime ? g.endTime - h.startTime : "line" in VTTCue.prototype ? d2.indexOf(h) - d2.indexOf(g) : d2.indexOf(g) - d2.indexOf(h);
          });
          b = t2(b);
          for (c = b.next(); !c.done; c = b.next()) a.addCue(c.value);
        }
        function Vo(a, b) {
          var c = false;
          a.mode === "disabled" && (c = true, a.mode = "hidden");
          for (var d2 = 0; d2 < a.cues.length; ) {
            var e = a.cues[d2];
            b(e) ? a.removeCue(e) : d2++;
          }
          c && (a.mode = "disabled");
        }
        ;
        function Wo(a) {
          var b = this;
          this.i = a;
          this.l = new Qc();
          this.j = null;
          this.h = /* @__PURE__ */ new Map();
          this.g = -1;
          this.A = false;
          this.u = null;
          this.D = function() {
            b.l.Ea(b.i, "textchanged", b.m);
            b.l.Ea(b.j.textTracks, "change", b.C);
            for (var c = t2(b.h.values()), d2 = c.next(); !d2.done; d2 = c.next()) d2.value.remove();
            b.h.clear();
            b.g = -1;
            b.j = null;
          };
          this.m = function() {
            var c = /* @__PURE__ */ new Map(), d2 = b.i.vc();
            d2 = t2(d2);
            for (var e = d2.next(); !e.done; e = d2.next()) {
              e = e.value;
              if (b.h.has(e.id)) {
                var f = b.h.get(e.id);
                e.active || f.track.mode === "disabled" || (f.track.mode = "disabled");
                b.h.delete(e.id);
              } else {
                f = b.j.ownerDocument.createElement("track");
                f.kind = Xo(e);
                var g = f, h = void 0;
                if (e.label) h = e.label;
                else if (e.language) if (e.language in Lo) h = Lo[e.language];
                else {
                  var k2 = Ec(e.language);
                  k2 in Lo && (h = Lo[k2] + " (" + e.language + ")");
                }
                h || (h = e.originalTextId, e.language && e.language !== e.originalTextId && (h += " (" + e.language + ")"));
                g.label = h;
                e.language in Lo && (f.srclang = e.language);
                Sb().Ga() === "CHROMIUM" && (f.src = "data:,WEBVTT");
                f.track.mode = "disabled";
                b.j.appendChild(f);
              }
              c.set(e.id, f);
              e.active && (b.g = e.id);
            }
            d2 = t2(b.h.values());
            for (e = d2.next(); !e.done; e = d2.next()) e.value.remove();
            b.g > -1 && (c.has(b.g) ? (d2 = c.get(b.g).track, d2.mode === "disabled" && (d2.mode = b.A ? "showing" : "hidden")) : b.g = -1);
            b.h = c;
          };
          this.C = function() {
            if (!b.u) {
              var c = b.j;
              b.u = new Cf(function() {
                b.u = null;
                if (b.j === c) {
                  var d2 = -1, e = false;
                  if (b.h.has(b.g)) {
                    var f = b.h.get(b.g);
                    f.track.mode === "showing" ? (d2 = b.g, e = true) : f.track.mode === "hidden" && (d2 = b.g);
                  }
                  if (!e) for (e = t2(b.h), f = e.next(); !f.done; f = e.next()) {
                    var g = t2(f.value);
                    f = g.next().value;
                    g = g.next().value;
                    if (g.track.mode === "showing") {
                      d2 = f;
                      break;
                    } else d2 < 0 && g.track.mode === "hidden" && (d2 = f);
                  }
                  e = t2(b.h);
                  for (f = e.next(); !f.done; f = e.next()) g = t2(f.value), f = g.next().value, g = g.next().value, f !== d2 && g.track.mode !== "disabled" && (g.track.mode = "disabled");
                  b.g !== d2 && (b.g = d2, d2 > -1 && b.i.fg({
                    id: d2
                  }));
                  b.i.Fe(d2 > -1 && b.h.get(d2).track.mode === "showing");
                }
              }).Y(0);
            }
          };
          this.l.o(a, "loaded", function() {
            return b.enableTextDisplayer();
          });
          this.enableTextDisplayer();
        }
        p = Wo.prototype;
        p.configure = function() {
        };
        p.remove = function(a, b) {
          if (this.i) this.h.has(this.g) && Vo(this.h.get(this.g).track, function(c) {
            return c.startTime < b && c.endTime > a;
          });
          else return false;
          return true;
        };
        p.append = function(a) {
          this.h.has(this.g) && Uo(this.h.get(this.g).track, a);
        };
        p.destroy = function() {
          this.i && (this.j && this.D(), this.i = null);
          this.l && (this.l.release(), this.l = null);
          return Promise.resolve();
        };
        p.isTextVisible = function() {
          return this.A;
        };
        p.setTextVisibility = function(a) {
          this.A = a;
          if (this.h.has(this.g)) {
            var b = this.h.get(this.g).track;
            b.mode !== "disabled" && (a = a ? "showing" : "hidden", b.mode !== a && (b.mode = a));
          } else if (this.i && this.i.m === 3) if (b = Array.from(this.i.h.textTracks).filter(function(d2) {
            return ["captions", "subtitles", "forced"].includes(d2.kind);
          }), a) {
            a = null;
            b = t2(b);
            for (var c = b.next(); !c.done; c = b.next()) if (c = c.value, c.mode === "showing") {
              a = null;
              break;
            } else a || c.mode !== "hidden" || (a = c);
            a && (a.mode = "showing");
          } else for (a = t2(b), b = a.next(); !b.done; b = a.next()) b = b.value, b.mode === "showing" && (b.mode = "hidden");
        };
        p.setTextLanguage = function() {
        };
        p.enableTextDisplayer = function() {
          !this.j && this.i && this.i.m === 2 && (this.j = this.i.h, this.l.qa(this.i, "unloading", this.D), this.l.o(this.i, "textchanged", this.m), this.l.o(this.j.textTracks, "change", this.C), this.m());
        };
        function Xo(a) {
          var b = Sb();
          return a.forced && b.Ga() === "WEBKIT" ? "forced" : a.kind === "caption" || a.roles && a.roles.some(function(c) {
            return c.includes("transcribes-spoken-dialog");
          }) && a.roles.some(function(c) {
            return c.includes("describes-music-and-sound");
          }) ? "captions" : "subtitles";
        }
        S("shaka.text.NativeTextDisplayer", Wo);
        Wo.prototype.enableTextDisplayer = Wo.prototype.enableTextDisplayer;
        Wo.prototype.setTextLanguage = Wo.prototype.setTextLanguage;
        Wo.prototype.setTextVisibility = Wo.prototype.setTextVisibility;
        Wo.prototype.isTextVisible = Wo.prototype.isTextVisible;
        Wo.prototype.destroy = Wo.prototype.destroy;
        Wo.prototype.append = Wo.prototype.append;
        Wo.prototype.remove = Wo.prototype.remove;
        Wo.prototype.configure = Wo.prototype.configure;
        function Yo(a, b) {
          Wc("SimpleTextDisplayer", "Please migrate to NativeTextDisplayer");
          this.h = a;
          this.i = b;
          this.g = null;
          a = t2(Array.from(this.h.textTracks));
          for (b = a.next(); !b.done; b = a.next()) b = b.value, b.kind !== "metadata" && b.kind !== "chapters" && (b.mode = "disabled", b.label == this.i && (this.g = b));
          this.g && (this.g.mode = "hidden");
        }
        p = Yo.prototype;
        p.configure = function() {
        };
        p.remove = function(a, b) {
          if (!this.g) return false;
          Vo(this.g, function(c) {
            return c.startTime < b && c.endTime > a;
          });
          return true;
        };
        p.append = function(a) {
          this.g && Uo(this.g, a);
        };
        p.destroy = function() {
          this.g && (Vo(this.g, function() {
            return true;
          }), this.g.mode = "disabled");
          this.g = this.h = null;
          return Promise.resolve();
        };
        p.isTextVisible = function() {
          return this.g ? this.g.mode == "showing" : false;
        };
        p.setTextVisibility = function(a) {
          a && !this.g && Zo(this);
          this.g && (this.g.mode = a ? "showing" : "hidden");
        };
        p.setTextLanguage = function() {
        };
        p.enableTextDisplayer = function() {
          Zo(this);
        };
        function Zo(a) {
          a.h && !a.g && (a.g = a.h.addTextTrack("subtitles", a.i), a.g.mode = "hidden");
        }
        S("shaka.text.SimpleTextDisplayer", Yo);
        Yo.prototype.enableTextDisplayer = Yo.prototype.enableTextDisplayer;
        Yo.prototype.setTextLanguage = Yo.prototype.setTextLanguage;
        Yo.prototype.setTextVisibility = Yo.prototype.setTextVisibility;
        Yo.prototype.isTextVisible = Yo.prototype.isTextVisible;
        Yo.prototype.destroy = Yo.prototype.destroy;
        Yo.prototype.append = Yo.prototype.append;
        Yo.prototype.remove = Yo.prototype.remove;
        Yo.prototype.configure = Yo.prototype.configure;
        function $o() {
        }
        p = $o.prototype;
        p.configure = function() {
        };
        p.remove = function() {
        };
        p.append = function() {
        };
        p.destroy = function() {
        };
        p.isTextVisible = function() {
          return false;
        };
        p.setTextVisibility = function() {
        };
        p.setTextLanguage = function() {
        };
        p.enableTextDisplayer = function() {
        };
        S("shaka.text.StubTextDisplayer", $o);
        $o.prototype.enableTextDisplayer = $o.prototype.enableTextDisplayer;
        $o.prototype.setTextLanguage = $o.prototype.setTextLanguage;
        $o.prototype.setTextVisibility = $o.prototype.setTextVisibility;
        $o.prototype.isTextVisible = $o.prototype.isTextVisible;
        $o.prototype.destroy = $o.prototype.destroy;
        $o.prototype.append = $o.prototype.append;
        $o.prototype.remove = $o.prototype.remove;
        $o.prototype.configure = $o.prototype.configure;
        function ap(a, b) {
          var c = this;
          this.m = false;
          this.h = [];
          this.j = a;
          this.u = b;
          this.D = this.A = null;
          this.g = W("div");
          this.g.classList.add("shaka-text-container");
          this.g.style.textAlign = "center";
          this.g.style.display = "flex";
          this.g.style.flexDirection = "column";
          this.g.style.alignItems = "center";
          this.g.style.justifyContent = "flex-end";
          this.C = new Cf(function() {
            c.j.paused || bp(c);
          });
          cp(this);
          this.l = /* @__PURE__ */ new Map();
          this.i = new Qc();
          this.i.o(document, "fullscreenchange", function() {
            bp(c, true);
          });
          this.i.o(this.j, "seeking", function() {
            bp(c, true);
          });
          this.i.o(this.j, "ratechange", function() {
            cp(c);
          });
          this.i.o(this.j, "resize", function() {
            var d2 = c.j, e = d2.videoWidth;
            d2 = d2.videoHeight;
            e && d2 ? c.A = e / d2 : c.A = null;
          });
          this.F = null;
          "ResizeObserver" in window7 && (this.F = new ResizeObserver(function() {
            bp(c, true);
          }), this.F.observe(this.g));
          this.G = /* @__PURE__ */ new Map();
        }
        p = ap.prototype;
        p.configure = function(a) {
          this.D = a;
          cp(this);
          bp(this, true);
        };
        p.append = function(a) {
          var b = [].concat(x(this.h));
          a = t2(So(a));
          for (var c = a.next(), d2 = {}; !c.done; d2 = {
            Rg: void 0
          }, c = a.next()) d2.Rg = c.value, b.some(/* @__PURE__ */ function(e) {
            return function(f) {
              return De(f, e.Rg);
            };
          }(d2)) || this.h.push(d2.Rg);
          this.h.length && cp(this);
          bp(this);
        };
        p.destroy = function() {
          if (!this.g) return Promise.resolve();
          this.g.parentElement && this.u.removeChild(this.g);
          this.g = null;
          this.m = false;
          this.h = [];
          this.C && (this.C.stop(), this.C = null);
          this.l.clear();
          this.i && (this.i.release(), this.i = null);
          this.F && (this.F.disconnect(), this.F = null);
          return Promise.resolve();
        };
        p.remove = function(a, b) {
          if (!this.g) return false;
          var c = this.h.length;
          this.h = this.h.filter(function(d2) {
            return d2.startTime < a || d2.endTime >= b;
          });
          bp(this, c > this.h.length);
          this.h.length || cp(this);
          return true;
        };
        p.isTextVisible = function() {
          return this.m;
        };
        p.setTextVisibility = function(a) {
          (this.m = a) ? (this.g.parentElement || this.u.appendChild(this.g), bp(this, true)) : this.g.parentElement && this.u.removeChild(this.g);
        };
        p.setTextLanguage = function(a) {
          a && a != "und" ? this.g.setAttribute("lang", a) : this.g.setAttribute("lang", "");
        };
        p.enableTextDisplayer = function() {
        };
        function cp(a) {
          a.C && (a.h.length ? a.C.za((a.D ? a.D.captionsUpdatePeriod : 0.25) / Math.max(1, Math.abs(a.j.playbackRate))) : a.C.stop());
        }
        function dp(a, b) {
          for (; b != null; ) {
            if (b == a.g) return true;
            b = b.parentElement;
          }
          return false;
        }
        function ep(a, b, c, d2, e) {
          var f = false, g = [], h = [];
          b = t2(b);
          for (var k2 = b.next(); !k2.done; k2 = b.next()) {
            k2 = k2.value;
            e.push(k2);
            var l = a.l.get(k2), m = k2.startTime <= d2 && k2.endTime > d2, n = l ? l.gk : null;
            l && (g.push(l.Sg), l.pd && g.push(l.pd), m || (f = true, a.l.delete(k2), l = null));
            m && (h.push(k2), l ? dp(a, n) || (f = true) : (fp(a, k2, e), l = a.l.get(k2), n = l.gk, f = true));
            k2.nestedCues.length > 0 && n && ep(a, k2.nestedCues, n, d2, e);
            e.pop();
          }
          if (f) {
            d2 = t2(g);
            for (e = d2.next(); !e.done; e = d2.next()) e = e.value, e.parentElement && e.parentElement.removeChild(e);
            h.sort(function(q, r2) {
              return q.startTime != r2.startTime ? q.startTime - r2.startTime : q.endTime - r2.endTime;
            });
            h = t2(h);
            for (d2 = h.next(); !d2.done; d2 = h.next()) d2 = a.l.get(d2.value), d2.pd ? (d2.pd.contains(c) && d2.pd.removeChild(c), c.appendChild(d2.pd), d2.pd.appendChild(d2.Sg)) : c.appendChild(d2.Sg);
          }
        }
        function bp(a, b) {
          if (a.g) {
            var c = a.j.currentTime;
            if (!a.m || (b === void 0 ? 0 : b)) {
              b = t2(a.G.values());
              for (var d2 = b.next(); !d2.done; d2 = b.next()) Sj(d2.value);
              Sj(a.g);
              a.l.clear();
              a.G.clear();
            }
            a.m && ep(a, a.h, a.g, c, []);
          }
        }
        function fp(a, b, c) {
          var d2 = c.length > 1, e = d2 ? "span" : "div";
          b.lineBreak && (e = "br");
          b.rubyTag && (e = b.rubyTag);
          d2 = !d2 && b.nestedCues.length > 0;
          var f = W(e);
          e != "br" && gp2(a, f, b, c, d2);
          c = null;
          if (b.region && b.region.id) {
            var g = b.region, h = a.A === 4 / 3 ? 2.5 : 1.9;
            c = g.id + "_" + g.width + "x" + g.height + (g.heightUnits == rd ? "%" : "px") + "-" + g.viewportAnchorX + "x" + g.viewportAnchorY + (g.viewportAnchorUnits == rd ? "%" : "px");
            if (a.G.has(c)) c = a.G.get(c);
            else {
              e = W("span");
              var k2 = g.heightUnits == rd ? "%" : "px", l = g.widthUnits == rd ? "%" : "px", m = g.viewportAnchorUnits == rd ? "%" : "px";
              e.id = "shaka-text-region---" + c;
              e.classList.add("shaka-text-region");
              e.style.position = "absolute";
              var n = g.height, q = g.width;
              g.heightUnits === 2 && (n = g.height * 5.33, k2 = "%");
              g.widthUnits === 2 && (q = g.width * h, l = "%");
              e.style.height = n + k2;
              e.style.width = q + l;
              g.viewportAnchorUnits === 2 ? (h = g.viewportAnchorY / 75 * 100, k2 = g.viewportAnchorX / (a.A === 4 / 3 ? 160 : 210) * 100, h -= g.regionAnchorY * n / 100, k2 -= g.regionAnchorX * q / 100, e.style.top = h + "%", e.style.left = k2 + "%") : (e.style.top = g.viewportAnchorY - g.regionAnchorY * n / 100 + m, e.style.left = g.viewportAnchorX - g.regionAnchorX * q / 100 + m);
              g.heightUnits !== 0 && g.widthUnits !== 0 && g.viewportAnchorUnits !== 0 && (g = Math.max(0, Math.min(100 - (parseInt(e.style.width.slice(0, -1), 10) || 0), parseInt(e.style.left.slice(0, -1), 10) || 0)), e.style.top = Math.max(0, Math.min(100 - (parseInt(e.style.height.slice(0, -1), 10) || 0), parseInt(e.style.top.slice(0, -1), 10) || 0)) + "%", e.style.left = g + "%");
              e.style.display = "flex";
              e.style.flexDirection = "column";
              e.style.alignItems = "center";
              e.style.justifyContent = b.displayAlign == "before" ? "flex-start" : b.displayAlign == "center" ? "center" : "flex-end";
              a.G.set(c, e);
              c = e;
            }
          }
          e = f;
          d2 && (e = W("span"), e.classList.add("shaka-text-wrapper"), e.style.backgroundColor = b.backgroundColor, e.style.lineHeight = "normal", f.appendChild(e));
          a.l.set(b, {
            Sg: f,
            gk: e,
            pd: c
          });
        }
        function hp(a) {
          var b = a.direction, c = a.positionAlign;
          a = a.textAlign;
          return c !== te ? c : a === "left" || a === "start" && b === ve || a === "end" && b === "rtl" ? "line-left" : a === "right" || a === "start" && b === "rtl" || a === "end" && b === ve ? "line-right" : "center";
        }
        function gp2(a, b, c, d2, e) {
          var f = b.style, g = c.nestedCues.length == 0, h = d2.length > 1;
          f.whiteSpace = "pre-wrap";
          var k2 = c.payload.replace(/\s+$/g, function(m) {
            return "\xA0".repeat(m.length);
          });
          f.webkitTextStrokeColor = c.textStrokeColor;
          f.webkitTextStrokeWidth = c.textStrokeWidth;
          f.color = c.color;
          f.direction = c.direction;
          f.opacity = c.opacity;
          f.paddingLeft = ip(c.linePadding, c, a.u);
          f.paddingRight = ip(c.linePadding, c, a.u);
          f.textCombineUpright = c.textCombineUpright;
          f.textShadow = c.textShadow;
          if (c.backgroundImage) f.backgroundImage = "url('" + c.backgroundImage + "')", f.backgroundRepeat = "no-repeat", f.backgroundSize = "contain", f.backgroundPosition = "center", c.backgroundColor && (f.backgroundColor = c.backgroundColor), f.width = "100%", f.height = "100%";
          else {
            if (c.nestedCues.length) var l = b;
            else l = W("span"), b.appendChild(l);
            c.border && (l.style.border = c.border);
            e || ((b = jp(d2, function(m) {
              return m.backgroundColor;
            })) ? l.style.backgroundColor = b : k2 && (l.style.backgroundColor = "rgba(0, 0, 0, 0.8)"));
            k2 && (l.setAttribute("translate", "no"), l.textContent = k2);
          }
          if (h && !d2[d2.length - 1].isContainer) f.display = "inline";
          else {
            f.display = "flex";
            f.flexDirection = "column";
            f.alignItems = "center";
            if (c.textAlign == "left" || c.textAlign == "start") f.width = "100%", f.alignItems = "start";
            else if (c.textAlign == "right" || c.textAlign == "end") f.width = "100%", f.alignItems = "end";
            f.justifyContent = c.displayAlign == "before" ? "flex-start" : c.displayAlign == "center" ? "center" : "flex-end";
          }
          g || (f.margin = "0");
          f.fontFamily = c.fontFamily;
          f.fontWeight = c.fontWeight.toString();
          f.fontStyle = c.fontStyle;
          f.letterSpacing = c.letterSpacing;
          f.fontSize = ip(c.fontSize, c, a.u, a.D ? a.D.fontScaleFactor : 1);
          d2 = c.line;
          d2 != null && (g = c.lineInterpretation, g == xe && (g = 1, h = 16, a.A && a.A < 1 && (h = 32), d2 = d2 < 0 ? 100 + d2 / h * 100 : d2 / h * 100), g == 1 && (f.position = "absolute", c.writingMode == we ? (f.width = "100%", c.lineAlign == ye ? f.top = d2 + "%" : c.lineAlign == "end" && (f.bottom = 100 - d2 + "%")) : c.writingMode == "vertical-lr" ? (f.height = "100%", c.lineAlign == ye ? f.left = d2 + "%" : c.lineAlign == "end" && (f.right = 100 - d2 + "%")) : (f.height = "100%", c.lineAlign == ye ? f.right = d2 + "%" : c.lineAlign == "end" && (f.left = 100 - d2 + "%"))));
          f.lineHeight = c.lineHeight;
          a = hp(c);
          a == "line-left" ? (f.cssFloat = "left", c.position !== null && (f.position = "absolute", c.writingMode == we ? (f.left = c.position + "%", f.width = "auto") : f.top = c.position + "%")) : a == "line-right" ? (f.cssFloat = "right", c.position !== null && (f.position = "absolute", c.writingMode == we ? (f.right = 100 - c.position + "%", f.width = "auto") : f.bottom = c.position + "%")) : c.position !== null && c.position != 50 && (f.position = "absolute", c.writingMode == we ? (f.left = c.position + "%", f.width = "auto") : f.top = c.position + "%");
          f.textAlign = c.textAlign;
          f.textDecoration = c.textDecoration.join(" ");
          f.writingMode = c.writingMode;
          "writingMode" in document.documentElement.style && f.writingMode == c.writingMode || (f.webkitWritingMode = c.writingMode);
          c.size && (c.writingMode == we ? f.width = c.size + "%" : f.height = c.size + "%");
        }
        function ip(a, b, c, d2) {
          d2 = d2 === void 0 ? 1 : d2;
          var e = (e = new RegExp(/(\d*\.?\d+)([a-z]+|%+)/).exec(a)) ? {
            value: Number(e[1]),
            unit: e[2]
          } : null;
          if (!e) return a;
          a = e.unit;
          d2 *= e.value;
          switch (a) {
            case "%":
              return d2 / 100 * c.clientHeight / b.cellResolution.rows + "px";
            case "c":
              return c.clientHeight * d2 / b.cellResolution.rows + "px";
            default:
              return d2 + a;
          }
        }
        function jp(a, b) {
          for (var c = a.length - 1; c >= 0; c--) {
            var d2 = b(a[c]);
            if (d2 || d2 === 0) return d2;
          }
          return null;
        }
        S("shaka.text.UITextDisplayer", ap);
        ap.prototype.enableTextDisplayer = ap.prototype.enableTextDisplayer;
        ap.prototype.setTextLanguage = ap.prototype.setTextLanguage;
        ap.prototype.setTextVisibility = ap.prototype.setTextVisibility;
        ap.prototype.isTextVisible = ap.prototype.isTextVisible;
        ap.prototype.remove = ap.prototype.remove;
        ap.prototype.destroy = ap.prototype.destroy;
        ap.prototype.append = ap.prototype.append;
        ap.prototype.configure = ap.prototype.configure;
        function kp(a, b) {
          function c(f) {
            for (var g = f, h = t2(b), k2 = h.next(); !k2.done; k2 = h.next()) k2 = k2.value, k2.end && k2.start < f && (g += k2.end - k2.start);
            f = Math.floor(g / 3600);
            h = Math.floor(g / 60 % 60);
            k2 = Math.floor(g % 60);
            g = Math.floor(g * 1e3 % 1e3);
            return (f < 10 ? "0" : "") + f + ":" + (h < 10 ? "0" : "") + h + ":" + (k2 < 10 ? "0" : "") + k2 + "." + (g < 100 ? g < 10 ? "00" : "0" : "") + g;
          }
          var d2 = Ro(a);
          a = "WEBVTT\n\n";
          d2 = t2(d2);
          for (var e = d2.next(); !e.done; e = d2.next()) e = e.value, a += c(e.startTime) + " --> " + c(e.endTime) + function(f) {
            var g = [];
            switch (f.textAlign) {
              case "left":
                g.push("align:left");
                break;
              case "right":
                g.push("align:right");
                break;
              case ue:
                g.push("align:middle");
                break;
              case "start":
                g.push("align:start");
                break;
              case "end":
                g.push("align:end");
            }
            switch (f.writingMode) {
              case "vertical-lr":
                g.push("vertical:lr");
                break;
              case "vertical-rl":
                g.push("vertical:rl");
            }
            return g.length ? " " + g.join(" ") : "";
          }(e) + "\n", a += e.payload + "\n\n";
          return a;
        }
        S("shaka.text.WebVttGenerator", function() {
        });
        function lp(a, b) {
          this.h = a;
          this.g = b;
          this.i = void 0;
          this.A = false;
          this.G = true;
          this.l = this.D = false;
          this.u = this.m = void 0;
          this.C = 0;
          this.H = false;
          this.F = new Qc();
          this.j = null;
        }
        lp.prototype.setMediaElement = function(a) {
          this.j = a;
          mp(this);
        };
        lp.prototype.configure = function(a) {
          this.g = a;
        };
        function np(a) {
          a.A = false;
          a.G = true;
          a.D = false;
          a.l = false;
          a.m = 0;
          a.u = 0;
          a.C = 0;
          a.H = false;
          a.j = null;
          a.F.Ta();
        }
        function op(a, b) {
          a.l = b;
          a.l ? a.i == pp ? a.i = qp : a.i == rp && (a.i = sp) : a.i == qp ? a.i = pp : a.i == sp && (a.i = rp);
        }
        function tp(a, b) {
          if (a.g && a.g.enabled && a.g.version == up && a.j && a.j.autoplay) {
            var c = a.j.play();
            c && c.then(function() {
              a.C = b;
            }).catch(function() {
              a.C = 0;
            });
          }
        }
        function vp(a, b, c) {
          try {
            if (!a.g.enabled) return b;
            var d2 = wp(a);
            a: {
              switch (c.toLowerCase()) {
                case "audio/mp4":
                case "audio/webm":
                case "audio/ogg":
                case "audio/mpeg":
                case "audio/aac":
                case "audio/flac":
                case "audio/wav":
                  var e = xp;
                  break a;
                case "video/webm":
                case "video/mp4":
                case "video/mpeg":
                case "video/mp2t":
                  e = yp;
                  break a;
                case "application/x-mpegurl":
                case "application/vnd.apple.mpegurl":
                case "application/dash+xml":
                case "video/vnd.mpeg.dash.mpd":
                case "application/vnd.ms-sstr+xml":
                  e = zp;
                  break a;
              }
              e = void 0;
            }
            d2.ot = e;
            d2.su = true;
            var f = Ap(d2);
            return Bp(b, f);
          } catch (g) {
            return cb("CMCD_SRC_ERROR", "Could not generate src CMCD data.", g), b;
          }
        }
        function mp(a) {
          a.F.qa(a.j, "play", function() {
            a.m || (a.m = Date.now());
          });
          a.F.qa(a.j, "playing", function() {
            a.u || (a.u = Date.now());
          });
        }
        function wp(a) {
          a.g.sessionId || (a.g.sessionId = window7.crypto.randomUUID());
          return {
            v: a.g.version,
            sf: a.i,
            sid: a.g.sessionId,
            cid: a.g.contentId,
            mtp: a.h.getBandwidthEstimate() / 1e3
          };
        }
        function Cp(a, b, c) {
          c = c === void 0 ? {} : c;
          var d2 = d2 === void 0 ? a.g.useHeaders : d2;
          if (a.g.enabled) if (a = Dp(a, c), d2) d2 = Ep(a), Object.keys(d2).length && Object.assign(b.headers, d2);
          else {
            var e = Ap(a);
            e && (b.uris = b.uris.map(function(f) {
              return Bp(f, e);
            }));
          }
        }
        function Fp(a, b) {
          var c = a.g.includeKeys;
          return c.length ? Object.keys(b).reduce(function(d2, e) {
            c.includes(e) && (d2[e] = b[e]);
            return d2;
          }, {}) : b;
        }
        function Gp(a) {
          if (a.type === 0) return Hp;
          if (a = a.stream) {
            var b = a.type;
            if (b == "video") return a.codecs && a.codecs.includes(",") ? yp : Ip;
            if (b == "audio") return xp;
            if (b == "text") return a.mimeType === "application/mp4" ? Jp : Kp;
          }
        }
        function Lp(a, b) {
          b = a.h.cc()[b];
          if (!b.length) return NaN;
          var c = a.h.getCurrentTime();
          return (a = b.find(function(d2) {
            return d2.start <= c && d2.end >= c;
          })) ? (a.end - c) * 1e3 : NaN;
        }
        function Mp(a, b) {
          b = a.h.cc()[b];
          if (!b.length) return 0;
          var c = a.h.getCurrentTime();
          return (a = b.find(function(d2) {
            return d2.start <= c && d2.end >= c;
          })) ? (a.end - c) * 1e3 : 0;
        }
        function aq(a, b) {
          var c = a.h.rb();
          if (!c.length) return NaN;
          a = c[0];
          c = t2(c);
          for (var d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, d2.type === "variant" && d2.bandwidth > a.bandwidth && (a = d2);
          switch (b) {
            case Ip:
              return a.videoBandwidth || NaN;
            case xp:
              return a.audioBandwidth || NaN;
            default:
              return a.bandwidth;
          }
        }
        function Dp(a, b) {
          b = b === void 0 ? {} : b;
          Object.assign(b, wp(a));
          b.pr = a.h.Ya();
          var c = b.ot === Ip || b.ot === yp;
          a.D && c && (b.bs = true, b.su = true, a.D = false);
          b.su == null && (b.su = a.G);
          b.v === up && (a.h.U() && (b.ltc = a.h.uf()), c = !a.H && a.u && a.m ? a.u - (a.C || a.m) : void 0, c != void 0 && (b.msd = c, a.H = true));
          return Fp(a, b);
        }
        function Ap(a) {
          function b(n) {
            return c(n / 100) * 100;
          }
          function c(n) {
            return Math.round(n);
          }
          function d2(n) {
            return !Number.isNaN(n) && n != null && n !== "" && n !== false;
          }
          var e = [], f = {
            br: c,
            d: c,
            bl: b,
            dl: b,
            mtp: b,
            nor: function(n) {
              return encodeURIComponent(n);
            },
            rtp: b,
            tb: c
          }, g = Object.keys(a || {}).sort();
          g = t2(g);
          for (var h = g.next(); !h.done; h = g.next()) {
            h = h.value;
            var k2 = a[h];
            if (d2(k2) && (h !== "v" || k2 !== 1) && (h != "pr" || k2 !== 1)) {
              var l = f[h];
              l && (k2 = l(k2));
              l = typeof k2;
              var m = void 0;
              m = l === "string" && h !== "ot" && h !== "sf" && h !== "st" ? h + "=" + JSON.stringify(k2) : l === "boolean" ? h : l === "symbol" ? h + "=" + k2.description : h + "=" + k2;
              e.push(m);
            }
          }
          return e.join(",");
        }
        function Ep(a) {
          var b = Object.keys(a), c = {}, d2 = ["Object", "Request", "Session", "Status"], e = [{}, {}, {}, {}], f = {
            br: 0,
            d: 0,
            ot: 0,
            tb: 0,
            bl: 1,
            dl: 1,
            mtp: 1,
            nor: 1,
            nrr: 1,
            su: 1,
            ltc: 1,
            cid: 2,
            pr: 2,
            sf: 2,
            sid: 2,
            st: 2,
            v: 2,
            msd: 2,
            bs: 3,
            rtp: 3
          };
          b = t2(b);
          for (var g = b.next(); !g.done; g = b.next()) g = g.value, e[f[g] != null ? f[g] : 1][g] = a[g];
          for (a = 0; a < e.length; a++) (f = Ap(e[a])) && (c["CMCD-" + d2[a]] = f);
          return c;
        }
        function Bp(a, b) {
          if (!b || a.includes("offline:")) return a;
          a = new rb(a);
          a.g.set("CMCD", b);
          return a.toString();
        }
        var zp = "m", xp = "a", Ip = "v", yp = "av", Hp = "i", Kp = "c", Jp = "tt", up = 2, pp = "d", qp = "ld", rp = "h", sp = "lh";
        S("shaka.util.CmcdManager.StreamingFormat", {
          DASH: pp,
          fn: qp,
          HLS: rp,
          gn: sp,
          wn: "s",
          OTHER: "o"
        });
        function bq(a) {
          this.h = a;
          this.g = null;
        }
        p = bq.prototype;
        p.configure = function(a) {
          this.h = a;
        };
        p.Yi = function() {
          return this.h.enabled && this.h.applyMaximumSuggestedBitrate && this.g && this.g.has(cq) ? this.g.get(cq) * 1e3 : null;
        };
        p.Xi = function() {
          return this.h.enabled && this.g && this.g.has(dq) ? this.g.get(dq) * 1e3 : null;
        };
        p.fl = function() {
          return this.h.enabled && this.g && this.g.has(eq) ? this.g.get(eq) : null;
        };
        p.hl = function() {
          return this.h.enabled && this.g && this.g.has(fq) ? this.g.get(fq) : null;
        };
        p.getBandwidthEstimate = function(a) {
          var b = this.Xi();
          if (!b) return a;
          var c = this.h.estimatedThroughputWeightRatio;
          return c > 0 && c <= 1 ? a * (1 - c) + b * c : a;
        };
        function gq(a) {
          return a ? a.toLowerCase() === "false" ? false : /^[-0-9]/.test(a) ? parseInt(a, 10) : a.replace(/["]+/g, "") : true;
        }
        S("shaka.util.CmsdManager", bq);
        bq.prototype.getBandwidthEstimate = bq.prototype.getBandwidthEstimate;
        bq.prototype.getRoundTripTime = bq.prototype.hl;
        bq.prototype.getResponseDelay = bq.prototype.fl;
        bq.prototype.getEstimatedThroughput = bq.prototype.Xi;
        bq.prototype.getMaxBitrate = bq.prototype.Yi;
        var dq = "etp", cq = "mb", eq = "rd", fq = "rtt";
        function hq() {
          this.g = null;
          this.h = [];
        }
        function iq(a, b) {
          return P(function(c) {
            if (c.g == 1) return a.g ? G(c, new Promise(function(d2) {
              return a.h.push(d2);
            }), 2) : c.B(2);
            a.g = b;
            H(c);
          });
        }
        hq.prototype.release = function() {
          this.h.length > 0 ? this.h.shift()() : this.g = null;
        };
        function Y(a, b, c) {
          b = b === void 0 ? null : b;
          lb.call(this);
          var d2 = this;
          this.m = jq;
          this.h = null;
          this.Re = b;
          this.Z = false;
          this.We = new Qc();
          this.Me = new Qc();
          this.j = new Qc();
          this.kc = new Qc();
          this.Pd = new Qc();
          this.G = this.H = this.F = this.J = null;
          this.Ye = 0;
          this.ea = new hq();
          this.O = this.$ = this.V = this.i = this.Ec = this.I = this.l = this.Je = this.R = this.Ei = this.sa = this.L = this.Za = this.Ia = this.Le = this.P = this.Ma = this.K = this.Ob = null;
          this.aa = false;
          this.Va = this.A = null;
          this.Qe = 1e9;
          this.Ve = [];
          this.fb = [];
          this.Bg = -1;
          this.g = kq(this);
          this.Dg = Zn();
          this.S = null;
          this.Ze = -1;
          this.jc = null;
          this.ua = {
            width: Infinity,
            height: Infinity
          };
          this.Pe = new yi(this.g, this.ua, null);
          this.Te = [];
          this.C = null;
          this.M = this.g.adaptationSetCriteriaFactory();
          this.M.configure({
            language: this.g.preferredAudioLanguage,
            role: this.g.preferredVariantRole,
            channelCount: 0,
            Qc: this.g.preferredVideoHdrLevel,
            spatialAudio: this.g.preferSpatialAudio,
            videoLayout: this.g.preferredVideoLayout,
            Zc: this.g.preferredAudioLabel,
            Yd: this.g.preferredVideoLabel,
            codecSwitchingStrategy: this.g.mediaSource.codecSwitchingStrategy,
            audioCodec: "",
            ae: "",
            $e: 0,
            preferredAudioCodecs: this.g.preferredAudioCodecs,
            preferredAudioChannelCount: this.g.preferredAudioChannelCount
          });
          this.Sd = this.g.preferredTextLanguage;
          this.Zd = this.g.preferredTextRole;
          this.Oe = this.g.preferForcedSubs;
          this.Ne = [];
          c && c(this);
          this.L = lq(this);
          this.sa = new bq(this.g.cmsd);
          this.J = mq(this);
          this.Xd = this.oa = this.va = this.D = null;
          this.Fg = false;
          this.Cg = [];
          this.Eg = new Cf(function() {
            return P(function(e) {
              if (e.g == 1) return d2.oa ? G(e, d2.bc(d2.Xd, true), 3) : e.B(0);
              if (e.g != 4) return G(e, d2.load(d2.oa), 4);
              d2.Fg ? d2.Xd.pause() : d2.Xd.play();
              d2.oa = null;
              d2.Fg = false;
              H(e);
            });
          });
          nq && (this.D = nq(), this.D.configure(this.g.ads), this.Pd.o(this.D, "ad-content-pause-requested", function(e) {
            var f;
            return P(function(g) {
              if (g.g == 1) {
                d2.Eg.stop();
                if (d2.oa) return g.B(0);
                d2.Xd = d2.h;
                d2.Fg = d2.isEnded();
                f = e.saveLivePosition || false;
                return G(g, d2.Si(true, f), 3);
              }
              d2.oa = g.h;
              H(g);
            });
          }), this.Pd.o(this.D, "ad-content-resume-requested", function(e) {
            e = e.offset || 0;
            if (d2.oa) {
              var f = d2.oa;
              f.m && e && (typeof f.m === "number" ? f.m += e : f.m.setTime(f.m.getTime() + e * 1e3));
            }
            d2.Eg.Y(0.1);
          }), this.Pd.o(this.D, "ad-content-attach-requested", function() {
            return P(function(e) {
              return d2.h || !d2.Xd ? e.B(0) : G(e, d2.bc(d2.Xd, true), 0);
            });
          }));
          oq && (this.va = oq(this), this.va.configure(this.g.queue));
          this.We.o(window7, "online", function() {
            pq(d2);
            d2.Xh();
          });
          this.Se = new Cf(function() {
            for (var e = Date.now() / 1e3, f = false, g = true, h = t2(d2.i.variants), k2 = h.next(); !k2.done; k2 = h.next()) k2 = k2.value, k2.disabledUntilTime > 0 && k2.disabledUntilTime <= e && (k2.disabledUntilTime = 0, f = true), k2.disabledUntilTime > 0 && (g = false);
            g && d2.Se.stop();
            f && qq(d2, false, void 0, false, false);
          });
          this.Oa = null;
          a && (Wc("Player w/ mediaElement", "Please migrate from initializing Player with a mediaElement; use the attach method instead."), this.bc(a, true));
          this.u = null;
        }
        ma(Y, lb);
        function rq(a) {
          a.R != null && (bd(a.R), a.R.release(), a.R = null);
        }
        function sq(a, b, c) {
          c || b.lcevc.enabled ? (rq(a), a.R == null && (a.R = new $c(a.h, a.Ei, b.lcevc, c), a.H && (a.H.M = a.R))) : rq(a);
        }
        function tq(a, b) {
          return new T(a, b);
        }
        p = Y.prototype;
        p.destroy = function() {
          var a = this, b;
          return P(function(c) {
            switch (c.g) {
              case 1:
                if (a.m == uq) return c.return();
                rq(a);
                b = a.detach();
                a.m = uq;
                return G(c, b, 2);
              case 2:
                return G(c, a.Vg(), 3);
              case 3:
                a.We && (a.We.release(), a.We = null);
                a.Me && (a.Me.release(), a.Me = null);
                a.j && (a.j.release(), a.j = null);
                a.kc && (a.kc.release(), a.kc = null);
                a.Pd && (a.Pd.release(), a.Pd = null);
                a.Va = null;
                a.g = null;
                a.C = null;
                a.Re = null;
                a.L = null;
                a.sa = null;
                if (!a.J) {
                  c.B(4);
                  break;
                }
                return G(c, a.J.destroy(), 5);
              case 5:
                a.J = null;
              case 4:
                a.A && (a.A.release(), a.A = null), a.va && (a.va.destroy(), a.va = null), lb.prototype.release.call(a), H(c);
            }
          });
        };
        function vq(a, b) {
          wq.set(a, b);
        }
        function xq() {
          window7.Promise || bb("A Promise implementation or polyfill is required");
          if (!(window7.Promise && window7.Uint8Array && Array.prototype.forEach) || (navigator.userAgent || "").includes("Trident/")) return false;
          Sb();
          return Ji() ? true : Ki().canPlayType("application/x-mpegurl") != "";
        }
        function yq(a, b) {
          a.dispatchEvent(tq("onstatechange", (/* @__PURE__ */ new Map()).set("state", b)));
        }
        p.bc = function(a, b) {
          b = b === void 0 ? true : b;
          var c = this, d2, e, f;
          return P(function(g) {
            switch (g.g) {
              case 1:
                if (c.m == uq) throw new U(2, 7, 7e3);
                d2 = c.h && c.h == a;
                if (!c.h || c.h == a) {
                  g.B(2);
                  break;
                }
                return G(g, c.detach(), 2);
              case 2:
                return G(g, zq(c, "attach"), 4);
              case 4:
                if (g.h) return g.return();
                sa(g, 5, 6);
                d2 || (yq(c, "attach"), e = function() {
                  var h = Aq(c, false);
                  h && Bq(c, h);
                }, c.Me.o(a, "error", e), c.h = a, c.L && c.L.setMediaElement(a));
                Sb();
                if (!b || !Ji() || c.H) {
                  g.B(6);
                  break;
                }
                return G(g, Cq(c), 6);
              case 6:
                wa(g);
                c.ea.release();
                xa(g, 0);
                break;
              case 5:
                return f = va(g), G(g, c.detach(), 10);
              case 10:
                throw f;
            }
          });
        };
        p.Gi = function(a) {
          this.Ei = a;
        };
        p.detach = function(a) {
          a = a === void 0 ? false : a;
          var b = this;
          return P(function(c) {
            if (c.g == 1) {
              if (b.m == uq) throw new U(2, 7, 7e3);
              return G(c, b.rc(false, a), 2);
            }
            if (c.g != 3) return G(c, zq(b, "detach"), 3);
            if (c.h) return c.return();
            try {
              b.h && (b.Me.Ta(), b.h = null), yq(b, "detach"), b.D && !a && b.D.release();
            } finally {
              b.ea.release();
            }
            H(c);
          });
        };
        function zq(a, b) {
          var c;
          return P(function(d2) {
            return d2.g == 1 ? (c = ++a.Ye, G(d2, iq(a.ea, b), 2)) : c != a.Ye ? (a.ea.release(), d2.return(true)) : d2.return(false);
          });
        }
        p.rc = function(a, b) {
          a = a === void 0 ? true : a;
          b = b === void 0 ? false : b;
          var c = this, d2, e, f, g, h, k2, l, m, n, q, r2, u, w;
          return P(function(v) {
            switch (v.g) {
              case 1:
                return c.m != uq && (c.m = jq), G(v, zq(c, "unload"), 2);
              case 2:
                if (v.h) return v.return();
                ta(v, 3);
                c.aa = false;
                yq(c, "unload");
                rq(c);
                d2 = c.Ne.map(function(y) {
                  return y();
                });
                c.Ne = [];
                return G(v, Promise.all(d2), 5);
              case 5:
                c.dispatchEvent(tq("unloading"));
                c.Le && (c.Le.release(), c.Le = null);
                c.Ia && (c.Ia.release(), c.Ia = null);
                c.Za && (c.Za.release(), c.Za = null);
                c.h && (c.j.Ta(), c.kc.Ta());
                c.Se.stop();
                c.Ob && (c.Ob.release(), c.Ob = null);
                c.Ma && (c.Ma.stop(), c.Ma = null);
                if (!c.I) {
                  v.B(6);
                  break;
                }
                return G(v, c.I.stop(), 7);
              case 7:
                c.I = null, c.Ec = null;
              case 6:
                if (!c.A) {
                  v.B(8);
                  break;
                }
                return G(v, c.A.stop(), 8);
              case 8:
                if (!c.l) {
                  v.B(10);
                  break;
                }
                return G(v, c.l.destroy(), 11);
              case 11:
                c.l = null;
              case 10:
                c.K && (c.K.release(), c.K = null);
                c.G && (c.G.release(), c.G = null);
                if ("webkit" !== window7.shakaMediaKeysPolyfill || !c.F) {
                  v.B(12);
                  break;
                }
                return G(v, c.F.destroy(), 13);
              case 13:
                c.F = null;
              case 12:
                if (!c.H) {
                  v.B(14);
                  break;
                }
                return G(v, c.H.destroy(), 15);
              case 15:
                c.H = null;
              case 14:
                if (c.D && !b) c.D.onAssetUnload();
                c.oa && !b && (c.oa.destroy(), c.oa = null);
                b || c.Eg.stop();
                c.L && np(c.L);
                c.sa && (c.sa.g = null);
                if (!c.u) {
                  v.B(16);
                  break;
                }
                return G(v, c.u.destroy(), 17);
              case 17:
                c.u = null;
              case 16:
                c.Z = false;
                if (c.h) {
                  e = t2(c.Cg);
                  for (f = e.next(); !f.done; f = e.next()) g = f.value, g.src.startsWith("blob:") && URL.revokeObjectURL(g.src), g.remove();
                  c.Cg = [];
                  Qj(c.h) && c.h.load();
                }
                if (!c.F) {
                  v.B(18);
                  break;
                }
                return G(v, c.F.destroy(), 19);
              case 19:
                c.F = null;
              case 18:
                c.Oa && c.V != c.Oa.ed() && (c.Oa.A || c.Oa.destroy(), c.Oa = null);
                c.V = null;
                c.$ = null;
                c.P = null;
                if (c.i) {
                  h = t2(c.i.variants);
                  for (k2 = h.next(); !k2.done; k2 = h.next()) for (l = k2.value, m = t2([l.audio, l.video]), n = m.next(); !n.done; n = m.next()) (q = n.value) && q.segmentIndex && q.segmentIndex.release();
                  r2 = t2(c.i.textStreams);
                  for (u = r2.next(); !u.done; u = r2.next()) w = u.value, w.segmentIndex && w.segmentIndex.release();
                }
                c.g && c.g.streaming.clearDecodingCache && (Vf.clear(), Ig.clear());
                c.i = null;
                c.C = new go();
                c.Di = null;
                c.jc = null;
                c.S = null;
                c.Ze = -1;
                c.Ve = [];
                c.fb = [];
                c.Bg = -1;
                c.J && c.J.Ni();
                Dq(c);
              case 3:
                wa(v);
                c.ea.release();
                xa(v, 4);
                break;
              case 4:
                Sb();
                if (a && Ji() && !c.H && c.h) return G(v, Cq(c), 0);
                v.B(0);
            }
          });
        };
        p.Cm = function(a) {
          this.O = a;
        };
        p.load = function(a, b, c) {
          b = b === void 0 ? null : b;
          var d2 = this, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y;
          return P(function(z) {
            switch (z.g) {
              case 1:
                if (d2.m == uq) throw new U(2, 7, 7e3);
                e = null;
                f = "";
                if (a instanceof mo) {
                  if (a.A) throw new U(2, 7, 7006);
                  e = a;
                  f = e.ed() || "";
                } else f = a || "";
                return G(z, iq(d2.ea, "load"), 2);
              case 2:
                d2.ea.release();
                if (!d2.h) throw new U(2, 7, 7002);
                if (!d2.V) {
                  z.B(3);
                  break;
                }
                d2.V = f;
                return G(z, d2.rc(false), 3);
              case 3:
                g = ++d2.Ye;
                h = function() {
                  return P(function(A) {
                    if (A.g == 1) return d2.Ye == g ? A.B(0) : e ? G(A, e.destroy(), 3) : A.B(3);
                    throw new U(2, 7, 7e3);
                  });
                };
                k2 = function(A, C) {
                  return P(function(D) {
                    switch (D.g) {
                      case 1:
                        return ta(D, 2), G(D, iq(d2.ea, C), 4);
                      case 4:
                        return G(D, h(), 5);
                      case 5:
                        return G(D, A(), 6);
                      case 6:
                        return G(D, h(), 7);
                      case 7:
                        e && d2.g && (e.g = d2.g);
                      case 2:
                        wa(D), d2.ea.release(), xa(D, 0);
                    }
                  });
                };
                sa(z, 5, 6);
                b == null && e && (b = e.getStartTime());
                d2.O = b;
                d2.aa = false;
                d2.dispatchEvent(tq("loading"));
                if (e) {
                  c = e.V;
                  z.B(8);
                  break;
                }
                if (c) {
                  z.B(8);
                  break;
                }
                return G(z, k2(function() {
                  return P(function(A) {
                    if (A.g == 1) return G(A, Eq(d2, f), 2);
                    c = A.h;
                    H(A);
                  });
                }, "guessMimeType_"), 8);
              case 8:
                l = !!e;
                if (e) {
                  po(e, d2);
                  d2.C = e.getStats();
                  z.B(11);
                  break;
                }
                return G(z, Fq(d2, f, b, c, true, d2.g), 12);
              case 12:
                (e = z.h) ? (e.F = false, po(e, d2), d2.C = e.getStats(), e.start(), e.C.catch(function() {
                })) : d2.C = new go();
              case 11:
                m = !e;
                n = Date.now() / 1e3;
                d2.C = e ? e.getStats() : new go();
                d2.V = f;
                d2.$ = c || null;
                Dq(d2);
                q = function() {
                  var A = d2.h ? d2.h.buffered : null;
                  return {
                    start: Hj(A) || 0,
                    end: Ij(A) || 0
                  };
                };
                d2.Ia = new om(q);
                d2.Ia.addEventListener("regionadd", function(A) {
                  Gq(d2, A.region, "metadataadded");
                });
                if (m) return G(z, k2(function() {
                  return P(function(A) {
                    return G(A, Hq(d2, c), 0);
                  });
                }, "initializeSrcEqualsDrmInner_"), 23);
                d2.Za = new om(q);
                return G(z, k2(function() {
                  return P(function(A) {
                    if (A.g == 1) return G(A, Promise.race([e.oa, e.C]), 2);
                    d2.Ec = e.I;
                    var C = e;
                    C.sa = true;
                    d2.I = C.l;
                    d2.i = e.qh();
                    H(A);
                  });
                }, "waitForFinish"), 15);
              case 15:
                if (d2.H) {
                  z.B(16);
                  break;
                }
                return G(z, k2(function() {
                  return P(function(A) {
                    return G(A, Cq(d2), 0);
                  });
                }, "initializeMediaSourceEngineInner_"), 16);
              case 16:
                return d2.i && d2.i.textStreams.length && (d2.u.enableTextDisplayer ? d2.u.enableTextDisplayer() : Wc("Text displayer w/ enableTextDisplayer", 'Text displayer should have a "enableTextDisplayer" method!')), G(z, k2(function() {
                  return P(function(A) {
                    return G(A, e.C, 0);
                  });
                }, "waitForFinish"), 18);
              case 18:
                d2.g = e.getConfiguration();
                d2.Pe = e.H;
                d2.I && d2.I.setMediaElement && d2.h && d2.I.setMediaElement(d2.h);
                d2.Le = ro(e);
                d2.Je = e.Oa;
                if (r2 = e.D) d2.M = r2;
                l && d2.h && d2.h.nodeName === "AUDIO" && (Iq(d2), d2.configure("manifest.disableVideo", true));
                if (e.i) {
                  z.B(19);
                  break;
                }
                return G(z, k2(function() {
                  return P(function(A) {
                    return G(A, xo(e, d2.h), 0);
                  });
                }, "drmEngine_.init"), 19);
              case 19:
                return d2.F = so(e), G(z, k2(function() {
                  return P(function(A) {
                    return G(A, d2.F.bc(d2.h), 0);
                  });
                }, "drmEngine_.attach"), 21);
              case 21:
                return !(u = e.G) || d2.Va && d2.Va == u || (d2.A = qo(e), d2.Va = e.G, typeof d2.A.setMediaElement != "function" && (Wc("AbrManager w/o setMediaElement", "Please use an AbrManager with setMediaElement function."), d2.A.setMediaElement = function() {
                }), typeof d2.A.setCmsdManager != "function" && (Wc("AbrManager w/o setCmsdManager", "Please use an AbrManager with setCmsdManager function."), d2.A.setCmsdManager = function() {
                }), typeof d2.A.trySuggestStreams != "function" && (Wc("AbrManager w/o trySuggestStreams", "Please use an AbrManager with trySuggestStreams function."), d2.A.trySuggestStreams = function() {
                })), w = to(e), v = e.u, G(z, k2(function() {
                  return P(function(A) {
                    return G(A, Jq(d2, n, v, w), 0);
                  });
                }, "loadInner_"), 22);
              case 22:
                oo(e);
                d2.$ && Sb().kg() && pf(d2.$) && Ck(d2.H, d2.V, d2.$);
                z.B(14);
                break;
              case 23:
                return G(z, k2(function() {
                  return P(function(A) {
                    return G(A, Kq(d2, n, c), 0);
                  });
                }, "srcEqualsInner_"), 14);
              case 14:
                d2.dispatchEvent(tq("loaded"));
              case 6:
                wa(z);
                if (!e) {
                  z.B(25);
                  break;
                }
                return G(z, e.destroy(), 25);
              case 25:
                d2.Oa = null;
                xa(z, 0);
                break;
              case 5:
                y = va(z);
                if (!y || y.code == 7e3) {
                  z.B(27);
                  break;
                }
                return G(z, d2.rc(false), 27);
              case 27:
                throw y;
            }
          });
        };
        function Iq(a) {
          for (var b = t2(a.i.variants), c = b.next(); !c.done; c = b.next()) c = c.value, c.video && (c.video.closeSegmentIndex(), c.video = null), c.bandwidth = c.audio && c.audio.bandwidth ? c.audio.bandwidth : 0;
          a.i.variants = a.i.variants.filter(function(d2) {
            return d2.audio;
          });
        }
        p.ym = function(a, b) {
          a = a === void 0 ? true : a;
          b = b === void 0 ? false : b;
          var c = this, d2;
          return P(function(e) {
            return e.g == 1 ? G(e, Lq(c), 2) : e.g != 3 ? (d2 = e.h, G(e, c.rc(a, b), 3)) : e.return(d2);
          });
        };
        p.Si = function(a, b) {
          a = a === void 0 ? false : a;
          b = b === void 0 ? false : b;
          var c = this, d2;
          return P(function(e) {
            return e.g == 1 ? G(e, Lq(c, b), 2) : e.g != 3 ? (d2 = e.h, G(e, c.detach(a), 3)) : e.return(d2);
          });
        };
        function Lq(a, b) {
          b = b === void 0 ? false : b;
          var c, d2, e;
          return P(function(f) {
            if (f.g == 1) {
              c = null;
              if (!(a.i && a.I && a.Ec && a.V && a.g)) return f.B(2);
              d2 = a.h.currentTime;
              a.U() && !b && (d2 = null);
              return G(f, Mq(a, a.V, d2, a.$, a.g, true, false, false), 3);
            }
            if (f.g != 2) {
              c = f.h;
              a.Te.push(c);
              a.I && a.I.setMediaElement && a.I.setMediaElement(null);
              if (e = a.l ? a.l.u : null) c.u = e;
              var g = c, h = a.I, k2 = a.Ec;
              g.h = a.i;
              g.l = h;
              g.I = k2;
              c.D = a.M;
              c.start();
              a.i = null;
              a.I = null;
              a.Ec = null;
              a.A = null;
              a.Va = null;
            }
            return f.return(c);
          });
        }
        p.preload = function(a, b, c, d2) {
          b = b === void 0 ? null : b;
          var e = this, f, g;
          return P(function(h) {
            if (h.g == 1) return f = kq(e), $n(f, d2 || e.g, kq(e)), G(h, Fq(e, a, b, c, false, f), 2);
            (g = h.h) ? g.start() : Bq(e, new U(2, 7, 7005));
            return h.return(g);
          });
        };
        p.Vg = function() {
          var a = this, b, c, d2, e;
          return P(function(f) {
            b = [];
            c = t2(a.Te);
            for (d2 = c.next(); !d2.done; d2 = c.next()) e = d2.value, e.A || b.push(e.destroy());
            a.Te = [];
            return G(f, Promise.all(b), 0);
          });
        };
        function Fq(a, b, c, d2, e, f) {
          e = e === void 0 ? false : e;
          var g, h, k2, l, m;
          return P(function(n) {
            if (n.g == 1) return d2 ? n.B(2) : G(n, Eq(a, b), 3);
            n.g != 2 && (d2 = n.h);
            if (g = Nq(a, d2)) return n.return(null);
            h = f || a.g;
            k2 = false;
            l = true;
            e && (a.A && a.Va == h.abrFactory && (l = false), a.h && a.h.nodeName === "AUDIO" && (k2 = true));
            m = Mq(a, b, c, d2 || null, h, !e, k2, l);
            m = e ? m.then(function(q) {
              q.F = false;
              return q;
            }) : m.then(function(q) {
              a.Te.push(q);
              return q;
            });
            return n.return(m);
          });
        }
        function Mq(a, b, c, d2, e, f, g, h) {
          f = f === void 0 ? true : f;
          g = g === void 0 ? false : g;
          h = h === void 0 ? true : h;
          var k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F;
          return P(function(B) {
            if (B.g == 1) {
              k2 = null;
              l = Hd(e);
              g && (l.manifest.disableVideo = true);
              m = function() {
                return k2.R && k2.A ? null : k2;
              };
              n = function() {
                return m() ? m().getConfiguration() : a.g;
              };
              if (a.ua.width != Infinity || a.ua.height != Infinity || a.g.ignoreHardwareResolution) return B.B(2);
              q = Sb();
              return G(B, q.tc(), 3);
            }
            B.g != 2 && (r2 = B.h, a.ua.width = r2.width, a.ua.height = r2.height);
            u = new yi(l, a.ua, null);
            w = {
              networkingEngine: a.J,
              filter: function(E) {
                var I, J;
                return P(function(K) {
                  if (K.g == 1) return G(K, zi(u, E), 2);
                  if (K.g != 4) {
                    I = K.h;
                    if (!I) return K.B(0);
                    J = tq("trackschanged");
                    return G(K, Promise.resolve(), 4);
                  }
                  k2.dispatchEvent(J);
                  H(K);
                });
              },
              makeTextStreamsForClosedCaptions: function(E) {
                return Oq(a, E);
              },
              onTimelineRegionAdded: function(E) {
                pm(k2.J, E);
              },
              onEvent: function(E) {
                return k2.dispatchEvent(E);
              },
              onError: function(E) {
                return k2.onError(E);
              },
              isLowLatencyMode: function() {
                return n().streaming.lowLatencyMode;
              },
              updateDuration: function() {
                a.l && k2.R && a.l.updateDuration();
              },
              newDrmInfo: function(E) {
                var I = k2.i, J = I ? I.g : null;
                J && I.C && Ci(u, J.keySystem, E);
              },
              onManifestUpdated: function() {
                var E = (/* @__PURE__ */ new Map()).set("isLive", a.U());
                k2.dispatchEvent(tq("manifestupdated", E));
                no(k2, false, function() {
                  if (a.D) a.D.onManifestUpdated(a.U());
                });
              },
              getBandwidthEstimate: function() {
                return a.A.getBandwidthEstimate();
              },
              onMetadata: function(E, I, J, K) {
                var L = E;
                if (E == "com.apple.hls.interstitial" && (L = "com.apple.quicktime.HLS", E = {
                  startTime: I,
                  endTime: J,
                  values: K
                }, a.D)) a.D.onHLSInterstitialMetadata(a, a.h, E);
                K = t2(K);
                E = K.next();
                for (var M = {}; !E.done; M = {
                  Rh: void 0
                }, E = K.next()) M.Rh = E.value, M.Rh.name != "ID" && no(k2, false, /* @__PURE__ */ function(N) {
                  return function() {
                    Pq(a, I, J, L, N.Rh);
                  };
                }(M));
              },
              disableStream: function(E) {
                return a.disableStream(E, a.g.streaming.maxDisabledTime);
              },
              addFont: function(E, I) {
                return a.addFont(E, I);
              }
            };
            v = new om(function() {
              return a.ya();
            });
            v.addEventListener("regionadd", function(E) {
              var I = E.region;
              Qq(a, "timelineregionadded", I, k2);
              no(k2, false, function() {
                a.D && (a.D.onDashTimedMetadata(I), a.D.onDASHInterstitialMetadata(a, a.h, I));
              });
            });
            y = null;
            l.streaming.observeQualityChanges && (y = new im(function() {
              return a.cc();
            }), y.addEventListener("qualitychange", function(E) {
              Rq(a, E.quality, E.position);
            }), y.addEventListener("audiotrackchange", function(E) {
              Rq(a, E.quality, E.position, true);
            }));
            z = true;
            A = {
              Bc: a.J,
              onError: function(E) {
                return k2.onError(E);
              },
              Qf: function(E) {
                no(k2, true, function() {
                  a.F && Sq(a, E);
                });
              },
              onExpirationUpdated: function(E, I) {
                var J = tq("expirationupdated");
                k2.dispatchEvent(J);
                if ((J = k2.l) && J.onExpirationUpdated) J.onExpirationUpdated(E, I);
              },
              onEvent: function(E) {
                k2.dispatchEvent(E);
                E.type == "drmsessionupdate" && z && (z = false, E = Date.now() / 1e3 - k2.Ia, (a.C || k2.getStats()).m = E, a.R && bd(a.R));
              }
            };
            C = mq(a, m);
            $g(a.J, C);
            D = function() {
              return a.Bd(A);
            };
            F = {
              config: l,
              Nl: w,
              Yl: v,
              Xl: y,
              Bd: D,
              Ml: u,
              networkingEngine: C,
              lk: f,
              kk: h
            };
            k2 = new mo(b, d2, c, F);
            h || uo(k2, a.A, a.Va);
            return B.return(k2);
          });
        }
        function Eq(a, b) {
          var c, d2, e;
          return P(function(f) {
            if (f.g == 1) return c = a.g.manifest.retryParameters, G(f, Jo(b, a.J, c), 2);
            d2 = f.h;
            d2 == "application/x-mpegurl" && (e = Sb(), e.Ga() === "WEBKIT" && (d2 = "application/vnd.apple.mpegurl"));
            return f.return(d2);
          });
        }
        function Nq(a, b) {
          if (!Ji(Sb())) return true;
          if (b) {
            if ((a.h || Ki()).canPlayType(b) == "") return false;
            if (!Ji(Sb()) || !Hi.has(b)) return true;
            if (pf(b)) return Sb().Ga() === "WEBKIT" && (a.g.drm.servers["com.apple.fps"] || a.g.drm.servers["com.apple.fps.1_0"]) ? a.g.streaming.useNativeHlsForFairPlay : a.g.streaming.preferNativeHls;
            if (b === "application/dash+xml" || b === "video/vnd.mpeg.dash.mpd") return a.g.streaming.preferNativeDash;
          }
          return false;
        }
        function Tq(a) {
          var b = a.g.textDisplayFactory;
          if (a.Di !== b) {
            var c = a.u;
            a.u = b();
            a.u.configure ? a.u.configure(a.g.textDisplayer) : Wc("Text displayer w/ configure", 'Text displayer should have a "configure" method!');
            a.u.setTextLanguage || Wc("Text displayer w/ setTextLanguage", 'Text displayer should have a "setTextLanguage" method!');
            c ? (a.u.setTextVisibility(c.isTextVisible()), c.destroy().catch(function() {
            })) : a.u.setTextVisibility(a.Z);
            a.H && il(a.H, a.u);
            a.Di = b;
            a.l && $m(a.l);
          } else a.u && a.u.configure && a.u.configure(a.g.textDisplayer);
        }
        function Cq(a) {
          var b, c, d2;
          return P(function(e) {
            if (e.g == 1) return Sb(), yq(a, "media-source"), a.g.mediaSource.useSourceElements && Qj(a.h), Tq(a), b = Uq(a.h, a.u, {
              Qk: function() {
                return a.keySystem();
              },
              onMetadata: function(f, g, h) {
                f = t2(f);
                for (var k2 = f.next(); !k2.done; k2 = f.next()) if (k2 = k2.value, k2.data && typeof k2.cueTime == "number" && k2.frames) {
                  var l = k2.cueTime + g, m = h;
                  m && l > m && (m = l);
                  for (var n = t2(k2.frames), q = n.next(); !q.done; q = n.next()) Pq(a, l, m, "org.id3", q.value);
                  if (a.D) a.D.onHlsTimedMetadata(k2, l);
                }
              },
              Sl: function(f) {
                a.Za && pm(a.Za, {
                  schemeIdUri: f.schemeIdUri,
                  startTime: f.startTime,
                  endTime: f.endTime,
                  id: String(f.id),
                  emsg: f
                });
              },
              onEvent: function(f) {
                return a.dispatchEvent(f);
              },
              Ul: function() {
                a.I && a.I.update && a.I.update();
              }
            }, a.R, a.g.mediaSource), c = a.g.manifest, d2 = c.segmentRelativeVttTiming, b.Ia = d2, G(e, b.K, 2);
            a.H = b;
            H(e);
          });
        }
        function Vq(a, b, c) {
          function d2() {
            return Wq(a);
          }
          a.j.o(b, "playing", d2);
          a.j.o(b, "pause", d2);
          a.j.o(b, "ended", d2);
          a.j.o(b, "ratechange", function() {
            var f = a.h.playbackRate;
            f != 0 && (a.K && (a.K.set(f), a.m == Xq && a.A.playbackRateChanged(f), Yq(a, f)), f = tq("ratechange"), a.dispatchEvent(f));
          });
          b.remote && (a.j.o(b.remote, "connect", function() {
            a.l && b.remote.state == "connected" && Zq(a);
            $q(a);
          }), a.j.o(b.remote, "connecting", function() {
            return $q(a);
          }), a.j.o(b.remote, "disconnect", function() {
            return P(function(f) {
              if (f.g == 1) return a.l && b.remote.state == "disconnected" ? G(f, nn(a.l), 3) : f.B(2);
              f.g != 2 && Zq(a);
              $q(a);
              H(f);
            });
          }));
          b.audioTracks && (a.j.o(b.audioTracks, "addtrack", function() {
            return $q(a);
          }), a.j.o(b.audioTracks, "removetrack", function() {
            return $q(a);
          }), a.j.o(b.audioTracks, "change", function() {
            return $q(a);
          }));
          b.videoTracks && (a.j.o(b.videoTracks, "addtrack", function() {
            return $q(a);
          }), a.j.o(b.videoTracks, "removetrack", function() {
            return $q(a);
          }), a.j.o(b.videoTracks, "change", function() {
            return $q(a);
          }));
          if (b.textTracks) {
            var e = function() {
              a.m === ar && a.u instanceof Wo && Zq(a);
              $q(a);
            };
            a.j.o(b.textTracks, "addtrack", function(f) {
              if (f.track) switch (f = f.track, f.kind) {
                case "metadata":
                  br(a, f);
                  break;
                case "chapters":
                  cr(a, f);
                  break;
                default:
                  e();
              }
            });
            a.j.o(b.textTracks, "removetrack", e);
            a.j.o(b.textTracks, "change", e);
            a.g.streaming.crossBoundaryStrategy !== "keep" && (a.j.o(b, "waiting", function() {
              a.l && fn(a.l);
            }), a.j.o(b, "timeupdate", function() {
              a.l && fn(a.l);
            }));
          }
          b.preload != "none" && a.j.qa(b, "loadedmetadata", function() {
            a.C.G = Date.now() / 1e3 - c;
          });
        }
        function Jq(a, b, c, d2) {
          var e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N, O;
          return P(function(Q) {
            switch (Q.g) {
              case 1:
                yq(a, "load");
                e = a.h;
                a.K = new em({
                  vf: function() {
                    return e.playbackRate;
                  },
                  fd: function() {
                    return e.defaultPlaybackRate;
                  },
                  gi: function(R) {
                    e.playbackRate = R;
                  },
                  oj: function(R) {
                    e.currentTime += R;
                  }
                });
                Vq(a, e, b);
                "onchange" in window7.screen && a.j.o(window7.screen, "change", function() {
                  if (a.M.getConfiguration) {
                    var R = a.M.getConfiguration();
                    R.Qc == "AUTO" ? dr(a) : a.g.preferredVideoHdrLevel == "AUTO" && a.g.abr.enabled && (R.Qc = "AUTO", a.M.configure(R), dr(a));
                  }
                });
                f = false;
                g = t2(a.i.variants);
                for (h = g.next(); !h.done; h = g.next()) k2 = h.value, (l = k2.video && k2.video.dependencyStream) && (f = cd(l));
                sq(a, a.g, f);
                a.Sd = a.g.preferredTextLanguage;
                a.Zd = a.g.preferredTextRole;
                a.Oe = a.g.preferForcedSubs;
                er(a.i.presentationTimeline, a.g.playRangeStart, a.g.playRangeEnd);
                a.A.init(function(R, V, Ba) {
                  a.i && a.l && R != a.l.u && fr(a, R, true, V === void 0 ? false : V, Ba === void 0 ? 0 : Ba);
                });
                a.A.setMediaElement(e);
                a.A.setCmsdManager(a.sa);
                a.l = gr(a);
                a.l.configure(a.g.streaming);
                a.m = Xq;
                a.dispatchEvent(tq("streaming"));
                m = c;
              case 2:
                (q = a.l.u) || m || (m = dr(a) ? a.A.chooseVariant() : null);
                r2 = [];
                n = q || m;
                u = t2([n.video, n.audio]);
                for (w = u.next(); !w.done; w = u.next()) (v = w.value) && !v.segmentIndex && (r2.push(v.createSegmentIndex()), v.dependencyStream && r2.push(v.dependencyStream.createSegmentIndex()));
                if (!(r2.length > 0)) {
                  Q.B(4);
                  break;
                }
                return G(Q, Promise.all(r2), 4);
              case 4:
                if (!n || n.disabledUntilTime != 0) {
                  Q.B(2);
                  break;
                }
                if (a.I && a.I.onInitialVariantChosen) a.I.onInitialVariantChosen(n);
                a.i.isLowLatency && (a.g.streaming.lowLatencyMode ? a.configure(a.Dg) : bb("Low-latency live stream detected, but low-latency streaming mode is not enabled in Shaka Player. Set streaming.lowLatencyMode configuration to true, and see https://bit.ly/3clctcj for details."));
                a.L && (op(a.L, a.i.isLowLatency && a.g.streaming.lowLatencyMode), tp(a.L, b * 1e3));
                er(a.i.presentationTimeline, a.g.playRangeStart, a.g.playRangeEnd);
                Qm(a.l, a.g.playRangeStart, a.g.playRangeEnd);
                a.aa = true;
                a.dispatchEvent(tq("canupdatestarttime"));
                y = function(R) {
                  a.G = hr(a, R);
                  a.Ob = ir(a, R);
                  jr(a, e, false);
                };
                a.g.streaming.startAtSegmentBoundary || (z = a.O, z == null && a.i.startTime && (z = a.i.startTime), y(z));
                if (q) {
                  Q.B(7);
                  break;
                }
                if (!a.g.streaming.startAtSegmentBoundary) {
                  Q.B(8);
                  break;
                }
                A = a.i.presentationTimeline;
                a.O instanceof Date && (D = A.m || A.i, F = a.O.getTime() / 1e3 - D, F != null && (C = F));
                C == null && (C = typeof a.O === "number" ? a.O : a.h.currentTime);
                a.O == null && a.i.startTime && (C = a.i.startTime);
                B = A.ec();
                E = A.Mb();
                C < B ? C = B : C > E && (C = E);
                return G(Q, kr(m, C), 9);
              case 9:
                I = Q.h, y(I);
              case 8:
                fr(a, m, true, false, 0);
              case 7:
                return a.G.ready(), J = a.vc().find(function(R) {
                  return R.active;
                }), J || ((K = mg(a.i.textStreams, a.Sd, a.Zd, a.Oe)[0] || null) && fo(a.C.h, K, true), m && (K ? (qg(m.audio, K, a.g) && (a.Z = true), a.Z && a.u.setTextVisibility(true)) : (a.Z = false, a.u.setTextVisibility(false)), lr(a)), K && (a.g.streaming.alwaysStreamText || a.ld()) && (Zm(a.l, K), mr(a))), G(Q, a.l.start(d2), 10);
              case 10:
                a.g.abr.enabled && (a.A.enable(), nr(a));
                $q(a);
                dr(a);
                a.i.variants.some(function(R) {
                  return R.primary;
                });
                if ((L = a.U()) && (a.g.streaming.liveSync && a.g.streaming.liveSync.enabled || a.i.serviceDescription || a.g.streaming.liveSync.panicMode) || a.g.streaming.vodDynamicPlaybackRate) M = function() {
                  return or(a);
                }, a.j.o(e, "timeupdate", M);
                L || (N = function() {
                  return pr(a);
                }, a.j.o(e, "timeupdate", N), pr(a), a.i.nextUrl && (a.g.streaming.preloadNextUrlWindow > 0 && (O = function() {
                  var R;
                  return P(function(V) {
                    if (V.g == 1) {
                      R = a.ya().end - a.h.currentTime;
                      if (isNaN(R) || !(R <= a.g.streaming.preloadNextUrlWindow)) return V.B(0);
                      a.j.Ea(e, "timeupdate", O);
                      return G(V, a.preload(a.i.nextUrl), 4);
                    }
                    a.Oa = V.h;
                    H(V);
                  });
                }, a.j.o(e, "timeupdate", O)), a.j.o(e, "ended", function() {
                  a.load(a.Oa || a.i.nextUrl);
                })));
                if (a.D) a.D.onManifestUpdated(L);
                H(Q);
            }
          });
        }
        function Hq(a, b) {
          var c, d2, e;
          return P(function(f) {
            return f.g == 1 ? (c = Date.now() / 1e3, d2 = true, a.F = a.Bd({
              Bc: a.J,
              onError: function(g) {
                Bq(a, g);
              },
              Qf: function() {
              },
              onExpirationUpdated: function() {
                var g = tq("expirationupdated");
                a.dispatchEvent(g);
              },
              onEvent: function(g) {
                a.dispatchEvent(g);
                g.type == "drmsessionupdate" && d2 && (d2 = false, a.C.m = Date.now() / 1e3 - c);
              }
            }), a.F.configure(a.g.drm), e = rg([b]), a.F.O = true, G(f, Jh(a.F, [e], []), 2)) : G(f, a.F.bc(a.h), 0);
          });
        }
        function Kq(a, b, c) {
          var d2, e, f, g, h, k2, l, m, n, q, r2, u;
          return P(function(w) {
            switch (w.g) {
              case 1:
                yq(a, "src-equals");
                d2 = a.h;
                a.G = new Rl(d2);
                e = false;
                a.Ne.push(function() {
                  e = true;
                });
                a.dispatchEvent(tq("canupdatestarttime"));
                a.O != null && a.G.Ag(a.O);
                a.Ob = qr(a, a.O || 0);
                a.K = new em({
                  vf: function() {
                    return d2.playbackRate;
                  },
                  fd: function() {
                    return d2.defaultPlaybackRate;
                  },
                  gi: function(v) {
                    d2.playbackRate = v;
                  },
                  oj: function(v) {
                    d2.currentTime += v;
                  }
                });
                jr(a, d2, true);
                d2.textTracks && (Tq(a), f = function(v) {
                  if (!(a.u instanceof Wo)) {
                    var y = rr(a).find(function(z) {
                      return z.mode !== "disabled";
                    });
                    y && (y.mode = v ? "showing" : "hidden");
                    a.u instanceof Yo && (y = sr(a)) && (y.mode = !v && a.u.isTextVisible() ? "showing" : "hidden");
                  }
                }, a.j.o(d2, "enterpictureinpicture", function() {
                  return f(true);
                }), a.j.o(d2, "leavepictureinpicture", function() {
                  return f(false);
                }), d2.remote ? (a.j.o(d2.remote, "connect", function() {
                  return f(false);
                }), a.j.o(d2.remote, "connecting", function() {
                  return f(false);
                }), a.j.o(d2.remote, "disconnect", function() {
                  return f(false);
                })) : "webkitCurrentPlaybackTargetIsWireless" in d2 && a.j.o(d2, "webkitcurrentplaybacktargetiswirelesschanged", function() {
                  return f(false);
                }), g = d2, g.webkitSupportsFullscreen && a.j.o(g, "webkitpresentationmodechanged", function() {
                  return f(g.webkitPresentationMode !== "inline");
                }));
                Vq(a, d2, b);
                h = vp(a.L, a.V, c);
                !h.includes("#t=") && (a.g.playRangeStart > 0 || isFinite(a.g.playRangeEnd)) && (h += "#t=", a.g.playRangeStart > 0 && (h += a.g.playRangeStart), isFinite(a.g.playRangeEnd) && (h += "," + a.g.playRangeEnd));
                if (!a.H) {
                  w.B(2);
                  break;
                }
                return G(w, a.H.destroy(), 3);
              case 3:
                a.H = null;
              case 2:
                return Qj(d2), d2.src = h, k2 = Sb(), k2.Ka() == "TV" && d2.load(), d2.preload != "none" && !d2.autoplay && pf(c) && k2.Ga() === "WEBKIT" && d2.load(), a.m = ar, a.dispatchEvent(tq("streaming")), l = new Mg(), Il(d2, HTMLMediaElement.HAVE_METADATA, a.j, function() {
                  a.G.ready();
                  a.$ && pf(a.$) || l.resolve();
                }), m = function() {
                  return new Promise(function(v) {
                    var y = new Cf(v);
                    a.j.o(d2.textTracks, "change", function() {
                      return y.Y(0.5);
                    });
                    y.Y(0.5);
                  });
                }, Il(d2, HTMLMediaElement.HAVE_CURRENT_DATA, a.j, function() {
                  var v, y, z, A, C;
                  return P(function(D) {
                    if (D.g == 1) return G(D, m(), 2);
                    if (e) return D.return();
                    tr(a);
                    v = rr(a);
                    v.some(function(F) {
                      return F.mode === "showing";
                    }) && (a.Z = true, a.u.setTextVisibility(true));
                    if (!(a.u instanceof Wo)) for (v.length && (a.u.enableTextDisplayer ? a.u.enableTextDisplayer() : Wc("Text displayer w/ enableTextDisplayer", 'Text displayer should have a "enableTextDisplayer" method')), y = false, z = t2(v), A = z.next(); !A.done; A = z.next()) C = A.value, C.mode !== "disabled" && (y ? (C.mode = "disabled", bb("Found more than one enabled text track, disabling it", C)) : (ur(a, C), y = true));
                    vr(a);
                    a.$ && pf(a.$) && l.resolve();
                    H(D);
                  });
                }), d2.error ? l.reject(Aq(a)) : d2.preload == "none" && (bb('With <video preload="none">, the browser will not load anything until play() is called. We are unable to measure load latency in a meaningful way, and we cannot provide track info yet. Please do not use preload="none" with Shaka Player.'), l.resolve()), a.j.qa(d2, "error", function() {
                  l.reject(Aq(a));
                }), G(w, Gf(a.g.streaming.loadTimeout, l), 4);
              case 4:
                if ((n = a.U()) && (a.g.streaming.liveSync && a.g.streaming.liveSync.enabled || a.g.streaming.liveSync.panicMode) || a.g.streaming.vodDynamicPlaybackRate) q = function() {
                  return or(a);
                }, a.j.o(d2, "timeupdate", q);
                n || (r2 = function() {
                  return pr(a);
                }, a.j.o(d2, "timeupdate", r2), pr(a));
                a.D && (a.D.onManifestUpdated(n), n && (u = a.ya().end, a.j.o(d2, "progress", function() {
                  var v = a.ya().end;
                  u != v && (a.D.onManifestUpdated(a.U()), u = v);
                })));
                a.aa = true;
                H(w);
            }
          });
        }
        function tr(a) {
          var b = a.g.preferredAudioLanguage;
          b != "" && a.Fj(b, a.g.preferredVariantRole);
        }
        function vr(a) {
          var b = a.g.preferredTextLanguage;
          b != "" && a.ai(b, a.g.preferredTextRole, a.g.preferForcedSubs);
        }
        function br(a, b) {
          if (b.kind == "metadata") {
            b.mode = "hidden";
            a.j.o(b, "cuechange", function() {
              if (b.activeCues) {
                for (var d2 = t2(b.activeCues), e = d2.next(); !e.done; e = d2.next()) if (e = e.value, Pq(a, e.startTime, e.endTime, e.type, e.value), a.D) a.D.onCueMetadataChange(e.value);
              }
              if (b.cues) {
                d2 = [];
                e = t2(b.cues);
                for (var f = e.next(), g = {}; !f.done; g = {
                  Jc: void 0
                }, f = e.next()) g.Jc = f.value, g.Jc.type == "com.apple.quicktime.HLS" && g.Jc.startTime != null && (f = d2.find(/* @__PURE__ */ function(h) {
                  return function(k2) {
                    return k2.startTime == h.Jc.startTime && k2.endTime == h.Jc.endTime;
                  };
                }(g)), f || (f = {
                  startTime: g.Jc.startTime,
                  endTime: g.Jc.endTime,
                  values: []
                }, d2.push(f)), f.values.push(g.Jc.value));
                d2 = t2(d2);
                for (e = d2.next(); !e.done; e = d2.next()) e = e.value, e.values.some(function(h) {
                  return h.key == "X-ASSET-URI" || h.key == "X-ASSET-LIST";
                }) && a.D && (e.values.push({
                  key: "CUE",
                  description: "",
                  data: e.startTime != 0 || a.U() ? "ONCE" : "ONCE,PRE",
                  mimeType: null,
                  pictureType: null
                }), a.D.onHLSInterstitialMetadata(a, a.h, e));
              }
            });
            var c = new Cf(function() {
              var d2 = wr(a);
              d2 = t2(d2);
              for (var e = d2.next(); !e.done; e = d2.next()) e.value.mode = "hidden";
            }).La().Y(0.5);
            a.Ne.push(function() {
              c.stop();
            });
          }
        }
        function Gq(a, b, c) {
          b = (/* @__PURE__ */ new Map()).set("startTime", b.startTime).set("endTime", b.endTime).set("metadataType", b.schemeIdUri).set("payload", b.payload);
          a.dispatchEvent(tq(c, b));
        }
        function Pq(a, b, c, d2, e) {
          a.Ia && (b = {
            schemeIdUri: d2,
            startTime: b,
            endTime: c || Infinity,
            id: "",
            payload: e
          }, b.id = JSON.stringify(b), pm(a.Ia, b));
        }
        function cr(a, b) {
          if (b && b.kind == "chapters") {
            b.mode = "hidden";
            var c = new Cf(function() {
              b.mode = "hidden";
            }).La().Y(0.5);
            a.Ne.push(function() {
              c.stop();
            });
          }
        }
        p.bm = function() {
          for (var a = this.ea; a.g; ) a.release();
        };
        p.Bd = function(a) {
          return new Ch(a);
        };
        function mq(a, b) {
          function c(f) {
            b() ? b().dispatchEvent(f) : a.dispatchEvent(f);
          }
          function d2(f) {
            b() ? no(b(), true, f) : f();
          }
          b || (b = function() {
            return null;
          });
          var e = new Wg(function(f, g, h, k2, l) {
            var m = b() ? b().j : a.A;
            m && m.segmentDownloaded(f, g, h, k2, l);
          }, function(f, g, h) {
            g = (/* @__PURE__ */ new Map()).set("headers", f).set("request", g).set("requestType", h);
            c(tq("downloadheadersreceived", g));
            d2(function() {
              if (a.sa) {
                var k2 = a.sa;
                if (k2.h.enabled) {
                  var l = f["cmsd-static"];
                  if (l) try {
                    var m = /* @__PURE__ */ new Map(), n = l.split(",");
                    for (l = 0; l < n.length; l++) {
                      var q = n[l].split("=");
                      m.set(q[0], gq(q[1]));
                    }
                  } catch (y) {
                  }
                  if (m = f["cmsd-dynamic"]) {
                    a: {
                      try {
                        var r2 = /* @__PURE__ */ new Map(), u = m.split(";");
                        for (m = 1; m < u.length; m++) {
                          var w = u[m].split("=");
                          r2.set(w[0], gq(w[1]));
                        }
                        var v = r2;
                        break a;
                      } catch (y) {
                        v = null;
                        break a;
                      }
                      v = void 0;
                    }
                    v && (k2.g = v);
                  }
                }
              }
            });
          }, function(f, g) {
            f = (/* @__PURE__ */ new Map()).set("request", f).set("response", g);
            c(tq("downloadcompleted", f));
          }, function(f, g, h, k2) {
            f = (/* @__PURE__ */ new Map()).set("request", f).set("error", g).set("httpResponseCode", h).set("aborted", k2);
            c(tq("downloadfailed", f));
          }, function(f, g, h) {
            d2(function() {
              var k2 = a.L, l = h;
              l = l === void 0 ? {} : l;
              if (k2.g.enabled) if (g.method === "HEAD") Cp(k2, g);
              else switch (f) {
                case 0:
                  try {
                    if (k2.g.enabled) {
                      if (l.type) {
                        a: {
                          switch (l.type) {
                            case 4:
                              var m = k2.l ? qp : pp;
                              break a;
                            case 3:
                            case 2:
                              m = k2.l ? sp : rp;
                              break a;
                            case 5:
                              m = "s";
                              break a;
                          }
                          m = void 0;
                        }
                        k2.i = m;
                      }
                      Cp(k2, g, {
                        ot: zp,
                        su: !k2.A
                      });
                    }
                  } catch (O) {
                    cb("CMCD_MANIFEST_ERROR", "Could not generate manifest CMCD data.", O);
                  }
                  break;
                case gh:
                  try {
                    if (k2.g.enabled) {
                      var n = g.uris[0], q = l.segment;
                      m = 0;
                      q && (m = q.endTime - q.startTime);
                      var r2 = {
                        d: m * 1e3,
                        st: k2.h.U() ? "l" : "v"
                      };
                      r2.ot = Gp(l);
                      var u = r2.ot === Ip || r2.ot === xp || r2.ot === yp || r2.ot === Jp, w = l.stream;
                      if (w) {
                        var v = k2.h.Ya();
                        if (u && (r2.bl = Lp(k2, w.type), r2.ot !== Jp)) {
                          var y = Mp(k2, w.type);
                          r2.dl = v ? y / Math.abs(v) : y;
                        }
                        w.bandwidth && (r2.br = w.bandwidth / 1e3);
                        if (w.segmentIndex && q) {
                          var z = w.segmentIndex.dc(q.endTime, true, v < 0);
                          if (z) {
                            var A = z.next().value;
                            if (A && A != q) {
                              if (n && !wd(q.T(), A.T())) {
                                var C = A.T()[0], D = new URL(C), F = new URL(n);
                                if (D.origin !== F.origin) var B = C;
                                else {
                                  for (var E = D.pathname.split("/").slice(1), I = F.pathname.split("/").slice(1, -1); E[0] === I[0]; ) E.shift(), I.shift();
                                  for (; I.length; ) I.shift(), E.unshift("..");
                                  B = E.join("/");
                                }
                                r2.nor = B;
                              }
                              if ((A.startByte || A.endByte) && (q.startByte != A.startByte || q.endByte != A.endByte)) {
                                var J = A.startByte + "-";
                                A.endByte && (J += A.endByte);
                                r2.nrr = J;
                              }
                            }
                          }
                          var K = k2.h.Ya() || 1, L = Mp(k2, w.type) || 500, M = w.bandwidth;
                          var N = M ? M * (q.endTime - q.startTime) / 1e3 / (L / K / 1e3) * k2.g.rtpSafetyFactor : NaN;
                          isNaN(N) || (r2.rtp = N);
                        }
                      }
                      u && r2.ot !== Jp && (r2.tb = aq(k2, r2.ot) / 1e3);
                      Cp(k2, g, r2);
                    }
                  } catch (O) {
                    cb("CMCD_SEGMENT_ERROR", "Could not generate segment CMCD data.", O);
                  }
                  break;
                case 2:
                case 5:
                case 6:
                  Cp(k2, g, {
                    ot: "k"
                  });
                  break;
                case 4:
                  Cp(k2, g, {
                    ot: "o"
                  });
              }
            });
          }, function(f, g, h, k2) {
            (f = b() ? b().l : a.I) && f.banLocation && f.banLocation(k2);
          }, function(f, g) {
            if (g.data) {
              g = g.data.byteLength;
              var h = b() ? b().getStats() : a.C;
              h && (ko(h, g), f === 0 && (h.ij = g));
            }
          });
          e.configure(a.g.networking);
          return e;
        }
        function hr(a, b) {
          return new Ul(a.h, a.i, a.g.streaming, b, function() {
            a.Ob && hm(a.Ob, !a.G.Bi());
            a.l && a.l.qd();
            a.P && xr(a);
          }, function(c) {
            return a.dispatchEvent(c);
          });
        }
        function ir(a, b) {
          var c = a.U() || typeof b === "number" && b > 0;
          b = new Eo(a.Le, c);
          b.addEventListener("enter", function(f) {
            Qq(a, "timelineregionenter", f.region);
          });
          b.addEventListener("exit", function(f) {
            Qq(a, "timelineregionexit", f.region);
          });
          b.addEventListener("skip", function(f) {
            var g = f.region;
            f.seeking || (Qq(a, "timelineregionenter", g), Qq(a, "timelineregionexit", g));
          });
          var d2 = new Eo(a.Ia, c);
          d2.addEventListener("enter", function(f) {
            Gq(a, f.region, "metadata");
          });
          c = new Eo(a.Za, c);
          c.addEventListener("enter", function(f) {
            f = (/* @__PURE__ */ new Map()).set("detail", f.region.emsg);
            a.dispatchEvent(tq("emsg", f));
          });
          var e = new gm(a.h);
          e.g.add(b);
          e.g.add(d2);
          e.g.add(c);
          a.Je && e.g.add(a.Je);
          return e;
        }
        function qr(a, b) {
          b = new Eo(a.Ia, b instanceof Date || b > 0);
          b.addEventListener("enter", function(d2) {
            Gq(a, d2.region, "metadata");
          });
          var c = new gm(a.h);
          c.g.add(b);
          return c;
        }
        function jr(a, b, c) {
          a.P = new vi();
          a.P.g = xi;
          yr(a);
          Dq(a);
          a.Ma = new Cf(function() {
            xr(a);
          });
          a.g.streaming.rebufferingGoal && a.Ma.za(0.25);
          a.j.o(b, "waiting", function() {
            return xr(a);
          });
          a.j.o(b, "canplaythrough", function() {
            return xr(a);
          });
          a.j.o(b, "playing", function() {
            return xr(a);
          });
          a.j.o(b, "seeked", function() {
            return xr(a);
          });
          c && (a.j.o(b, "stalled", function() {
            return xr(a);
          }), a.j.o(b, "progress", function() {
            return xr(a);
          }), a.j.o(b, "timeupdate", function() {
            return xr(a);
          }));
        }
        function yr(a) {
          var b = a.g.streaming.rebufferingGoal;
          a.P.i.set(wi, Math.min(0.5, b / 2)).set(xi, b);
        }
        function xr(a) {
          var b = a.H ? Fk(a.H) : false, c = a.isEnded() || b || a.G.ej(), d2 = Kj(a.h.buffered, a.h.currentTime);
          b = a.P;
          var e = b.i.get(b.g), f = b.g;
          c = c || d2 >= e && d2 > 0 ? wi : xi;
          b.g = c;
          (f = f != c) && c === wi && (b.h = Date.now());
          f && Dq(a);
        }
        function Uq(a, b, c, d2, e) {
          return new yk(a, b, c, e, d2);
        }
        function lq(a) {
          return new lp({
            getBandwidthEstimate: function() {
              return a.A ? a.A.getBandwidthEstimate() : NaN;
            },
            cc: function() {
              return a.cc();
            },
            getCurrentTime: function() {
              return a.h ? a.h.currentTime : 0;
            },
            Ya: function() {
              return a.Ya();
            },
            Lb: function() {
              return a.Lb();
            },
            rb: function() {
              return a.rb();
            },
            U: function() {
              return a.U();
            },
            uf: function() {
              return a.uf();
            }
          }, a.g.cmcd);
        }
        function gr(a) {
          return new Km(a.i, {
            gd: function() {
              return a.G ? a.G.Xe() : 0;
            },
            getBandwidthEstimate: function() {
              return a.A.getBandwidthEstimate();
            },
            Ya: function() {
              return a.Ya();
            },
            video: a.h,
            ia: a.H,
            Bc: a.J,
            onError: function(b) {
              return Bq(a, b);
            },
            onEvent: function(b) {
              return a.dispatchEvent(b);
            },
            Rf: function(b, c, d2) {
              var e = b.startTime;
              b = b.endTime;
              c = c.type;
              if (c != tc) {
                if (a.G) {
                  a.G.qj();
                  var f = Mk(a.H, c);
                  !a.U() && a.h.paused && !a.h.seeking && f != null && f > 0 && a.G.Xe() < f && a.G.Ag(f);
                }
                xr(a);
              }
              d2 = (/* @__PURE__ */ new Map()).set("start", e).set("end", b).set("contentType", c).set("isMuxed", d2);
              a.dispatchEvent(tq("segmentappended", d2));
            },
            Tl: function(b, c) {
              (c = c.Kd) && a.Je && km(a.Je, c, b);
            },
            Ji: function(b, c) {
              var d2 = a.F;
              if (d2.h.parseInbandPsshEnabled && !d2.L && ["audio", "video"].includes(b)) {
                b = new Ah(Lb(c));
                c = 0;
                for (var e = t2(b.data), f = e.next(); !f.done; f = e.next()) c += f.value.length;
                if (c == 0) d2 = Promise.resolve();
                else {
                  c = new Uint8Array(c);
                  e = 0;
                  b = t2(b.data);
                  for (f = b.next(); !f.done; f = b.next()) f = f.value, c.set(f, e), e += f.length;
                  Sh(d2, "cenc", c);
                  d2 = d2.m;
                }
              } else d2 = Promise.resolve();
              return d2;
            },
            disableStream: function(b, c) {
              return a.disableStream(b, c);
            }
          });
        }
        p.configure = function(a, b) {
          arguments.length == 2 && typeof a == "string" && (a = Bn(a, b));
          a.streaming && "forceTransmuxTS" in a.streaming && (Wc("streaming.forceTransmuxTS configuration", "Please Use mediaSource.forceTransmux instead."), a.mediaSource = a.mediaSource || {}, a.mediaSource.mediaSource = a.streaming.forceTransmuxTS, delete a.streaming.forceTransmuxTS);
          a.streaming && "forceTransmux" in a.streaming && (Wc("streaming.forceTransmux configuration", "Please Use mediaSource.forceTransmux instead."), a.mediaSource = a.mediaSource || {}, a.mediaSource.mediaSource = a.streaming.forceTransmux, delete a.streaming.forceTransmux);
          if (a.streaming && "useNativeHlsOnSafari" in a.streaming) {
            Wc("streaming.useNativeHlsOnSafari configuration", "Please Use streaming.useNativeHlsForFairPlay or streaming.preferNativeHls instead.");
            var c = Sb();
            a.streaming.preferNativeHls = a.streaming.useNativeHlsOnSafari && c.Ga() === "WEBKIT";
            delete a.streaming.useNativeHlsOnSafari;
          }
          a.streaming && typeof a.streaming.liveSync == "boolean" && (Wc("streaming.liveSync", "Please Use streaming.liveSync.enabled instead."), c = a.streaming.liveSync, a.streaming.liveSync = {}, a.streaming.liveSync.enabled = c);
          if (a.streaming && !(a.streaming.liveSync && "targetLatency" in a.streaming.liveSync) && ("liveSyncMinLatency" in a.streaming || "liveSyncMaxLatency" in a.streaming)) {
            c = a.streaming.liveSyncMinLatency || 0;
            var d2 = Math.abs((a.streaming.liveSyncMaxLatency || 1) - c) / 2;
            a.streaming.liveSync = a.streaming.liveSync || {};
            a.streaming.liveSync.targetLatency = c + d2;
            a.streaming.liveSync.targetLatencyTolerance = d2;
          }
          a.streaming && "liveSyncMaxLatency" in a.streaming && (Wc("streaming.liveSyncMaxLatency", "Please Use streaming.liveSync.targetLatency and streaming.liveSync.targetLatencyTolerance instead. Or, set the values in your DASH manifest"), delete a.streaming.liveSyncMaxLatency);
          a.streaming && "liveSyncMinLatency" in a.streaming && (Wc("streaming.liveSyncMinLatency", "Please Use streaming.liveSync.targetLatency and streaming.liveSync.targetLatencyTolerance instead. Or, set the values in your DASH manifest"), delete a.streaming.liveSyncMinLatency);
          a.streaming && "liveSyncTargetLatency" in a.streaming && (Wc("streaming.liveSyncTargetLatency", "Please Use streaming.liveSync.targetLatency instead."), a.streaming.liveSync = a.streaming.liveSync || {}, a.streaming.liveSync.targetLatency = a.streaming.liveSyncTargetLatency, delete a.streaming.liveSyncTargetLatency);
          a.streaming && "liveSyncTargetLatencyTolerance" in a.streaming && (Wc("streaming.liveSyncTargetLatencyTolerance", "Please Use streaming.liveSync.targetLatencyTolerance instead."), a.streaming.liveSync = a.streaming.liveSync || {}, a.streaming.liveSync.targetLatencyTolerance = a.streaming.liveSyncTargetLatencyTolerance, delete a.streaming.liveSyncTargetLatencyTolerance);
          a.streaming && "liveSyncPlaybackRate" in a.streaming && (Wc("streaming.liveSyncPlaybackRate", "Please Use streaming.liveSync.maxPlaybackRate instead."), a.streaming.liveSync = a.streaming.liveSync || {}, a.streaming.liveSync.maxPlaybackRate = a.streaming.liveSyncPlaybackRate, delete a.streaming.liveSyncPlaybackRate);
          a.streaming && "liveSyncMinPlaybackRate" in a.streaming && (Wc("streaming.liveSyncMinPlaybackRate", "Please Use streaming.liveSync.minPlaybackRate instead."), a.streaming.liveSync = a.streaming.liveSync || {}, a.streaming.liveSync.minPlaybackRate = a.streaming.liveSyncMinPlaybackRate, delete a.streaming.liveSyncMinPlaybackRate);
          a.streaming && "liveSyncPanicMode" in a.streaming && (Wc("streaming.liveSyncPanicMode", "Please Use streaming.liveSync.panicMode instead."), a.streaming.liveSync = a.streaming.liveSync || {}, a.streaming.liveSync.panicMode = a.streaming.liveSyncPanicMode, delete a.streaming.liveSyncPanicMode);
          a.streaming && "liveSyncPanicThreshold" in a.streaming && (Wc("streaming.liveSyncPanicThreshold", "Please Use streaming.liveSync.panicThreshold instead."), a.streaming.liveSync = a.streaming.liveSync || {}, a.streaming.liveSync.panicThreshold = a.streaming.liveSyncPanicThreshold, delete a.streaming.liveSyncPanicThreshold);
          if (a.mediaSource && "sourceBufferExtraFeatures" in a.mediaSource) {
            Wc("mediaSource.sourceBufferExtraFeatures configuration", "Please Use mediaSource.addExtraFeaturesToSourceBuffer() instead.");
            var e = a.mediaSource.sourceBufferExtraFeatures;
            a.mediaSource.addExtraFeaturesToSourceBuffer = function() {
              return e;
            };
            delete a.mediaSource.sourceBufferExtraFeatures;
          }
          a.manifest && a.manifest.hls && "useSafariBehaviorForLive" in a.manifest.hls && (Wc("manifest.hls.useSafariBehaviorForLive configuration", "Please Use liveSync config to keep on live Edge instead."), delete a.manifest.hls.useSafariBehaviorForLive);
          a.streaming && "parsePrftBox" in a.streaming && (Wc("streaming.parsePrftBox configuration", "Now fired without needing a configuration."), delete a.streaming.parsePrftBox);
          a.manifest && a.manifest.dash && "enableAudioGroups" in a.manifest.dash && (Wc("manifest.dash.enableAudioGroups configuration", "It is now enabled by default and cannot be disabled."), delete a.manifest.dash.enableAudioGroups);
          a.streaming && "dispatchAllEmsgBoxes" in a.streaming && (Wc("streaming.dispatchAllEmsgBoxes configuration", "Please Use mediaSource.dispatchAllEmsgBoxes instead."), a.mediaSource = a.mediaSource || {}, a.mediaSource.dispatchAllEmsgBoxes = a.streaming.dispatchAllEmsgBoxes, delete a.streaming.dispatchAllEmsgBoxes);
          a.streaming && "autoLowLatencyMode" in a.streaming && (Wc("streaming.autoLowLatencyMode configuration", "Please Use streaming.lowLatencyMode instead."), a.streaming.lowLatencyMode = a.streaming.autoLowLatencyMode, delete a.streaming.autoLowLatencyMode);
          a.manifest && a.manifest.dash && "ignoreSupplementalCodecs" in a.manifest.dash && (Wc("manifest.dash.ignoreSupplementalCodecs configuration", "Please Use manifest.ignoreSupplementalCodecs instead."), a.manifest.ignoreSupplementalCodecs = a.manifest.dash.ignoreSupplementalCodecs, delete a.manifest.dash.ignoreSupplementalCodecs);
          a.manifest && a.manifest.hls && "ignoreSupplementalCodecs" in a.manifest.hls && (Wc("manifest.hls.ignoreSupplementalCodecs configuration", "Please Use manifest.ignoreSupplementalCodecs instead."), a.manifest.ignoreSupplementalCodecs = a.manifest.hls.ignoreSupplementalCodecs, delete a.manifest.hls.ignoreSupplementalCodecs);
          a.manifest && a.manifest.dash && "updatePeriod" in a.manifest.dash && (Wc("manifest.dash.updatePeriod configuration", "Please Use manifest.updatePeriod instead."), a.manifest.updatePeriod = a.manifest.dash.updatePeriod, delete a.manifest.dash.updatePeriod);
          a.manifest && a.manifest.hls && "updatePeriod" in a.manifest.hls && (Wc("manifest.hls.updatePeriod configuration", "Please Use manifest.updatePeriod instead."), a.manifest.updatePeriod = a.manifest.hls.updatePeriod, delete a.manifest.hls.updatePeriod);
          a.manifest && a.manifest.dash && "ignoreDrmInfo" in a.manifest.dash && (Wc("manifest.dash.ignoreDrmInfo configuration", "Please Use manifest.ignoreDrmInfo instead."), a.manifest.ignoreDrmInfo = a.manifest.dash.ignoreDrmInfo, delete a.manifest.dash.ignoreDrmInfo);
          if (a.drm && a.drm.advanced) {
            c = false;
            for (var f in a.drm.advanced) {
              var g = a.drm.advanced[f];
              d2 = g.videoRobustness;
              g = g.audioRobustness;
              "videoRobustness" in a.drm.advanced[f] && !Array.isArray(a.drm.advanced[f].videoRobustness) && (a.drm.advanced[f].videoRobustness = [d2], c = true);
              "audioRobustness" in a.drm.advanced[f] && !Array.isArray(a.drm.advanced[f].audioRobustness) && (a.drm.advanced[f].audioRobustness = [g], c = true);
            }
            c && Wc("AdvancedDrmConfiguration's videoRobustness and audioRobustness", "These properties are no longer strings but array of strings, please update your usage of these properties.");
          }
          a.streaming && "forceHTTP" in a.streaming && (Wc("streaming.forceHTTP configuration", "Please Use networking.forceHTTP instead."), a.networking = a.networking || {}, a.networking.forceHTTP = a.streaming.forceHTTP, delete a.streaming.forceHTTP);
          a.streaming && "forceHTTPS" in a.streaming && (Wc("streaming.forceHTTPS configuration", "Please Use networking.forceHTTP instead."), a.networking = a.networking || {}, a.networking.forceHTTPS = a.streaming.forceHTTPS, delete a.streaming.forceHTTPS);
          a.streaming && "minBytesForProgressEvents" in a.streaming && (Wc("streaming.minBytesForProgressEvents configuration", "Please Use networking.minBytesForProgressEvents instead."), a.networking = a.networking || {}, a.networking.minBytesForProgressEvents = a.streaming.minBytesForProgressEvents, delete a.streaming.minBytesForProgressEvents);
          f = $n(this.g, a, kq(this));
          zr(this);
          return f;
        };
        p.vk = function(a) {
          this.Dg = a;
        };
        function zr(a) {
          a.Pe = new yi(a.g, a.ua, a.F);
          if (a.I) {
            var b = Hd(a.g.manifest);
            a.h && a.h.nodeName === "AUDIO" && (b.disableVideo = true);
            a.I.configure(b);
          }
          a.F && a.F.configure(a.g.drm);
          if (a.l) {
            a.l.configure(a.g.streaming);
            try {
              a.m != uq && Ai(a.Pe, a.i) && $q(a);
            } catch (c) {
              Bq(a, c);
            }
            a.A && dr(a);
            b = a.l.u;
            !b || b.allowedByApplication && b.allowedByKeySystem || qq(a);
          }
          a.J && a.J.configure(a.g.networking);
          a.H && (a.H.configure(a.g.mediaSource), a.H.Ia = a.g.manifest.segmentRelativeVttTiming);
          a.u && Tq(a);
          a.A && (a.A.configure(a.g.abr), a.g.abr.enabled ? a.A.enable() : a.A.disable(), nr(a));
          a.P && yr(a);
          a.Ma && (a.g.streaming.rebufferingGoal ? a.Ma.za(0.25) : a.Ma.stop());
          a.i && er(a.i.presentationTimeline, a.g.playRangeStart, a.g.playRangeEnd);
          a.D && a.D.configure(a.g.ads);
          a.L && a.L.configure(a.g.cmcd);
          a.sa && a.sa.configure(a.g.cmsd);
          a.va && a.va.configure(a.g.queue);
        }
        p.getConfiguration = function() {
          var a = kq(this);
          $n(a, this.g, kq(this));
          return a;
        };
        p.Hk = function() {
          return this.Dg;
        };
        p.Zi = function() {
          var a = kq(this);
          $n(a, this.g, kq(this));
          return Dn(this.g, kq(this));
        };
        p.Wi = function() {
          if (this.h) {
            var a = this.h.buffered.length;
            a = a ? this.h.buffered.end(a - 1) : 0;
            var b = this.getConfiguration().streaming.bufferingGoal;
            b = Math.min(this.h.currentTime + b, this.ya().end);
            if (a >= b) return 1;
            if (!(a <= this.h.currentTime) && a < b) return (a - this.h.currentTime) / (b - this.h.currentTime);
          }
          return 0;
        };
        p.Aj = function() {
          for (var a in this.g) delete this.g[a];
          $n(this.g, kq(this), kq(this));
          zr(this);
        };
        p.Rk = function() {
          return this.m;
        };
        p.rh = function() {
          return this.i ? this.i.type : null;
        };
        p.Yk = function() {
          return this.h;
        };
        p.Lb = function() {
          return this.J;
        };
        p.ed = function() {
          return this.V;
        };
        p.rf = function() {
          return this.D ? this.D : null;
        };
        p.uh = function() {
          return this.va ? this.va : null;
        };
        p.U = function() {
          return this.i && !this.Da() ? this.i.presentationTimeline.U() : this.h && (this.h.src || this.Da()) ? this.h.duration == Infinity : false;
        };
        p.kd = function() {
          return this.i ? this.i.presentationTimeline.kd() : false;
        };
        p.Hd = function() {
          if (this.i && !this.Da()) {
            var a = this.i.variants;
            return a.length ? !a[0].video : false;
          }
          return this.h && (this.h.src || this.Da()) ? this.h.videoTracks ? this.h.videoTracks.length == 0 : this.h.videoHeight == 0 : false;
        };
        p.Hh = function() {
          if (this.i && !this.Da()) {
            var a = this.i.variants;
            if (!a.length) return false;
            a = a[0];
            return a.audio || !a.video ? false : !a.video.codecs.includes(",");
          }
          return this.h && (this.h.src || this.Da()) && this.h.audioTracks ? this.h.audioTracks.length == 0 : false;
        };
        p.ya = function() {
          if (this.i && !this.Da()) {
            if (!this.aa && this.i.type == "HLS") return {
              start: 0,
              end: 0
            };
            var a = this.i.presentationTimeline;
            return {
              start: a.ec(),
              end: a.Mb()
            };
          }
          if (this.h && (this.h.src || this.Da()) && (a = this.h.seekable) && a.length) {
            var b = this.g ? this.g.playRangeStart : 0;
            b = Math.max(a.start(0), b);
            var c = this.g ? this.g.playRangeEnd : Infinity;
            a = Math.min(a.end(a.length - 1), c);
            return {
              start: b,
              end: a
            };
          }
          return {
            start: 0,
            end: 0
          };
        };
        p.yl = function() {
          this.U() && (this.h.currentTime = this.ya().end);
        };
        p.Cl = function() {
          return this.aa;
        };
        p.keySystem = function() {
          var a = this.drmInfo();
          return a ? a.keySystem : "";
        };
        p.drmInfo = function() {
          return this.F ? this.F.g : null;
        };
        p.ke = function() {
          return this.F ? this.F.ke() : Infinity;
        };
        p.mh = function() {
          return this.F ? this.F.mh() : [];
        };
        p.tf = function() {
          return this.F ? this.F.tf() : {};
        };
        p.Bf = function() {
          return this.P ? this.P.g == xi : !!this.V;
        };
        p.Ya = function() {
          return this.h ? this.K ? this.K.i : 1 : 0;
        };
        p.zi = function(a) {
          this.m == Xq && this.l && Wm(this.l, a);
        };
        p.Xc = function(a, b) {
          b = b === void 0 ? true : b;
          a == 0 ? bb("A trick play rate of 0 is unsupported!") : (this.K.set(a), this.m == Xq && (this.A.playbackRateChanged(a), this.zi(b && a != 1)), Yq(this, a));
        };
        p.zd = function() {
          var a = this.K.fd();
          this.m == ar && this.K.set(a);
          this.m == Xq && (this.K.set(a), this.A.playbackRateChanged(a), this.zi(false));
          this.kc.Ta();
        };
        p.rb = function() {
          if (this.i && !this.Da()) {
            for (var a = this.l ? this.l.u : null, b = [], c = 0, d2 = t2(this.i.variants), e = d2.next(); !e.done; e = d2.next()) if (e = e.value, kg(e)) {
              var f = cg(e);
              f.active = e == a;
              f.active || c == 1 || a == null || e.video != a.video || e.audio != a.audio || (f.active = true);
              f.active && c++;
              b.push(f);
            }
            return b;
          }
          if (this.h && this.h.audioTracks) {
            var g = Ar(this);
            a = Array.from(this.h.audioTracks);
            return a.length ? a.map(function(h) {
              return jg(h, g);
            }) : g ? [jg(null, g)] : [];
          }
          return [];
        };
        p.vc = function() {
          if (this.i) {
            if (this.Da()) return [];
            for (var a = this.l ? this.l.C : null, b = [], c = t2(this.i.textStreams), d2 = c.next(); !d2.done; d2 = c.next()) {
              d2 = d2.value;
              var e = dg(d2);
              e.active = d2 == a;
              b.push(e);
            }
            return b;
          }
          return this.h && this.h.src && this.h.textTracks ? rr(this).map(function(f) {
            return ig(f);
          }) : [];
        };
        p.ph = function() {
          var a = this.Ve;
          this.i && (a = this.i.imageStreams);
          return a.map(function(b) {
            return eg(b);
          });
        };
        p.yk = function(a) {
          var b = this, c, d2;
          return P(function(e) {
            if (e.g == 1) return G(e, Br(b, a), 2);
            c = e.h;
            if (!c) return e.return(null);
            d2 = [];
            c.segmentIndex.Kb(function(f) {
              var g = Cr(f.tilesLayout || c.tilesLayout);
              if (g) for (var h = g.rows * g.columns, k2 = f.j - f.startTime, l = 0; l < h; l++) {
                var m = Dr(f, c, f.startTime + k2 * l / h, g);
                d2.push(m);
              }
            });
            c.closeSegmentIndex && c.closeSegmentIndex();
            return e.return(d2);
          });
        };
        function Cr(a) {
          return a ? (a = /(\d+)x(\d+)/.exec(a)) ? {
            columns: parseInt(a[1], 10),
            rows: parseInt(a[2], 10)
          } : null : null;
        }
        p.$i = function(a, b) {
          var c = this, d2, e, f, g;
          return P(function(h) {
            if (h.g == 1) return G(h, Br(c, a), 2);
            d2 = h.h;
            if (!d2) return h.return(null);
            e = d2.segmentIndex.find(b);
            if (e == null) return h.return(null);
            f = d2.segmentIndex.get(e);
            return (g = Cr(f.tilesLayout || d2.tilesLayout)) ? h.return(Dr(f, d2, b, g)) : h.return(null);
          });
        };
        function Br(a, b) {
          var c, d2;
          return P(function(e) {
            if (e.g == 1) {
              if (a.m != Xq && a.m != ar) return e.return(null);
              c = a.Ve;
              a.i && (c = a.i.imageStreams);
              d2 = c[0];
              if (!d2) return e.return(null);
              b != null && (d2 = c.find(function(f) {
                return f.id == b;
              }));
              return d2 ? d2.segmentIndex ? e.B(2) : G(e, d2.createSegmentIndex(), 2) : e.return(null);
            }
            return e.return(d2);
          });
        }
        function Dr(a, b, c, d2) {
          var e = b.width || 0, f = b.height || 0, g = e / d2.columns, h = f / d2.rows, k2 = d2.columns * d2.rows, l = a.j - a.startTime;
          l = a.D || l / k2;
          var m = a.startTime, n = 0, q = 0;
          k2 > 1 && (q = Math.floor((c - a.startTime) / l), m = a.startTime + q * l, n = q % d2.columns * g, q = Math.floor(q / d2.columns) * h);
          d2 = false;
          if (c = a.thumbnailSprite) d2 = true, h = c.height, n = c.positionX, q = c.positionY, g = c.width;
          return {
            segment: a,
            imageHeight: f,
            imageWidth: e,
            height: h,
            positionX: n,
            positionY: q,
            startTime: m,
            duration: l,
            uris: a.T(),
            startByte: a.Nc(),
            endByte: a.Lc(),
            width: g,
            sprite: d2,
            mimeType: a.mimeType || b.mimeType,
            codecs: a.codecs || b.codecs
          };
        }
        p.fg = function(a) {
          function b() {
            var d2 = c.i.textStreams.find(function(e) {
              return e.id == a.id;
            });
            d2 && d2 != c.l.C && (fo(c.C.h, d2, false), Zm(c.l, d2), Zq(c), mr(c), c.Sd = d2.language);
          }
          var c = this;
          if (this.i && this.G && (b(), !this.Da())) return;
          (function() {
            if (c.h && c.h.textTracks) {
              var d2 = rr(c), e = d2.find(function(h) {
                return gg(h) === a.id;
              });
              if (e) {
                if (c.u instanceof Wo) {
                  d2 = t2(d2);
                  for (var f = d2.next(); !f.done; f = d2.next()) {
                    f = f.value;
                    var g = f === e ? c.Z ? "showing" : "hidden" : "disabled";
                    f.mode !== g && (f.mode = g);
                  }
                } else d2 = d2.find(function(h) {
                  return h.mode !== "disabled";
                }), d2 !== e && (d2 && (d2.mode = "disabled", c.j.Ea(d2, "cuechange"), c.u.remove(0, Infinity)), e && ur(c, e));
                Zq(c);
                mr(c);
              }
            }
          })();
        };
        function ur(a, b) {
          a.j.o(b, "cuechange", function() {
            a.u.remove(0, Math.max(0, a.h.currentTime - a.g.streaming.bufferBehind));
            var c = {
              periodStart: 0,
              segmentStart: 0,
              segmentEnd: a.h.duration,
              vttOffset: 0
            }, d2 = [], e = Array.from(b.activeCues || []);
            e = t2(e);
            for (var f = e.next(); !f.done; f = e.next()) {
              f = f.value;
              if (f.endTime === Infinity || f.endTime < f.startTime) f = null;
              else {
                var g = new se(f.startTime, f.endTime, f.text);
                g.line = typeof f.line === "number" ? f.line : null;
                f.lineAlign && (g.lineAlign = f.lineAlign);
                g.lineInterpretation = f.snapToLines ? xe : 1;
                g.position = typeof f.position === "number" ? f.position : null;
                f.positionAlign && (g.positionAlign = f.positionAlign);
                g.size = f.size;
                g.textAlign = f.align;
                f.vertical === "lr" ? g.writingMode = "vertical-lr" : f.vertical === "rl" && (g.writingMode = "vertical-rl");
                f.region && (g.region.id = f.region.id, g.region.height = f.region.lines, g.region.heightUnits = 2, g.region.regionAnchorX = f.region.regionAnchorX, g.region.regionAnchorY = f.region.regionAnchorY, g.region.scroll = f.region.scroll, g.region.viewportAnchorX = f.region.viewportAnchorX, g.region.viewportAnchorY = f.region.viewportAnchorY, g.region.viewportAnchorUnits = rd, g.region.width = f.region.width, g.region.widthUnits = rd);
                Fe(g);
                f = g;
              }
              f && ((g = a.g.mediaSource.modifyCueCallback) && g(f, null, c), d2.push(f));
            }
            a.u.append(d2);
          });
          b.mode = document.pictureInPictureElement ? "showing" : "hidden";
        }
        p.De = function(a, b, c) {
          function d2() {
            var f = e.i.variants.find(function(h) {
              return h.id == a.id;
            });
            if (f && kg(f)) {
              var g = e.l.u;
              e.g.abr.enabled && (g.video != f.video || g.audio && f.audio && g.audio.language == f.audio.language && g.audio.channelsCount == f.audio.channelsCount && g.audio.label == f.audio.label) && bb("Changing tracks while abr manager is enabled will likely result in the selected track being overridden. Consider disabling abr before calling selectVariantTrack().");
              e.Da() ? fr(e, f, false, false, 0) : fr(e, f, false, b || false, c || 0);
              e.M.configure({
                language: f.language,
                role: f.audio && f.audio.roles && f.audio.roles[0] || "",
                channelCount: f.audio && f.audio.channelsCount ? f.audio.channelsCount : 0,
                Qc: f.video && f.video.hdr ? f.video.hdr : "",
                spatialAudio: f.audio && f.audio.spatialAudio ? f.audio.spatialAudio : false,
                videoLayout: f.video && f.video.videoLayout ? f.video.videoLayout : "",
                Zc: f.audio && f.audio.label ? f.audio.label : "",
                Yd: "",
                codecSwitchingStrategy: e.g.mediaSource.codecSwitchingStrategy,
                audioCodec: f.audio && f.audio.codecs ? f.audio.codecs : "",
                ae: g.audio && g.audio.codecs ? g.audio.codecs : "",
                $e: g.audio && g.audio.channelsCount ? g.audio.channelsCount : 0,
                preferredAudioCodecs: e.g.preferredAudioCodecs,
                preferredAudioChannelCount: e.g.preferredAudioChannelCount
              });
              dr(e);
            }
          }
          var e = this;
          b = b === void 0 ? false : b;
          c = c === void 0 ? 0 : c;
          if (this.i && this.G && (d2(), !this.Da())) return;
          (function() {
            if (a.originalAudioId && e.h && e.h.audioTracks) {
              var f = Array.from(e.h.audioTracks);
              f = t2(f);
              for (var g = f.next(); !g.done; g = f.next()) if (g = g.value, gg(g) == a.id) {
                Er(e, g);
                break;
              }
            }
          })();
        };
        p.Gj = function(a, b) {
          function c() {
            var e = d2.M.getConfiguration();
            e.audioCodec = a.codecs || "";
            e.Zc = a.label || "";
            e.channelCount = a.channelsCount || 0;
            e.language = a.language;
            e.role = a.roles[0] || "";
            e.spatialAudio = a.spatialAudio;
            d2.M.configure(e);
            qq(d2, true, b, false, false);
          }
          var d2 = this;
          b = b === void 0 ? 0 : b;
          if (this.i && this.G && (c(), !this.Da())) return;
          (function() {
            if (d2.h && d2.h.audioTracks) {
              var e = zc(a.language), f = Array.from(d2.h.audioTracks), g = null;
              f = t2(f);
              for (var h = f.next(); !h.done; h = f.next()) {
                h = h.value;
                var k2 = h.language || "und";
                if (h.label == a.label && zc(k2) == e && h.kind == a.roles[0]) {
                  g = h;
                  break;
                }
              }
              g && Er(d2, g);
            }
          })();
        };
        p.getAudioTracks = function() {
          if (this.i && !this.Da()) {
            var a = this.rb();
            if (!a.length) return [];
            var b = a.find(function(f) {
              return f.active;
            });
            if (!b) return [];
            var c = a;
            this.m != Xq || this.Da() || (c = a.filter(function(f) {
              return f.originalVideoId === b.originalVideoId && f.audioCodec;
            }));
            if (!c.length) return [];
            a = /* @__PURE__ */ new Map();
            c = t2(c);
            for (var d2 = c.next(); !d2.done; d2 = c.next()) {
              d2 = d2.value;
              var e = d2.originalAudioId;
              e || d2.audioId == null || (e = String(d2.audioId));
              e && a.set(e, {
                active: d2.active,
                language: d2.language,
                label: d2.label,
                mimeType: d2.audioMimeType,
                codecs: d2.audioCodec,
                primary: d2.primary,
                roles: d2.audioRoles || [],
                accessibilityPurpose: d2.accessibilityPurpose,
                channelsCount: d2.channelsCount,
                audioSamplingRate: d2.audioSamplingRate,
                spatialAudio: d2.spatialAudio,
                originalLanguage: d2.originalLanguage
              });
            }
            return Array.from(a.values());
          }
          return this.h && this.h.audioTracks ? Array.from(this.h.audioTracks).map(function(f) {
            var g = f.language;
            g = {
              active: f.enabled,
              language: zc(g || "und"),
              label: f.label,
              mimeType: null,
              codecs: null,
              primary: f.kind == "main",
              roles: [],
              accessibilityPurpose: null,
              channelsCount: null,
              audioSamplingRate: null,
              spatialAudio: false,
              originalLanguage: g
            };
            f.kind && g.roles.push(f.kind);
            f.configuration && (f.configuration.codec && (g.codecs = f.configuration.codec), f.configuration.sampleRate && (g.audioSamplingRate = f.configuration.sampleRate), f.configuration.numberOfChannels && (g.channelsCount = f.configuration.numberOfChannels));
            return g;
          }) : [];
        };
        p.Hj = function(a, b, c) {
          b = b === void 0 ? false : b;
          c = c === void 0 ? 0 : c;
          var d2 = this.rb();
          if (d2.length) {
            var e = d2.find(function(f) {
              return f.active;
            });
            e && (d2 = d2.find(function(f) {
              return f.audioId === e.audioId && (f.videoBandwidth || f.bandwidth) == a.bandwidth && f.width == a.width && f.height == a.height && f.frameRate == a.frameRate && f.pixelAspectRatio == a.pixelAspectRatio && f.hdr == a.hdr && f.colorGamut == a.colorGamut && f.videoLayout == a.videoLayout && f.videoMimeType == a.mimeType && f.videoCodec == a.codecs;
            })) && !d2.active && this.De(d2, b, c);
          }
        };
        p.getVideoTracks = function() {
          if (this.m == ar || this.Da()) return [];
          var a = this.rb();
          if (!a.length) return [];
          var b = a.find(function(f) {
            return f.active;
          });
          if (!b) return [];
          var c = a.filter(function(f) {
            return f.originalAudioId === b.originalAudioId && f.audioId === b.audioId && f.audioGroupId === b.audioGroupId && f.videoCodec;
          });
          if (!c.length) return [];
          a = /* @__PURE__ */ new Map();
          c = t2(c);
          for (var d2 = c.next(); !d2.done; d2 = c.next()) {
            d2 = d2.value;
            var e = d2.originalVideoId;
            e || d2.videoId == null || (e = String(d2.videoId));
            e && a.set(e, {
              active: d2.active,
              bandwidth: d2.videoBandwidth || d2.bandwidth,
              width: d2.width,
              height: d2.height,
              frameRate: d2.frameRate,
              pixelAspectRatio: d2.pixelAspectRatio,
              hdr: d2.hdr,
              colorGamut: d2.colorGamut,
              videoLayout: d2.videoLayout,
              mimeType: d2.videoMimeType,
              codecs: d2.videoCodec
            });
          }
          return Array.from(a.values());
        };
        p.Ak = function() {
          return Fr(this.rb());
        };
        p.kl = function() {
          return Fr(this.vc());
        };
        p.zk = function() {
          return Array.from(Gr(this.rb()));
        };
        p.jl = function() {
          return Array.from(Gr(this.vc()));
        };
        p.Fj = function(a, b, c, d2, e, f, g) {
          function h() {
            function l(u, w) {
              return u.video || w.video ? u.video && w.video ? Math.abs((u.video.height || 0) - (w.video.height || 0)) + Math.abs((u.video.width || 0) - (w.video.width || 0)) : Infinity : 0;
            }
            var m = k2.l.u;
            k2.M = k2.g.adaptationSetCriteriaFactory();
            k2.M.configure({
              language: a,
              role: b || "",
              channelCount: c || 0,
              Qc: "",
              spatialAudio: f || false,
              videoLayout: "",
              Zc: g || "",
              Yd: "",
              codecSwitchingStrategy: k2.g.mediaSource.codecSwitchingStrategy,
              audioCodec: e || "",
              ae: m.audio && m.audio.codecs ? m.audio.codecs : "",
              $e: m.audio && m.audio.channelsCount ? m.audio.channelsCount : 0,
              preferredAudioCodecs: k2.g.preferredAudioCodecs,
              preferredAudioChannelCount: k2.g.preferredAudioChannelCount
            });
            var n = k2.M.create(k2.i.variants), q = null;
            n = t2(n.values());
            for (var r2 = n.next(); !r2.done; r2 = n.next()) r2 = r2.value, kg(r2) && (!q || l(q, m) > l(r2, m)) && (q = r2);
            q != m && (q ? (m = cg(q), k2.De(m, true, d2 || 0)) : qq(k2));
          }
          var k2 = this;
          c = c === void 0 ? 0 : c;
          d2 = d2 === void 0 ? 0 : d2;
          e = e === void 0 ? "" : e;
          f = f === void 0 ? false : f;
          g = g === void 0 ? "" : g;
          if (this.i && this.G && (h(), !this.Da())) return;
          (function() {
            if (k2.h && k2.h.audioTracks) {
              var l = mg(k2.rb(), a, b || "", false)[0];
              l && k2.De(l);
            }
          })();
        };
        p.ai = function(a, b, c) {
          function d2() {
            e.Sd = a;
            e.Zd = b || "";
            e.Oe = c || false;
            var f = mg(e.i.textStreams, e.Sd, e.Zd, e.Oe)[0] || null;
            f && f != e.l.C && (fo(e.C.h, f, false), e.g.streaming.alwaysStreamText || e.ld()) && (Zm(e.l, f), Zq(e), mr(e));
          }
          var e = this;
          c = c === void 0 ? false : c;
          if (this.i && this.G && (d2(), !this.Da())) return;
          (function() {
            var f = mg(e.vc(), a, b || "", c || false)[0];
            f && e.fg(f);
          })();
        };
        p.om = function(a, b, c) {
          function d2() {
            for (var f = null, g = t2(e.i.variants), h = g.next(); !h.done; h = g.next()) if (h = h.value, h.audio.label == a) {
              f = h;
              break;
            }
            f != null && (e.M = e.g.adaptationSetCriteriaFactory(), e.M.configure({
              language: f.language,
              role: "",
              channelCount: 0,
              Qc: "",
              spatialAudio: false,
              videoLayout: "",
              Yd: "",
              Zc: a,
              codecSwitchingStrategy: e.g.mediaSource.codecSwitchingStrategy,
              audioCodec: "",
              ae: "",
              $e: 0,
              preferredAudioCodecs: e.g.preferredAudioCodecs,
              preferredAudioChannelCount: e.g.preferredAudioChannelCount
            }), qq(e, b, c));
          }
          var e = this;
          b = b === void 0 ? true : b;
          c = c === void 0 ? 0 : c;
          if (this.i && this.G && (d2(), !this.Da())) return;
          (function() {
            if (e.h && e.h.audioTracks) {
              var f = Array.from(e.h.audioTracks), g = null;
              f = t2(f);
              for (var h = f.next(); !h.done; h = f.next()) h = h.value, h.label == a && (g = h);
              g && Er(e, g);
            }
          })();
        };
        p.ld = function() {
          var a = this.Z;
          return this.u ? this.u.isTextVisible() : a;
        };
        p.Ek = function() {
          return this.fb.map(function(a) {
            return dg(a);
          });
        };
        p.Dk = function(a) {
          Wc("getChapters", "Please use an getChaptersAsync.");
          if (!this.fb.length) return [];
          var b = zc(a);
          a = this.fb.filter(function(f) {
            return zc(f.language) == b;
          });
          if (!a.length) return [];
          var c = [], d2 = /* @__PURE__ */ new Set();
          a = t2(a);
          for (var e = a.next(); !e.done; e = a.next()) e = e.value, e.segmentIndex && e.segmentIndex.Kb(function(f) {
            var g = f.T()[0], h = f.startTime + "-" + f.endTime + "-" + g;
            f = {
              id: h,
              title: g,
              startTime: f.startTime,
              endTime: f.endTime
            };
            d2.has(h) || (c.push(f), d2.add(h));
          });
          return c;
        };
        p.nh = function(a) {
          var b = this, c, d2, e, f, g, h, k2;
          return P(function(l) {
            switch (l.g) {
              case 1:
                if (!b.fb.length) return l.return([]);
                c = zc(a);
                d2 = b.fb.filter(function(m) {
                  return zc(m.language) == c;
                });
                if (!d2.length) return l.return([]);
                e = [];
                f = /* @__PURE__ */ new Set();
                g = t2(d2);
                h = g.next();
              case 2:
                if (h.done) {
                  l.B(4);
                  break;
                }
                k2 = h.value;
                if (k2.segmentIndex) {
                  l.B(5);
                  break;
                }
                return G(l, k2.createSegmentIndex(), 5);
              case 5:
                k2.segmentIndex.Kb(function(m) {
                  var n = m.T()[0], q = m.startTime + "-" + m.endTime + "-" + n;
                  m = {
                    id: q,
                    title: n,
                    startTime: m.startTime,
                    endTime: m.endTime
                  };
                  f.has(q) || (e.push(m), f.add(q));
                });
                h = g.next();
                l.B(2);
                break;
              case 4:
                return l.return(e);
            }
          });
        };
        function rr(a) {
          return Array.from(a.h.textTracks).filter(function(b) {
            return b.kind != "metadata" && b.kind != "chapters" && b.label != "Shaka Player TextTrack";
          });
        }
        function sr(a) {
          return Array.from(a.h.textTracks).find(function(b) {
            return b.label == "Shaka Player TextTrack";
          });
        }
        function wr(a) {
          return Array.from(a.h.textTracks).filter(function(b) {
            return b.kind == "metadata";
          });
        }
        p.Fe = function(a) {
          a = !!a;
          this.Z != a && (this.Z = a, this.m == Xq ? (this.u.setTextVisibility(a), this.g.streaming.alwaysStreamText || (a ? this.l.C || (a = mg(this.i.textStreams, this.Sd, this.Zd, this.Oe), a.length > 0 && (Zm(this.l, a[0]), Zq(this), mr(this))) : Vm(this.l))) : this.h && this.h.src && this.h.textTracks && this.u.setTextVisibility(a), lr(this));
        };
        p.Zk = function() {
          if (this.G) var a = this.G.Xe();
          else {
            if (this.O == null) return /* @__PURE__ */ new Date();
            if (this.O instanceof Date) return this.O;
            a = this.O;
          }
          if (this.i && !this.Da()) {
            var b = this.i.presentationTimeline;
            return new Date(((b.m || b.i) + a) * 1e3);
          }
          return this.h && this.h.getStartDate ? (b = this.h.getStartDate(), isNaN(b.getTime()) ? null : new Date(b.getTime() + a * 1e3)) : null;
        };
        p.sh = function() {
          if (this.i && !this.Da()) {
            var a = this.i.presentationTimeline;
            a = a.m || a.i;
            return a === null ? null : new Date(a * 1e3);
          }
          return this.h && this.h.getStartDate ? (a = this.h.getStartDate(), isNaN(a.getTime()) ? null : a) : null;
        };
        p.wf = function() {
          return this.U() ? this.i ? this.i.presentationTimeline.wf() : null : null;
        };
        p.cc = function() {
          if (this.m == Xq) return this.H.cc();
          var a = {
            total: [],
            audio: [],
            video: [],
            text: []
          };
          this.m == ar && (a.total = Lj(this.h.buffered));
          return a;
        };
        p.uf = function() {
          if (!this.h || !this.h.currentTime) return null;
          var a = this.sh().getTime() + this.h.currentTime * 1e3;
          return Math.floor(Date.now() - a);
        };
        p.getStats = function() {
          if (this.m != Xq && this.m != ar) return {
            width: NaN,
            height: NaN,
            currentCodecs: "",
            streamBandwidth: NaN,
            decodedFrames: NaN,
            droppedFrames: NaN,
            corruptedFrames: NaN,
            stallsDetected: NaN,
            gapsJumped: NaN,
            estimatedBandwidth: NaN,
            completionPercent: NaN,
            loadLatency: NaN,
            manifestTimeSeconds: NaN,
            drmTimeSeconds: NaN,
            playTime: NaN,
            pauseTime: NaN,
            bufferingTime: NaN,
            licenseTime: NaN,
            liveLatency: NaN,
            maxSegmentDuration: NaN,
            manifestSizeBytes: NaN,
            bytesDownloaded: NaN,
            nonFatalErrorCount: NaN,
            manifestPeriodCount: NaN,
            manifestGapCount: NaN,
            switchHistory: [],
            stateHistory: []
          };
          Wq(this);
          var a = this.h, b = a.currentTime / a.duration;
          isNaN(b) || this.U() || jo(this.C, Math.round(100 * b));
          this.G && (this.C.R = this.G.Ai(), this.C.S = this.G.Ci());
          a.getVideoPlaybackQuality && (b = a.getVideoPlaybackQuality(), ho(this.C, Number(b.droppedVideoFrames), Number(b.totalVideoFrames)), this.C.M = Number(b.corruptedVideoFrames));
          this.C.u = this.F ? ci(this.F) : NaN;
          io(this.C, a.videoWidth || NaN, a.videoHeight || NaN);
          this.C.l = "";
          this.U() && this.sh() != null && (a = this.uf() || 0, this.C.F = a / 1e3);
          b = this.rb().find(function(e) {
            return e.active;
          });
          a = this.vc().find(function(e) {
            return e.active;
          });
          if (b) {
            if (b.bandwidth) {
              var c = this.K ? this.K.i : 1, d2 = c * b.bandwidth;
              a && a.bandwidth && (d2 += c * a.bandwidth);
              this.C.C = d2;
            }
            b.width && b.height && io(this.C, b.width || NaN, b.height || NaN);
            b = b.codecs;
            a && (b += "," + (a.codecs || a.mimeType));
            b && (this.C.l = b);
          }
          this.m != Xq || this.Da() || (this.i && (this.C.I = this.i.periodCount, this.C.H = this.i.gapCount, this.i.presentationTimeline && (this.C.K = this.i.presentationTimeline.h)), a = this.A.getBandwidthEstimate(), this.C.A = a);
          this.m == ar && ko(this.C, NaN);
          return lo(this.C);
        };
        p.be = function(a, b, c, d2, e, f, g) {
          g = g === void 0 ? false : g;
          var h = this, k2, l, m, n, q, r2, u, w, v, y, z, A;
          return P(function(C) {
            switch (C.g) {
              case 1:
                if (h.m != Xq && h.m != ar) throw new U(1, 7, 7004);
                c != "subtitles" && c != "captions" && bb("Using a kind value different of `subtitles` or `captions` can cause unwanted issues.");
                if (d2) {
                  C.B(2);
                  break;
                }
                return G(C, Hr(h, a), 3);
              case 3:
                d2 = C.h;
              case 2:
                k2 = [];
                h.D && (k2 = h.D.getCuePoints());
                if (h.m != ar) {
                  C.B(4);
                  break;
                }
                l = Sb();
                g && l.Ga() === "WEBKIT" && (c = "forced");
                return G(C, Ir(h, a, b, c, d2, f || "", k2), 5);
              case 5:
                m = C.h;
                if (m.track) return $q(h), C.return(ig(m.track));
                throw new U(1, 2, 2012);
              case 4:
                n = vc;
                q = h.ya();
                r2 = q.end - q.start;
                h.i && (r2 = h.i.presentationTimeline.getDuration());
                if (r2 == Infinity) throw new U(1, 4, 4033);
                if (!k2.length) {
                  C.B(6);
                  break;
                }
                return G(C, Jr(h, a, h.J, h.g.streaming.retryParameters), 7);
              case 7:
                u = C.h, w = Kr(h, u, d2, k2), v = new Blob([w], {
                  type: "text/vtt"
                }), a = Bk(v), d2 = "text/vtt";
              case 6:
                y = {
                  id: h.Qe++,
                  originalId: null,
                  groupId: null,
                  createSegmentIndex: function() {
                    return Promise.resolve();
                  },
                  segmentIndex: am(0, r2, [a]),
                  mimeType: d2 || "",
                  codecs: e || "",
                  kind: c,
                  encrypted: false,
                  drmInfos: [],
                  keyIds: /* @__PURE__ */ new Set(),
                  language: b,
                  originalLanguage: b,
                  label: f || null,
                  type: n.ab,
                  primary: false,
                  trickModeVideo: null,
                  dependencyStream: null,
                  emsgSchemeIdUris: null,
                  roles: [],
                  forced: !!g,
                  channelsCount: null,
                  audioSamplingRate: null,
                  spatialAudio: false,
                  closedCaptions: null,
                  accessibilityPurpose: null,
                  external: true,
                  fastSwitching: false,
                  fullMimeTypes: /* @__PURE__ */ new Set([ef(d2 || "", e || "")]),
                  isAudioMuxedInVideo: false,
                  baseOriginalId: null
                };
                z = ef(y.mimeType, y.codecs);
                A = vf(z);
                if (!A) throw new U(2, 2, 2014, d2);
                h.i.textStreams.push(y);
                $q(h);
                return C.return(dg(y));
            }
          });
        };
        p.cf = function(a, b) {
          var c = this, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C;
          return P(function(D) {
            switch (D.g) {
              case 1:
                if (c.m != Xq && c.m != ar) throw new U(1, 7, 7004);
                if (b) {
                  D.B(2);
                  break;
                }
                return G(D, Hr(c, a), 3);
              case 3:
                b = D.h;
              case 2:
                if (b != "text/vtt") throw new U(1, 2, 2017, a);
                d2 = vc;
                e = c.ya();
                f = e.end - e.start;
                c.i && (f = c.i.presentationTimeline.getDuration());
                if (f == Infinity) throw new U(1, 4, 4045);
                return G(D, Jr(c, a, c.J, c.g.streaming.retryParameters), 4);
              case 4:
                g = D.h;
                h = uf(b);
                if (!h) throw new U(2, 2, 2014, b);
                k2 = h();
                l = {
                  periodStart: 0,
                  segmentStart: 0,
                  segmentEnd: f,
                  vttOffset: 0
                };
                m = Lb(g);
                n = k2.parseMedia(m, l, a, []);
                q = [];
                r2 = t2(n);
                u = r2.next();
                for (w = {}; !u.done; w = {
                  vg: void 0,
                  Cd: void 0
                }, u = r2.next()) w.Cd = u.value, w.vg = null, v = /* @__PURE__ */ function(F) {
                  return function() {
                    F.vg == null && (F.vg = nc([a], [F.Cd.payload]));
                    return F.vg || [];
                  };
                }(w), y = new Cj(w.Cd.startTime, w.Cd.endTime, v, 0, null, null, 0, 0, Infinity), w.Cd.payload.includes("#xywh") && (z = w.Cd.payload.split("#xywh=")[1].split(","), z.length === 4 && y.jg({
                  height: parseInt(z[3], 10),
                  positionX: parseInt(z[0], 10),
                  positionY: parseInt(z[1], 10),
                  width: parseInt(z[2], 10)
                })), q.push(y);
                A = b;
                if (!q.length) {
                  D.B(5);
                  break;
                }
                return G(D, Jo(q[0].T()[0], c.J, c.g.manifest.retryParameters), 6);
              case 6:
                A = D.h;
              case 5:
                return C = {
                  id: c.Qe++,
                  originalId: null,
                  groupId: null,
                  createSegmentIndex: function() {
                    return Promise.resolve();
                  },
                  segmentIndex: new Zl(q),
                  mimeType: A || "",
                  codecs: "",
                  kind: "",
                  encrypted: false,
                  drmInfos: [],
                  keyIds: /* @__PURE__ */ new Set(),
                  language: "und",
                  originalLanguage: null,
                  label: null,
                  type: d2.yg,
                  primary: false,
                  trickModeVideo: null,
                  dependencyStream: null,
                  emsgSchemeIdUris: null,
                  roles: [],
                  forced: false,
                  channelsCount: null,
                  audioSamplingRate: null,
                  spatialAudio: false,
                  closedCaptions: null,
                  tilesLayout: "1x1",
                  accessibilityPurpose: null,
                  external: true,
                  fastSwitching: false,
                  fullMimeTypes: /* @__PURE__ */ new Set([ef(A || "", "")]),
                  isAudioMuxedInVideo: false,
                  baseOriginalId: null
                }, c.m == ar ? c.Ve.push(C) : c.i.imageStreams.push(C), $q(c), D.return(eg(C));
            }
          });
        };
        p.bf = function(a, b, c) {
          var d2 = this, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z;
          return P(function(A) {
            switch (A.g) {
              case 1:
                if (d2.m != Xq && d2.m != ar) throw new U(1, 7, 7004);
                if (c) {
                  A.B(2);
                  break;
                }
                return G(A, Hr(d2, a), 3);
              case 3:
                c = A.h;
              case 2:
                e = vc;
                f = d2.ya();
                g = f.end - f.start;
                d2.i && (g = d2.i.presentationTimeline.getDuration());
                if (g == Infinity) throw new U(1, 4, 4054);
                return G(A, Jr(d2, a, d2.J, d2.g.streaming.retryParameters), 4);
              case 4:
                h = A.h;
                k2 = uf(c);
                if (!k2) throw new U(2, 2, 2014, c);
                l = k2();
                m = {
                  periodStart: 0,
                  segmentStart: 0,
                  segmentEnd: g,
                  vttOffset: 0
                };
                n = Lb(h);
                q = l.parseMedia(n, m, a, []);
                r2 = [];
                u = t2(q);
                w = u.next();
                for (v = {}; !w.done; v = {
                  nf: void 0
                }, w = u.next()) v.nf = w.value, y = new Cj(v.nf.startTime, v.nf.endTime, /* @__PURE__ */ function(C) {
                  return function() {
                    return [C.nf.payload];
                  };
                }(v), 0, null, null, 0, 0, Infinity), r2.push(y);
                z = {
                  id: d2.Qe++,
                  originalId: null,
                  groupId: null,
                  createSegmentIndex: function() {
                    return Promise.resolve();
                  },
                  segmentIndex: new Zl(r2),
                  mimeType: "text/plain",
                  codecs: "",
                  kind: "",
                  encrypted: false,
                  drmInfos: [],
                  keyIds: /* @__PURE__ */ new Set(),
                  language: b,
                  originalLanguage: b,
                  label: null,
                  type: e.ab,
                  primary: false,
                  trickModeVideo: null,
                  dependencyStream: null,
                  emsgSchemeIdUris: null,
                  roles: [],
                  forced: false,
                  channelsCount: null,
                  audioSamplingRate: null,
                  spatialAudio: false,
                  closedCaptions: null,
                  accessibilityPurpose: null,
                  external: true,
                  fastSwitching: false,
                  fullMimeTypes: /* @__PURE__ */ new Set([ef("text/plain", "")]),
                  isAudioMuxedInVideo: false,
                  baseOriginalId: null
                };
                d2.fb.push(z);
                $q(d2);
                return A.return(dg(z));
            }
          });
        };
        function Hr(a, b) {
          var c;
          return P(function(d2) {
            switch (d2.g) {
              case 1:
                return sa(d2, 2), G(d2, Jo(b, a.J, a.g.streaming.retryParameters), 4);
              case 4:
                c = d2.h;
                ua(d2, 3);
                break;
              case 2:
                va(d2);
              case 3:
                if (c) return d2.return(c);
                throw new U(1, 2, 2011, b);
            }
          });
        }
        function Ir(a, b, c, d2, e, f, g) {
          var h, k2, l, m;
          return P(function(n) {
            if (n.g == 1) return e != "text/vtt" || g.length ? G(n, Jr(a, b, a.J, a.g.streaming.retryParameters), 3) : n.B(2);
            n.g != 2 && (h = n.h, k2 = Kr(a, h, e, g), l = new Blob([k2], {
              type: "text/vtt"
            }), b = Bk(l), e = "text/vtt");
            m = document.createElement("track");
            a: {
              var q = a.L, r2 = b;
              try {
                if (!q.g.enabled) {
                  var u = r2;
                  break a;
                }
                var w = wp(q);
                w.ot = Kp;
                w.su = true;
                var v = Ap(w);
                u = Bp(r2, v);
                break a;
              } catch (y) {
                cb("CMCD_TEXT_TRACK_ERROR", "Could not generate text track CMCD data.", y);
                u = r2;
                break a;
              }
              u = void 0;
            }
            m.src = u;
            m.label = f;
            m.kind = d2;
            m.srclang = c;
            a.h.getAttribute("crossorigin") || a.h.setAttribute("crossorigin", "anonymous");
            a.h.appendChild(m);
            a.Cg.push(m);
            return n.return(m);
          });
        }
        function Jr(a, b, c, d2) {
          var e, f, g;
          return P(function(h) {
            if (h.g == 1) {
              e = gh;
              f = ah([b], d2);
              f.method = "GET";
              var k2 = a.L;
              try {
                k2.g.enabled && Cp(k2, f, {
                  ot: Kp,
                  su: true
                });
              } catch (l) {
                cb("CMCD_TEXT_ERROR", "Could not generate text CMCD data.", l);
              }
              return G(h, c.request(e, f).promise, 2);
            }
            g = h.h;
            return h.return(g.data);
          });
        }
        function Kr(a, b, c, d2) {
          var e = uf(c);
          if (e) return c = e(), a = {
            periodStart: 0,
            segmentStart: 0,
            segmentEnd: a.h.duration,
            vttOffset: 0
          }, b = Lb(b), b = c.parseMedia(b, a, null, []), kp(b, d2);
          throw new U(2, 2, 2014, c);
        }
        p.um = function(a, b) {
          this.ua.width = a;
          this.ua.height = b;
        };
        p.Xh = function(a) {
          if (this.m == Xq) {
            var b = this.l;
            a = a === void 0 ? 0.1 : a;
            if (b.l.g) b = false;
            else if (b.D) b = false;
            else {
              for (var c = t2(b.h.values()), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, !d2.oe || d2.$a || d2.Fb || (d2.oe = false, Um(b, d2, a));
              b = true;
            }
          } else b = false;
          return b;
        };
        p.qh = function() {
          bb("Shaka Player's internal Manifest structure is NOT covered by semantic versioning compatibility guarantees.  It may change at any time!  Please consider filing a feature request for whatever you use getManifest() for.");
          return this.i;
        };
        p.Vk = function() {
          return this.Ec;
        };
        p.Nk = function() {
          var a = {
            video: null,
            audio: null,
            text: null
          };
          if (this.m != Xq) return a;
          var b = this.l.u, c = this.h.currentTime;
          b = t2([b.video, b.audio, this.l.C]);
          for (var d2 = b.next(); !d2.done; d2 = b.next()) if ((d2 = d2.value) && d2.segmentIndex) {
            var e = d2.segmentIndex.find(c);
            e = d2.segmentIndex.get(e);
            e = {
              codecs: e.codecs || d2.codecs,
              mimeType: e.mimeType || d2.mimeType,
              bandwidth: e.bandwidth || d2.bandwidth
            };
            d2.type == "video" ? (e.width = d2.width, e.height = d2.height, a.video = e) : d2.type == "audio" ? a.audio = e : d2.type == tc && (a.text = e);
          }
          return a;
        };
        function kq(a) {
          var b = Vn();
          b.streaming.failureCallback = function(c) {
            if (a.U()) {
              var d2 = null;
              c.code == 1001 || c.code == 1002 ? (d2 = 1, a.g.streaming.lowLatencyMode && (d2 = 0.1)) : c.code == 1003 && (d2 = 0.1);
              d2 != null && (c.severity = 1, a.Xh(d2));
            }
          };
          b.textDisplayFactory = function() {
            var c = Sb();
            return a.Re && (document.fullscreenEnabled || c.Ga() !== "WEBKIT") ? new ap(a.h, a.Re) : "track" in document.createElement("track") ? new Wo(a) : new $o();
          };
          return b;
        }
        p.ji = function(a) {
          this.Re = a;
        };
        function Oq(a, b) {
          for (var c = /* @__PURE__ */ new Set(), d2 = t2(b.textStreams), e = d2.next(); !e.done; e = d2.next()) e = e.value, e.mimeType != "application/cea-608" && e.mimeType != "application/cea-708" || c.add(e.originalId);
          d2 = t2(b.variants);
          for (e = d2.next(); !e.done; e = d2.next()) if ((e = e.value.video) && e.closedCaptions) {
            for (var f = t2(e.closedCaptions.keys()), g = f.next(); !g.done; g = f.next()) if (g = g.value, !c.has(g)) {
              var h = g.startsWith("CC") ? "application/cea-608" : "application/cea-708", k2 = new bm(), l = e.closedCaptions.get(g);
              h = {
                id: a.Qe++,
                originalId: g,
                groupId: null,
                createSegmentIndex: function() {
                  return Promise.resolve();
                },
                segmentIndex: k2,
                mimeType: h,
                codecs: "",
                kind: "caption",
                encrypted: false,
                drmInfos: [],
                keyIds: /* @__PURE__ */ new Set(),
                language: l,
                originalLanguage: l,
                label: null,
                type: tc,
                primary: false,
                trickModeVideo: null,
                dependencyStream: null,
                emsgSchemeIdUris: null,
                roles: e.roles,
                forced: false,
                channelsCount: null,
                audioSamplingRate: null,
                spatialAudio: false,
                closedCaptions: null,
                accessibilityPurpose: null,
                external: false,
                fastSwitching: false,
                fullMimeTypes: /* @__PURE__ */ new Set([ef(h, "")]),
                isAudioMuxedInVideo: false,
                baseOriginalId: null
              };
              b.textStreams.push(h);
              c.add(g);
            }
          }
        }
        function kr(a, b) {
          var c, d2, e, f, g;
          return P(function(h) {
            if (h.g == 1) return c = a.audio, d2 = a.video, e = function(k2, l) {
              var m, n, q;
              return P(function(r2) {
                if (r2.g == 1) return k2 ? k2.segmentIndex ? r2.B(2) : G(r2, k2.createSegmentIndex(), 2) : r2.return(null);
                n = (m = k2.segmentIndex.dc(l)) ? m.next().value : null;
                if (!n) return r2.return(null);
                q = n.startTime;
                return r2.return(q);
              });
            }, G(h, e(c, b), 2);
            if (h.g != 3) return f = h.h, G(h, e(d2, b), 3);
            g = h.h;
            return g != null && f != null ? h.return(Math.max(g, f)) : g != null ? h.return(g) : f != null ? h.return(f) : h.return(b);
          });
        }
        function Dq(a) {
          var b = a.Bf();
          if (a.C && a.P && a.G) {
            if (a.g.streaming.rebufferingGoal == 0) {
              var c = a.K;
              c.j = false;
              fm(c);
            } else c = a.K, c.j = b, fm(c);
            a.L && (c = a.L, b || c.A || (c.A = true), c.A && b && (c.D = true), c.G = b);
            Wq(a);
            c = a.g.streaming.liveSync.dynamicTargetLatency.maxAttempts;
            if (a.g.streaming.liveSync.dynamicTargetLatency.enabled && b && a.Ze < c) {
              c = a.g.streaming.liveSync.dynamicTargetLatency.maxLatency;
              var d2 = a.g.streaming.liveSync.targetLatencyTolerance, e = a.g.streaming.liveSync.dynamicTargetLatency.rebufferIncrement;
              a.S && (a.S = Math.min(a.S + ++a.Ze * e, c - d2));
            }
          }
          b = (/* @__PURE__ */ new Map()).set("buffering", b);
          a.dispatchEvent(tq("buffering", b));
        }
        function Yq(a, b) {
          a.kc.Ta();
          a.kc.o(a.h, "timeupdate", function() {
            var c = a.h.currentTime, d2 = a.ya(), e = a.U(), f = e ? a.g.streaming.safeSeekOffset : 0;
            b > 0 ? (!e || b >= 1) && Math.floor(c) >= Math.floor(d2.end) && a.zd() : Math.floor(c) <= Math.floor(d2.start + f) && a.zd();
          });
        }
        function Wq(a) {
          if (a.C && a.P) {
            var b = a.C.g, c = "playing";
            a.P.g == xi ? c = "buffering" : a.isEnded() ? c = "ended" : a.h.paused && (c = "paused");
            var d2 = c;
            if (b.g == null) b.g = {
              timestamp: Date.now() / 1e3,
              state: d2,
              duration: 0
            }, b = true;
            else {
              var e = Date.now() / 1e3;
              b.g.duration = e - b.g.timestamp;
              b.g.state == d2 ? b = false : (b.h.push(b.g), b.g = {
                timestamp: e,
                state: d2,
                duration: 0
              }, b = true);
            }
            b && (c = (/* @__PURE__ */ new Map()).set("newstate", c), a.dispatchEvent(tq("statechanged", c)));
          }
        }
        function or(a) {
          var b = a.h.playbackRate, c = a.U();
          if (a.g.streaming.vodDynamicPlaybackRate && !c) {
            var d2 = a.g.streaming.vodDynamicPlaybackRateLowBufferRate, e = a.Wi();
            e <= a.g.streaming.vodDynamicPlaybackRateBufferRatio ? b != d2 && a.Xc(d2, false) : e == 1 && b !== a.K.fd() && a.zd();
          }
          if (c && (c = a.ya(), Number.isFinite(c.end) && !(a.h.currentTime < c.start || a.h.paused))) {
            d2 = a.g.streaming.liveSync.targetLatencyTolerance;
            e = a.g.streaming.liveSync.dynamicTargetLatency.enabled;
            var f = a.g.streaming.liveSync.dynamicTargetLatency.stabilityThreshold;
            if (a.g.streaming.liveSync && a.g.streaming.liveSync.enabled) {
              var g = a.g.streaming.liveSync.targetLatency;
              var h = g + d2;
              var k2 = Math.max(0, g - d2);
              var l = a.g.streaming.liveSync.maxPlaybackRate;
              var m = a.g.streaming.liveSync.minPlaybackRate;
            } else a.i && a.i.serviceDescription && (g = a.i.serviceDescription.targetLatency, a.i.serviceDescription.targetLatency != null ? h = a.i.serviceDescription.targetLatency + d2 : a.i.serviceDescription.maxLatency != null && (h = a.i.serviceDescription.maxLatency), a.i.serviceDescription.targetLatency != null ? k2 = Math.max(0, a.i.serviceDescription.targetLatency - d2) : a.i.serviceDescription.minLatency != null && (k2 = a.i.serviceDescription.minLatency), l = a.i.serviceDescription.maxPlaybackRate || a.g.streaming.liveSync.maxPlaybackRate, m = a.i.serviceDescription.minPlaybackRate || a.g.streaming.liveSync.minPlaybackRate);
            a.S || typeof g !== "number" || (a.S = g);
            var n = a.g.streaming.liveSync.dynamicTargetLatency.maxAttempts;
            e && a.jc && a.S !== null && typeof g === "number" && a.Ze < n && Date.now() - a.jc > f * 1e3 && (f = a.g.streaming.liveSync.dynamicTargetLatency.minLatency, a.S = Math.max(a.S - (g - f) / 2, f + d2), a.jc = Date.now());
            e && a.S !== null && (h = a.S + d2, k2 = a.S - d2);
            g = c.end - a.h.currentTime;
            d2 = 0;
            a.m == ar && (e = a.h.buffered, e.length > 0 && (d2 = e.end(e.length - 1), d2 = Math.max(l, d2 - c.end)));
            c = a.g.streaming.liveSync.panicMode;
            e = a.g.streaming.liveSync.panicThreshold * 1e3;
            f = Date.now() - a.P.h;
            c && !m && (m = a.g.streaming.liveSync.minPlaybackRate);
            c && m && f <= e ? b != m && a.Xc(m, false) : h != void 0 && l && g - d2 > h ? (b != l && a.Xc(l, false), a.jc = null) : k2 != void 0 && m && g - d2 < k2 ? (b != m && a.Xc(m, false), a.jc = null) : b !== a.K.fd() && (a.zd(), a.jc = Date.now());
          }
        }
        function pr(a) {
          if (a.h) {
            var b = function(e, f) {
              var g = g === void 0 ? Number.EPSILON : g;
              if (e === f) g = true;
              else {
                var h = Math.abs(e - f);
                g = h <= g ? true : g !== Number.EPSILON ? Math.abs(h - g) <= Number.EPSILON : false;
              }
              return (g || f > e) && a.Bg < e ? (a.Bg = e, true) : false;
            }, c = a.ya();
            c = c.end - c.start;
            c = c > 0 ? a.h.currentTime / c : 0;
            if (!isNaN(c)) {
              c *= 100;
              if (b(0, c)) var d2 = tq("started");
              else if (b(25, c)) d2 = tq("firstquartile");
              else if (b(50, c)) d2 = tq("midpoint");
              else if (b(75, c)) d2 = tq("thirdquartile");
              else {
                if (b(100, c) || c > 100) d2 = tq("complete");
                a.g && a.g.playRangeEnd != Infinity && a.isEnded() && a.h.pause();
              }
              d2 && a.dispatchEvent(d2);
            }
          }
        }
        function dr(a) {
          try {
            Di(a.Pe, a.i);
          } catch (c) {
            return Bq(a, c), false;
          }
          var b = lg(a.i.variants);
          b = a.M.create(b);
          a.A.setVariants(Array.from(b.values()));
          return true;
        }
        function qq(a, b, c, d2, e) {
          b = b === void 0 ? true : b;
          c = c === void 0 ? 0 : c;
          d2 = d2 === void 0 ? false : d2;
          e = e === void 0 ? true : e;
          var f;
          (f = dr(a) ? a.A.chooseVariant() : null) && fr(a, f, e, b, c, d2);
        }
        function fr(a, b, c, d2, e, f) {
          f = f === void 0 ? false : f;
          var g = a.l.u;
          if (b == g) d2 && Ym(a.l, b, d2, e, true);
          else {
            var h = a.C.h;
            h.h != b && (h.h = b, h.g.push({
              timestamp: Date.now() / 1e3,
              id: b.id,
              type: "variant",
              fromAdaptation: c,
              bandwidth: b.bandwidth
            }));
            Ym(a.l, b, d2, e, f, c);
            d2 = null;
            g && (d2 = cg(g));
            g = cg(b);
            g.active = true;
            if (a.R && (e = a.R, b = b.video)) {
              b.dependencyStream && (b = b.dependencyStream);
              f = 0;
              h = -1;
              switch (b.mimeType) {
                case "video/webm":
                  f = 1;
                  break;
                case "video/mp4":
                  f = 2;
              }
              switch (a.rh()) {
                case "DASH":
                  h = 1;
                  break;
                case "HLS":
                  h = 0;
              }
              e.g && (e.g.setLevelSwitching(b.id, true), e.g.setContainerFormat(f), e.j || e.g.setStreamingFormat(h));
            }
            c ? (c = (/* @__PURE__ */ new Map()).set("oldTrack", d2).set("newTrack", g), c = tq("adaptation", c), Lr(a, c)) : Mr(a, d2, g);
            Nr(a, d2, g);
          }
        }
        function Er(a, b) {
          var c = Array.from(a.h.audioTracks).find(function(e) {
            return e.enabled;
          });
          b.enabled = true;
          if (c) {
            b.id !== c.id && (c.enabled = false);
            var d2 = Ar(a);
            c = jg(c, d2);
            b = jg(b, d2);
            Mr(a, c, b);
            Nr(a, c, b);
          }
        }
        function Ar(a) {
          return a.h && a.h.videoTracks ? Array.from(a.h.videoTracks).find(function(b) {
            return b.selected;
          }) : null;
        }
        function $q(a) {
          var b = tq("trackschanged");
          Lr(a, b);
          Or(a);
        }
        function Mr(a, b, c) {
          b = (/* @__PURE__ */ new Map()).set("oldTrack", b).set("newTrack", c);
          b = tq("variantchanged", b);
          Lr(a, b);
        }
        function Nr(a, b, c) {
          var d2 = false;
          b && b.audioId == c.audioId && b.audioGroupId == c.audioGroupId || (d2 = true);
          d2 && Or(a);
        }
        function Or(a) {
          var b = tq("audiotrackschanged");
          Lr(a, b);
        }
        function Zq(a) {
          var b = tq("textchanged");
          Lr(a, b);
        }
        function lr(a) {
          var b = tq("texttrackvisibility");
          Lr(a, b);
        }
        function nr(a) {
          a.g.abr.enabled || pq(a);
          var b = (/* @__PURE__ */ new Map()).set("newStatus", a.g.abr.enabled);
          Lr(a, tq("abrstatuschanged", b));
        }
        function mr(a) {
          var b = a.vc().find(function(c) {
            return c.active;
          });
          b && a.u && a.u.setTextLanguage && a.u.setTextLanguage(b.language);
        }
        function pq(a, b) {
          b = b === void 0 ? true : b;
          if (a.m == Xq) {
            a.Se.stop();
            for (var c = t2(a.i.variants), d2 = c.next(); !d2.done; d2 = c.next()) d2.value.disabledUntilTime = 0;
            b && dr(a);
          }
        }
        p.disableStream = function(a, b) {
          if (!this.g.abr.enabled || this.m === uq || !navigator.onLine || b == 0 || !this.i) return false;
          if (this.i.variants.some(function(h) {
            var k2 = h[a.type];
            return k2 && k2.id !== a.id && !h.disabledUntilTime ? a.type == "audio" ? a.language === k2.language : true : false;
          })) {
            for (var c = false, d2 = false, e = t2(this.i.variants), f = e.next(); !f.done; f = e.next()) {
              f = f.value;
              var g = f[a.type];
              g && (g.id === a.id ? (f.disabledUntilTime = Date.now() / 1e3 + b, c = true) : g.trickModeVideo && g.trickModeVideo.id == a.id && (d2 = true));
            }
            if (!c && d2) return false;
            this.Se.za(1);
            b = this.cc().video.reduce(function(h, k2) {
              return h + k2.end - k2.start;
            }, 0);
            qq(this, false, b, true, false);
            return true;
          }
          return false;
        };
        function Bq(a, b) {
          var c, d2, e, f, g;
          return P(function(h) {
            switch (h.g) {
              case 1:
                if (a.m == uq) return h.return();
                b.severity === 1 && a.C.L++;
                c = true;
                if (!(a.aa && a.i && a.l) || b.code != 3016 && b.code != 3014 && b.code != 3015 && b.code != 3024 && b.code != 3018) {
                  h.B(2);
                  break;
                }
                d2 = Sb();
                if (d2.Ga() === "WEBKIT" && b.code == 3016) return h.return();
                sa(h, 3);
                return G(h, nn(a.l), 5);
              case 5:
                e = h.h;
                c = !e;
                e && (f = tq("mediasourcerecovered"), a.dispatchEvent(f));
                ua(h, 2);
                break;
              case 3:
                va(h), c = true;
              case 2:
                if (!c) return h.return();
                b.severity === 2 && pq(a, false);
                g = tq("error", (/* @__PURE__ */ new Map()).set("detail", b));
                a.dispatchEvent(g);
                g.defaultPrevented && (b.handled = true);
                H(h);
            }
          });
        }
        p.addFont = function(a, b) {
          return Vj(a, b);
        };
        function Qq(a, b, c, d2) {
          d2 = d2 === void 0 ? a : d2;
          a = (/* @__PURE__ */ new Map()).set("detail", {
            schemeIdUri: c.schemeIdUri,
            value: c.value,
            startTime: c.startTime,
            endTime: c.endTime,
            id: c.id,
            timescale: c.timescale,
            eventElement: c.eventElement,
            eventNode: c.eventNode
          });
          d2.dispatchEvent(tq(b, a));
        }
        function Rq(a, b, c, d2) {
          d2 = d2 === void 0 ? false : d2;
          b = (/* @__PURE__ */ new Map()).set("mediaQuality", {
            bandwidth: b.bandwidth,
            audioSamplingRate: b.audioSamplingRate,
            codecs: b.codecs,
            contentType: b.contentType,
            frameRate: b.frameRate,
            height: b.height,
            mimeType: b.mimeType,
            channelsCount: b.channelsCount,
            pixelAspectRatio: b.pixelAspectRatio,
            width: b.width,
            label: b.label,
            roles: b.roles,
            language: b.language
          }).set("position", c);
          a.dispatchEvent(tq(d2 ? "audiotrackchanged" : "mediaqualitychanged", b));
        }
        function Aq(a, b) {
          b = b === void 0 ? true : b;
          if (!a.h.error) return b ? new U(2, 3, 3016) : null;
          var c = a.h.error.code;
          if (!b && c == 1) return null;
          if (b = a.h.error.msExtendedCode) b < 0 && (b += 4294967296), b = b.toString(16);
          return new U(2, 3, 3016, c, b, a.h.error.message);
        }
        function Sq(a, b) {
          var c = tq("keystatuschanged");
          a.dispatchEvent(c);
          var d2 = Object.keys(b);
          d2.length == 1 && d2[0] == "" && (d2 = ["00"], b = {
            "00": b[""]
          });
          var e = d2.length == 1 && d2[0] == "00";
          c = false;
          if (d2.length) {
            d2 = a.keySystem();
            for (var f = kh(a.g.drm.clearKeys), g = function(u, w) {
              u.allowedByKeySystem = true;
              w = t2(w);
              for (var v = w.next(); !v.done; v = w.next()) if (v = v.value, (v = b[e ? "00" : v]) || a.F.L) u.allowedByKeySystem = u.allowedByKeySystem && !!v && !Ei.includes(v);
            }, h = t2(a.i.variants), k2 = h.next(); !k2.done; k2 = h.next()) {
              k2 = k2.value;
              var l = og(k2);
              l = t2(l);
              for (var m = l.next(); !m.done; m = l.next()) {
                m = m.value;
                var n = k2.allowedByKeySystem;
                if (m.keyIds.size) if (m.drmInfos.length && !f.size && a.i.type == "HLS") for (var q = t2(m.drmInfos), r2 = q.next(); !r2.done; r2 = q.next()) r2 = r2.value, r2.keySystem == d2 && (r2.keyIds.size ? g(k2, r2.keyIds) : g(k2, m.keyIds));
                else g(k2, m.keyIds);
                n != k2.allowedByKeySystem && (c = true);
              }
            }
          }
          if (c && ($q(a), !dr(a))) return;
          (c = a.l.u) && !c.allowedByKeySystem && qq(a);
        }
        function er(a, b, c) {
          b > 0 && (a.U() || a.Pj(b));
          b = a.getDuration();
          c < b && (a.U() || a.yb(c));
        }
        function Lr(a, b) {
          P(function(c) {
            if (c.g == 1) return G(c, Promise.resolve(), 2);
            a.m != uq && a.dispatchEvent(b);
            H(c);
          });
        }
        function Gr(a) {
          var b = /* @__PURE__ */ new Set();
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) c = c.value, c.language ? b.add(zc(c.language)) : b.add("und");
          return b;
        }
        function Fr(a) {
          for (var b = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), d2 = 0; d2 < a.length; d2++) {
            var e = a[d2], f = "und", g = [];
            e.language && (f = zc(e.language));
            e.type == "variant" ? g = e.audioRoles : g = e.roles;
            g && g.length || (g = [""]);
            b.has(f) || b.set(f, /* @__PURE__ */ new Set());
            g = t2(g);
            for (var h = g.next(); !h.done; h = g.next()) h = h.value, b.get(f).add(h), e.label && (c.has(f) || c.set(f, /* @__PURE__ */ new Map()), c.get(f).set(h, e.label));
          }
          var k2 = [];
          b.forEach(function(l, m) {
            l = t2(l);
            for (var n = l.next(); !n.done; n = l.next()) {
              n = n.value;
              var q = null;
              c.has(m) && c.get(m).has(n) && (q = c.get(m).get(n));
              k2.push({
                language: m,
                role: n,
                label: q
              });
            }
          });
          return k2;
        }
        p.Da = function() {
          return this.h && this.h.remote ? this.h.remote.state != "disconnected" : false;
        };
        p.isEnded = function() {
          return !this.h || this.h.ended ? true : this.aa && !this.U() && this.h.currentTime >= this.ya().end;
        };
        S("shaka.Player", Y);
        Y.prototype.isEnded = Y.prototype.isEnded;
        Y.prototype.isRemotePlayback = Y.prototype.Da;
        Y.prototype.addFont = Y.prototype.addFont;
        Y.prototype.setVideoContainer = Y.prototype.ji;
        Y.prototype.getFetchedPlaybackInfo = Y.prototype.Nk;
        Y.prototype.getManifestParserFactory = Y.prototype.Vk;
        Y.prototype.getManifest = Y.prototype.qh;
        Y.prototype.retryStreaming = Y.prototype.Xh;
        Y.prototype.setMaxHardwareResolution = Y.prototype.um;
        Y.prototype.addChaptersTrack = Y.prototype.bf;
        Y.prototype.addThumbnailsTrack = Y.prototype.cf;
        Y.prototype.addTextTrackAsync = Y.prototype.be;
        Y.prototype.getStats = Y.prototype.getStats;
        Y.prototype.getBufferedInfo = Y.prototype.cc;
        Y.prototype.getSegmentAvailabilityDuration = Y.prototype.wf;
        Y.prototype.getPresentationStartTimeAsDate = Y.prototype.sh;
        Y.prototype.getPlayheadTimeAsDate = Y.prototype.Zk;
        Y.prototype.setTextTrackVisibility = Y.prototype.Fe;
        Y.prototype.getChaptersAsync = Y.prototype.nh;
        Y.prototype.getChapters = Y.prototype.Dk;
        Y.prototype.getChaptersTracks = Y.prototype.Ek;
        Y.prototype.isTextTrackVisible = Y.prototype.ld;
        Y.prototype.selectVariantsByLabel = Y.prototype.om;
        Y.prototype.selectTextLanguage = Y.prototype.ai;
        Y.prototype.selectAudioLanguage = Y.prototype.Fj;
        Y.prototype.getTextLanguages = Y.prototype.jl;
        Y.prototype.getAudioLanguages = Y.prototype.zk;
        Y.prototype.getTextLanguagesAndRoles = Y.prototype.kl;
        Y.prototype.getAudioLanguagesAndRoles = Y.prototype.Ak;
        Y.prototype.getVideoTracks = Y.prototype.getVideoTracks;
        Y.prototype.selectVideoTrack = Y.prototype.Hj;
        Y.prototype.getAudioTracks = Y.prototype.getAudioTracks;
        Y.prototype.selectAudioTrack = Y.prototype.Gj;
        Y.prototype.selectVariantTrack = Y.prototype.De;
        Y.prototype.selectTextTrack = Y.prototype.fg;
        Y.prototype.getThumbnails = Y.prototype.$i;
        Y.prototype.getAllThumbnails = Y.prototype.yk;
        Y.prototype.getImageTracks = Y.prototype.ph;
        Y.prototype.getTextTracks = Y.prototype.vc;
        Y.prototype.getVariantTracks = Y.prototype.rb;
        Y.prototype.cancelTrickPlay = Y.prototype.zd;
        Y.prototype.trickPlay = Y.prototype.Xc;
        Y.prototype.useTrickPlayTrackIfAvailable = Y.prototype.zi;
        Y.prototype.getPlaybackRate = Y.prototype.Ya;
        Y.prototype.isBuffering = Y.prototype.Bf;
        Y.prototype.getKeyStatuses = Y.prototype.tf;
        Y.prototype.getActiveSessionsMetadata = Y.prototype.mh;
        Y.prototype.getExpiration = Y.prototype.ke;
        Y.prototype.drmInfo = Y.prototype.drmInfo;
        Y.prototype.keySystem = Y.prototype.keySystem;
        Y.prototype.isFullyLoaded = Y.prototype.Cl;
        Y.prototype.goToLive = Y.prototype.yl;
        Y.prototype.seekRange = Y.prototype.ya;
        Y.prototype.isVideoOnly = Y.prototype.Hh;
        Y.prototype.isAudioOnly = Y.prototype.Hd;
        Y.prototype.isInProgress = Y.prototype.kd;
        Y.prototype.isLive = Y.prototype.U;
        Y.prototype.getQueueManager = Y.prototype.uh;
        Y.prototype.getAdManager = Y.prototype.rf;
        Y.prototype.getAssetUri = Y.prototype.ed;
        Y.prototype.getNetworkingEngine = Y.prototype.Lb;
        Y.prototype.getMediaElement = Y.prototype.Yk;
        Y.prototype.getManifestType = Y.prototype.rh;
        Y.prototype.getLoadMode = Y.prototype.Rk;
        Y.prototype.resetConfiguration = Y.prototype.Aj;
        Y.prototype.getBufferFullness = Y.prototype.Wi;
        Y.prototype.getNonDefaultConfiguration = Y.prototype.Zi;
        Y.prototype.getConfigurationForLowLatency = Y.prototype.Hk;
        Y.prototype.getConfiguration = Y.prototype.getConfiguration;
        Y.prototype.configurationForLowLatency = Y.prototype.vk;
        Y.prototype.configure = Y.prototype.configure;
        Y.prototype.releaseAllMutexes = Y.prototype.bm;
        Y.prototype.destroyAllPreloads = Y.prototype.Vg;
        Y.prototype.preload = Y.prototype.preload;
        Y.prototype.detachAndSavePreload = Y.prototype.Si;
        Y.prototype.unloadAndSavePreload = Y.prototype.ym;
        Y.prototype.load = Y.prototype.load;
        Y.prototype.updateStartTime = Y.prototype.Cm;
        Y.prototype.unload = Y.prototype.rc;
        Y.prototype.detach = Y.prototype.detach;
        Y.prototype.attachCanvas = Y.prototype.Gi;
        Y.prototype.attach = Y.prototype.bc;
        Y.probeSupport = function(a) {
          a = a === void 0 ? true : a;
          var b, c, d2, e, f, g, h;
          return P(function(k2) {
            switch (k2.g) {
              case 1:
                b = {};
                if (!a) {
                  k2.B(2);
                  break;
                }
                return G(k2, pi(), 3);
              case 3:
                b = k2.h;
              case 2:
                return c = Ii(), d2 = Ek(), e = Sb(), G(k2, e.tc(), 4);
              case 4:
                return f = k2.h, g = {
                  manifest: c,
                  media: d2,
                  drm: b,
                  hardwareResolution: f
                }, h = wq, h.forEach(function(l, m) {
                  g[m] = l();
                }), k2.return(g);
            }
          });
        };
        Y.isBrowserSupported = xq;
        Y.setQueueManagerFactory = function(a) {
          oq = a;
        };
        Y.setAdManagerFactory = function(a) {
          nq = a;
        };
        Y.registerSupportPlugin = vq;
        Y.prototype.destroy = Y.prototype.destroy;
        var uq = 0, jq = 1, Xq = 2, ar = 3;
        Y.LoadMode = {
          DESTROYED: uq,
          NOT_LOADED: jq,
          MEDIA_SOURCE: Xq,
          SRC_EQUALS: ar
        };
        Y.version = "v4.15.10";
        var Pr = ["4", "15"];
        Xc = new function(a) {
          this.g = a;
          this.i = Yc;
          this.h = Zc;
        }(new Vc(Number(Pr[0]), Number(Pr[1])));
        var wq = /* @__PURE__ */ new Map(), nq = null, oq = null;
        function Qr() {
          this.g = [];
          this.i = this.m = this.l = this.j = this.h = 0;
        }
        function Rr(a) {
          return a.g.length ? a.g.reduce(function(b, c) {
            return b + c;
          }, 0) / a.g.length : 0;
        }
        ;
        function Sr(a, b, c) {
          var d2 = this;
          this.g = a;
          this.h = b;
          this.m = c;
          this.i = false;
          this.j = this.h.getVolume();
          this.l = new Qc();
          this.l.o(this.h, google.ima.AdEvent.Type.PAUSED, function() {
            d2.i = true;
          });
          this.l.o(this.h, google.ima.AdEvent.Type.RESUMED, function() {
            d2.i = false;
          });
        }
        p = Sr.prototype;
        p.needsSkipUI = function() {
          return false;
        };
        p.isClientRendering = function() {
          return true;
        };
        p.hasCustomClick = function() {
          return true;
        };
        p.isUsingAnotherMediaElement = function() {
          return true;
        };
        p.getDuration = function() {
          return this.g.getDuration();
        };
        p.getMinSuggestedDuration = function() {
          return this.g.getMinSuggestedDuration();
        };
        p.getRemainingTime = function() {
          return this.h.getRemainingTime();
        };
        p.isPaused = function() {
          return this.i;
        };
        p.isSkippable = function() {
          return this.g.getSkipTimeOffset() >= 0;
        };
        p.getTimeUntilSkippable = function() {
          var a = this.g.getSkipTimeOffset();
          a = this.getRemainingTime() - a;
          return Math.max(a, 0);
        };
        p.canSkipNow = function() {
          return this.h.getAdSkippableState();
        };
        p.skip = function() {
          return this.h.skip();
        };
        p.pause = function() {
          return this.h.pause();
        };
        p.play = function() {
          return this.h.resume();
        };
        p.getVolume = function() {
          return this.h.getVolume();
        };
        p.setVolume = function(a) {
          this.m.volume = a;
          return this.h.setVolume(a);
        };
        p.isMuted = function() {
          return this.h.getVolume() == 0;
        };
        p.isLinear = function() {
          return this.g.isLinear();
        };
        p.resize = function(a, b) {
          this.h.resize(a, b);
        };
        p.setMuted = function(a) {
          (this.m.muted = a) ? (this.j = this.getVolume(), this.h.setVolume(0)) : this.h.setVolume(this.j);
        };
        p.getSequenceLength = function() {
          var a = this.g.getAdPodInfo();
          return a == null ? 1 : a.getTotalAds();
        };
        p.getPositionInSequence = function() {
          var a = this.g.getAdPodInfo();
          return a == null ? 1 : a.getAdPosition();
        };
        p.getTitle = function() {
          return this.g.getTitle();
        };
        p.getDescription = function() {
          return this.g.getDescription();
        };
        p.getVastMediaBitrate = function() {
          return this.g.getVastMediaBitrate();
        };
        p.getVastMediaHeight = function() {
          return this.g.getVastMediaHeight();
        };
        p.getVastMediaWidth = function() {
          return this.g.getVastMediaWidth();
        };
        p.getVastAdId = function() {
          return "";
        };
        p.getAdId = function() {
          return this.g.getAdId();
        };
        p.getCreativeAdId = function() {
          return this.g.getCreativeAdId();
        };
        p.getAdvertiserName = function() {
          return this.g.getAdvertiserName();
        };
        p.getMediaUrl = function() {
          return this.g.getMediaUrl();
        };
        p.getTimeOffset = function() {
          var a = this.g.getAdPodInfo();
          return a == null ? 0 : a.getTimeOffset();
        };
        p.getPodIndex = function() {
          var a = this.g.getAdPodInfo();
          return a == null ? 0 : a.getPodIndex();
        };
        p.release = function() {
          this.h = this.g = null;
        };
        S("shaka.ads.ClientSideAd", Sr);
        Sr.prototype.release = Sr.prototype.release;
        Sr.prototype.getPodIndex = Sr.prototype.getPodIndex;
        Sr.prototype.getTimeOffset = Sr.prototype.getTimeOffset;
        Sr.prototype.getMediaUrl = Sr.prototype.getMediaUrl;
        Sr.prototype.getAdvertiserName = Sr.prototype.getAdvertiserName;
        Sr.prototype.getCreativeAdId = Sr.prototype.getCreativeAdId;
        Sr.prototype.getAdId = Sr.prototype.getAdId;
        Sr.prototype.getVastAdId = Sr.prototype.getVastAdId;
        Sr.prototype.getVastMediaWidth = Sr.prototype.getVastMediaWidth;
        Sr.prototype.getVastMediaHeight = Sr.prototype.getVastMediaHeight;
        Sr.prototype.getVastMediaBitrate = Sr.prototype.getVastMediaBitrate;
        Sr.prototype.getDescription = Sr.prototype.getDescription;
        Sr.prototype.getTitle = Sr.prototype.getTitle;
        Sr.prototype.getPositionInSequence = Sr.prototype.getPositionInSequence;
        Sr.prototype.getSequenceLength = Sr.prototype.getSequenceLength;
        Sr.prototype.setMuted = Sr.prototype.setMuted;
        Sr.prototype.resize = Sr.prototype.resize;
        Sr.prototype.isLinear = Sr.prototype.isLinear;
        Sr.prototype.isMuted = Sr.prototype.isMuted;
        Sr.prototype.setVolume = Sr.prototype.setVolume;
        Sr.prototype.getVolume = Sr.prototype.getVolume;
        Sr.prototype.play = Sr.prototype.play;
        Sr.prototype.pause = Sr.prototype.pause;
        Sr.prototype.skip = Sr.prototype.skip;
        Sr.prototype.canSkipNow = Sr.prototype.canSkipNow;
        Sr.prototype.getTimeUntilSkippable = Sr.prototype.getTimeUntilSkippable;
        Sr.prototype.isSkippable = Sr.prototype.isSkippable;
        Sr.prototype.isPaused = Sr.prototype.isPaused;
        Sr.prototype.getRemainingTime = Sr.prototype.getRemainingTime;
        Sr.prototype.getMinSuggestedDuration = Sr.prototype.getMinSuggestedDuration;
        Sr.prototype.getDuration = Sr.prototype.getDuration;
        Sr.prototype.isUsingAnotherMediaElement = Sr.prototype.isUsingAnotherMediaElement;
        Sr.prototype.hasCustomClick = Sr.prototype.hasCustomClick;
        Sr.prototype.isClientRendering = Sr.prototype.isClientRendering;
        Sr.prototype.needsSkipUI = Sr.prototype.needsSkipUI;
        function Tr() {
        }
        function Ur(a, b) {
          var c = [];
          a = t2(Sd(a, "Ad"));
          for (var d2 = a.next(); !d2.done; d2 = a.next()) if (d2 = Xd(d2.value, "InLine")) {
            if (d2 = Xd(d2, "Creatives")) {
              d2 = t2(Sd(d2, "Creative"));
              for (var e = d2.next(); !e.done; e = d2.next()) {
                e = e.value;
                var f = Xd(e, "Linear");
                f && Vr(c, b, f);
                if (e = Xd(e, "NonLinearAds")) {
                  e = Sd(e, "NonLinear");
                  e = t2(e);
                  for (var g = e.next(); !g.done; g = e.next()) a: {
                    f = c;
                    var h = b, k2 = g.value, l = Xd(k2, "StaticResource");
                    if (l) g = l.attributes.creativeType;
                    else {
                      l = Xd(k2, "HTMLResource");
                      if (!l) break a;
                      g = "text/html";
                    }
                    if (l = Ud(l)) {
                      g === "text/html" && (l = "data:text/html;charset=UTF-8," + encodeURIComponent(l));
                      var m = $d(k2, "width", fe) || $d(k2, "expandedWidth", fe), n = $d(k2, "height", fe) || $d(k2, "expandedHeight", fe);
                      if (m || n) {
                        var q = null;
                        (k2 = k2.attributes.minSuggestedDuration) && (q = Fd(k2));
                        k2 = 0;
                        h != null && (k2 = h);
                        f.push({
                          id: null,
                          groupId: null,
                          startTime: k2,
                          endTime: null,
                          uri: l,
                          mimeType: g,
                          isSkippable: false,
                          skipOffset: null,
                          skipFor: null,
                          canJump: false,
                          resumeOffset: 0,
                          playoutLimit: q,
                          once: true,
                          pre: h == null,
                          post: h == Infinity,
                          timelineRange: false,
                          loop: false,
                          overlay: {
                            viewport: {
                              x: 0,
                              y: 0
                            },
                            topLeft: {
                              x: 0,
                              y: 0
                            },
                            size: {
                              x: m || 0,
                              y: n || 0
                            }
                          },
                          displayOnBackground: false,
                          currentVideo: null,
                          background: null
                        });
                      }
                    }
                  }
                }
              }
            }
          }
          return c;
        }
        function Vr(a, b, c) {
          var d2 = 0;
          b != null && (d2 = b);
          var e = null;
          c.attributes.skipoffset && (e = Fd(c.attributes.skipoffset), isNaN(e) && (e = null));
          if (c = Xd(c, "MediaFiles")) {
            var f = Sd(c, "MediaFile");
            c = f;
            f = f.filter(function(h) {
              return h.attributes.delivery == "streaming";
            });
            f.length && (c = f);
            c = c.sort(function(h, k2) {
              return (parseInt(k2.attributes.height, 10) || 0) - (parseInt(h.attributes.height, 10) || 0);
            });
            c = t2(c);
            for (f = c.next(); !f.done; f = c.next()) if (f = f.value, !f.attributes.apiFramework) {
              var g = Ud(f);
              if (g) {
                a.push({
                  id: null,
                  groupId: null,
                  startTime: d2,
                  endTime: null,
                  uri: g,
                  mimeType: f.attributes.type || null,
                  isSkippable: e != null,
                  skipOffset: e,
                  skipFor: null,
                  canJump: false,
                  resumeOffset: 0,
                  playoutLimit: null,
                  once: true,
                  pre: b == null,
                  post: b == Infinity,
                  timelineRange: false,
                  loop: false,
                  overlay: null,
                  displayOnBackground: false,
                  currentVideo: null,
                  background: null
                });
                break;
              }
            }
          }
        }
        function Wr(a) {
          var b = [];
          a = t2(Sd(a, "vmap:AdBreak"));
          for (var c = a.next(); !c.done; c = a.next()) {
            var d2 = c.value, e = d2.attributes.timeOffset;
            e && (c = null, e == "start" ? c = null : e == "end" ? c = Infinity : c = Fd(e), (d2 = Xd(d2, "vmap:AdSource")) && (d2 = Xd(d2, "vmap:AdTagURI")) && (d2 = Td(d2)) && b.push({
              time: c,
              uri: d2
            }));
          }
          return b;
        }
        S("shaka.ads.Utils", Tr);
        Tr.ADS_LOADED = "ads-loaded";
        Tr.AD_STARTED = "ad-started";
        Tr.AD_FIRST_QUARTILE = "ad-first-quartile";
        Tr.AD_MIDPOINT = "ad-midpoint";
        Tr.AD_THIRD_QUARTILE = "ad-third-quartile";
        Tr.AD_COMPLETE = "ad-complete";
        Tr.AD_STOPPED = "ad-stopped";
        Tr.AD_SKIPPED = "ad-skipped";
        Tr.AD_VOLUME_CHANGED = "ad-volume-changed";
        Tr.AD_MUTED = "ad-muted";
        Tr.AD_PAUSED = "ad-paused";
        Tr.AD_RESUMED = "ad-resumed";
        Tr.AD_SKIP_STATE_CHANGED = "ad-skip-state-changed";
        Tr.CUEPOINTS_CHANGED = "ad-cue-points-changed";
        Tr.IMA_AD_MANAGER_LOADED = "ima-ad-manager-loaded";
        Tr.IMA_STREAM_MANAGER_LOADED = "ima-stream-manager-loaded";
        Tr.AD_CLICKED = "ad-clicked";
        Tr.AD_PROGRESS = "ad-progress";
        Tr.AD_BUFFERING = "ad-buffering";
        Tr.AD_IMPRESSION = "ad-impression";
        Tr.AD_DURATION_CHANGED = "ad-duration-changed";
        Tr.AD_CLOSED = "ad-closed";
        Tr.AD_LOADED = "ad-loaded";
        Tr.ALL_ADS_COMPLETED = "all-ads-completed";
        Tr.AD_LINEAR_CHANGED = "ad-linear-changed";
        Tr.AD_METADATA = "ad-metadata";
        Tr.AD_RECOVERABLE_ERROR = "ad-recoverable-error";
        Tr.AD_ERROR = "ad-error";
        Tr.AD_BREAK_READY = "ad-break-ready";
        Tr.AD_INTERACTION = "ad-interaction";
        Tr.AD_CONTENT_PAUSE_REQUESTED = "ad-content-pause-requested";
        Tr.AD_CONTENT_RESUME_REQUESTED = "ad-content-resume-requested";
        Tr.AD_CONTENT_ATTACH_REQUESTED = "ad-content-attach-requested";
        function Xr(a, b, c, d2, e) {
          var f = this;
          this.A = a;
          this.i = b;
          this.G = false;
          this.C = this.u = null;
          this.H = NaN;
          this.l = e;
          this.j = null;
          this.h = new Qc();
          google.ima.settings.setLocale(c);
          google.ima.settings.setDisableCustomPlaybackForIOS10Plus(true);
          this.F = new google.ima.AdDisplayContainer(this.A, this.i);
          this.F.initialize();
          this.m = new google.ima.AdsLoader(this.F);
          this.m.getSettings().setPlayerType("shaka-player");
          this.m.getSettings().setPlayerVersion("v4.15.10");
          this.g = null;
          this.D = d2 || new google.ima.AdsRenderingSettings();
          this.h.o(this.m, google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, function(g) {
            Yr(f, g);
          });
          this.h.o(this.m, google.ima.AdErrorEvent.Type.AD_ERROR, function(g) {
            Zr(f, g);
          });
          this.h.o(this.i, "ended", function() {
            f.m.contentComplete();
          });
          this.h.qa(this.i, "play", function() {
            f.G = true;
          });
        }
        Xr.prototype.configure = function(a) {
          this.u = a;
        };
        Xr.prototype.stop = function() {
          this.g && this.g.stop();
          this.A && Sj(this.A);
        };
        Xr.prototype.release = function() {
          this.stop();
          this.C && this.C.disconnect();
          this.h && this.h.release();
          this.g && this.g.destroy();
          this.m.destroy();
          this.F.destroy();
        };
        function Zr(a, b) {
          b.getError();
          b = (/* @__PURE__ */ new Map()).set("originalEvent", b);
          a.l(new T("ad-error", b));
          $r(a, null);
          a.l(new T("ad-cue-points-changed", (/* @__PURE__ */ new Map()).set("cuepoints", [])));
        }
        function Yr(a, b) {
          a.l(new T("ads-loaded", (/* @__PURE__ */ new Map()).set("loadTime", Date.now() / 1e3 - a.H)));
          if (a.u.customPlayheadTracker) {
            var c = {
              currentTime: a.i.currentTime
            };
            a.g = b.getAdsManager(c, a.D);
            a.i.muted ? a.g.setVolume(0) : a.g.setVolume(a.i.volume);
            a.h.o(a.i, "timeupdate", function() {
              a.i.duration && (c.currentTime = a.i.currentTime);
            });
            a.h.o(a.i, "volumechange", function() {
              a.j && (a.j.setVolume(a.i.volume), a.i.muted && a.j.setMuted(true));
            });
          } else a.g = b.getAdsManager(a.i, a.D);
          a.l(new T("ima-ad-manager-loaded", (/* @__PURE__ */ new Map()).set("imaAdManager", a.g)));
          var d2 = a.g.getCuePoints();
          if (d2.length) {
            b = [];
            d2 = t2(d2);
            for (var e = d2.next(); !e.done; e = d2.next()) b.push({
              start: e.value,
              end: null
            });
            a.l(new T("ad-cue-points-changed", (/* @__PURE__ */ new Map()).set("cuepoints", b)));
          }
          as(a);
          try {
            a.g.init(a.i.offsetWidth, a.i.offsetHeight), a.h.o(a.i, "loadeddata", function() {
              a.g.resize(a.i.offsetWidth, a.i.offsetHeight);
            }), "ResizeObserver" in window7 ? (a.C = new ResizeObserver(function() {
              a.g.resize(a.i.offsetWidth, a.i.offsetHeight);
            }), a.C.observe(a.i)) : a.h.o(document, "fullscreenchange", function() {
              a.g.resize(a.i.offsetWidth, a.i.offsetHeight);
            }), a.G || a.u.skipPlayDetection ? a.g.start() : a.h.qa(a.i, "play", function() {
              a.G = true;
              a.g.start();
            });
          } catch (f) {
            $r(a, null);
          }
        }
        function as(a) {
          function b(c, d2) {
            c = (/* @__PURE__ */ new Map()).set("originalEvent", c);
            a.l(new T(d2, c));
          }
          a.h.o(a.g, google.ima.AdErrorEvent.Type.AD_ERROR, function(c) {
            Zr(a, c);
          });
          a.h.o(a.g, google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, function(c) {
            bs(a, c);
          });
          a.h.o(a.g, google.ima.AdEvent.Type.STARTED, function(c) {
            bs(a, c);
          });
          a.h.o(a.g, google.ima.AdEvent.Type.FIRST_QUARTILE, function(c) {
            b(c, "ad-first-quartile");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.MIDPOINT, function(c) {
            b(c, "ad-midpoint");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.THIRD_QUARTILE, function(c) {
            b(c, "ad-third-quartile");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.COMPLETE, function(c) {
            b(c, "ad-complete");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, function(c) {
            $r(a, c);
          });
          a.h.o(a.g, google.ima.AdEvent.Type.ALL_ADS_COMPLETED, function(c) {
            $r(a, c);
          });
          a.h.o(a.g, google.ima.AdEvent.Type.SKIPPED, function(c) {
            b(c, "ad-skipped");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.VOLUME_CHANGED, function(c) {
            b(c, "ad-volume-changed");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.VOLUME_MUTED, function(c) {
            b(c, "ad-muted");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.PAUSED, function(c) {
            a.j && (a.j.i = true, b(c, "ad-paused"));
          });
          a.h.o(a.g, google.ima.AdEvent.Type.RESUMED, function(c) {
            a.j && (a.j.i = false, b(c, "ad-resumed"));
          });
          a.h.o(a.g, google.ima.AdEvent.Type.SKIPPABLE_STATE_CHANGED, function(c) {
            a.j && b(c, "ad-skip-state-changed");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.CLICK, function(c) {
            b(c, "ad-clicked");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.AD_PROGRESS, function(c) {
            b(c, "ad-progress");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.AD_BUFFERING, function(c) {
            b(c, "ad-buffering");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.IMPRESSION, function(c) {
            b(c, "ad-impression");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.DURATION_CHANGE, function(c) {
            b(c, "ad-duration-changed");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.USER_CLOSE, function(c) {
            b(c, "ad-closed");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.LOADED, function(c) {
            b(c, "ad-loaded");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.ALL_ADS_COMPLETED, function(c) {
            b(c, "all-ads-completed");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.LINEAR_CHANGED, function(c) {
            b(c, "ad-linear-changed");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.AD_METADATA, function(c) {
            b(c, "ad-metadata");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.LOG, function(c) {
            b(c, "ad-recoverable-error");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.AD_BREAK_READY, function(c) {
            b(c, "ad-break-ready");
          });
          a.h.o(a.g, google.ima.AdEvent.Type.INTERACTION, function(c) {
            b(c, "ad-interaction");
          });
        }
        function bs(a, b) {
          var c = b.getAd();
          c ? (a.j = new Sr(c, a.g, a.i), b.type != google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED || a.u.supportsMultipleMediaElements || a.l(new T("ad-content-pause-requested")), b = (/* @__PURE__ */ new Map()).set("ad", a.j).set("sdkAdObject", c).set("originalEvent", b), a.l(new T("ad-started", b)), a.j.isLinear() && (a.A.setAttribute("ad-active", "true"), a.u.customPlayheadTracker || a.i.pause(), a.i.muted ? (b = a.j, b.j = a.i.volume, b.h.setVolume(0)) : a.j.setVolume(a.i.volume))) : bb("The IMA SDK fired a " + b.type + " event with no associated ad. Unable to play ad!");
        }
        function $r(a, b) {
          b && b.type == google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED && !a.u.supportsMultipleMediaElements && a.l(new T("ad-content-resume-requested"));
          a.l(new T("ad-stopped", (/* @__PURE__ */ new Map()).set("originalEvent", b)));
          a.j && a.j.isLinear() && (a.A.removeAttribute("ad-active"), a.u.customPlayheadTracker || a.i.ended || a.i.play());
        }
        ;
        function cs(a, b, c, d2, e, f) {
          this.g = a;
          this.i = b;
          this.j = (this.h = b.isSkippable) ? b.skipOffset || 0 : b.skipOffset;
          this.l = b.skipFor;
          this.C = c;
          this.u = d2;
          this.m = e;
          this.A = f;
          this.D = b.overlay;
        }
        p = cs.prototype;
        p.needsSkipUI = function() {
          return true;
        };
        p.isClientRendering = function() {
          return true;
        };
        p.hasCustomClick = function() {
          return false;
        };
        p.isUsingAnotherMediaElement = function() {
          return this.A;
        };
        p.getDuration = function() {
          var a = this.g.duration;
          return isNaN(a) ? -1 : a;
        };
        p.getMinSuggestedDuration = function() {
          return this.getDuration();
        };
        p.getRemainingTime = function() {
          var a = this.g.duration;
          return isNaN(a) ? -1 : a - this.g.currentTime;
        };
        p.isPaused = function() {
          return this.g.paused;
        };
        p.isSkippable = function() {
          return this.h && this.l != null ? this.getDuration() - this.getRemainingTime() < this.j + this.l : this.h;
        };
        p.getTimeUntilSkippable = function() {
          if (this.isSkippable()) {
            var a = this.getRemainingTime() + this.j - this.getDuration();
            return Math.max(a, 0);
          }
          return Math.max(this.getRemainingTime(), 0);
        };
        p.canSkipNow = function() {
          return this.h && this.getTimeUntilSkippable() == 0;
        };
        p.skip = function() {
          this.canSkipNow() && this.C();
        };
        p.pause = function() {
          return this.g.pause();
        };
        p.play = function() {
          return this.g.play();
        };
        p.getVolume = function() {
          return this.g.volume;
        };
        p.setVolume = function(a) {
          this.g.volume = a;
        };
        p.isMuted = function() {
          return this.g.muted;
        };
        p.isLinear = function() {
          return this.D == null;
        };
        p.resize = function() {
        };
        p.setMuted = function(a) {
          this.g.muted = a;
        };
        p.getSequenceLength = function() {
          return this.u;
        };
        p.getPositionInSequence = function() {
          return this.m;
        };
        p.getTitle = function() {
          return "";
        };
        p.getDescription = function() {
          return "";
        };
        p.getVastMediaBitrate = function() {
          return 0;
        };
        p.getVastMediaHeight = function() {
          return 0;
        };
        p.getVastMediaWidth = function() {
          return 0;
        };
        p.getVastAdId = function() {
          return "";
        };
        p.getAdId = function() {
          return this.i.id || "";
        };
        p.getCreativeAdId = function() {
          return "";
        };
        p.getAdvertiserName = function() {
          return "";
        };
        p.getMediaUrl = function() {
          return this.i.uri;
        };
        p.getTimeOffset = function() {
          return 0;
        };
        p.getPodIndex = function() {
          return 0;
        };
        p.release = function() {
          this.g = null;
        };
        S("shaka.ads.InterstitialAd", cs);
        cs.prototype.release = cs.prototype.release;
        cs.prototype.getPodIndex = cs.prototype.getPodIndex;
        cs.prototype.getTimeOffset = cs.prototype.getTimeOffset;
        cs.prototype.getMediaUrl = cs.prototype.getMediaUrl;
        cs.prototype.getAdvertiserName = cs.prototype.getAdvertiserName;
        cs.prototype.getCreativeAdId = cs.prototype.getCreativeAdId;
        cs.prototype.getAdId = cs.prototype.getAdId;
        cs.prototype.getVastAdId = cs.prototype.getVastAdId;
        cs.prototype.getVastMediaWidth = cs.prototype.getVastMediaWidth;
        cs.prototype.getVastMediaHeight = cs.prototype.getVastMediaHeight;
        cs.prototype.getVastMediaBitrate = cs.prototype.getVastMediaBitrate;
        cs.prototype.getDescription = cs.prototype.getDescription;
        cs.prototype.getTitle = cs.prototype.getTitle;
        cs.prototype.getPositionInSequence = cs.prototype.getPositionInSequence;
        cs.prototype.getSequenceLength = cs.prototype.getSequenceLength;
        cs.prototype.setMuted = cs.prototype.setMuted;
        cs.prototype.resize = cs.prototype.resize;
        cs.prototype.isLinear = cs.prototype.isLinear;
        cs.prototype.isMuted = cs.prototype.isMuted;
        cs.prototype.setVolume = cs.prototype.setVolume;
        cs.prototype.getVolume = cs.prototype.getVolume;
        cs.prototype.play = cs.prototype.play;
        cs.prototype.pause = cs.prototype.pause;
        cs.prototype.skip = cs.prototype.skip;
        cs.prototype.canSkipNow = cs.prototype.canSkipNow;
        cs.prototype.getTimeUntilSkippable = cs.prototype.getTimeUntilSkippable;
        cs.prototype.isSkippable = cs.prototype.isSkippable;
        cs.prototype.isPaused = cs.prototype.isPaused;
        cs.prototype.getRemainingTime = cs.prototype.getRemainingTime;
        cs.prototype.getMinSuggestedDuration = cs.prototype.getMinSuggestedDuration;
        cs.prototype.getDuration = cs.prototype.getDuration;
        cs.prototype.isUsingAnotherMediaElement = cs.prototype.isUsingAnotherMediaElement;
        cs.prototype.hasCustomClick = cs.prototype.hasCustomClick;
        cs.prototype.isClientRendering = cs.prototype.isClientRendering;
        cs.prototype.needsSkipUI = cs.prototype.needsSkipUI;
        function ds(a, b, c) {
          this.g = a;
          this.j = b;
          this.h = c;
          this.i = a.overlay == null;
        }
        p = ds.prototype;
        p.needsSkipUI = function() {
          return true;
        };
        p.isClientRendering = function() {
          return true;
        };
        p.hasCustomClick = function() {
          return false;
        };
        p.isUsingAnotherMediaElement = function() {
          return false;
        };
        p.getDuration = function() {
          return -1;
        };
        p.getMinSuggestedDuration = function() {
          return this.getDuration();
        };
        p.getRemainingTime = function() {
          return -1;
        };
        p.isPaused = function() {
          return false;
        };
        p.isSkippable = function() {
          return false;
        };
        p.getTimeUntilSkippable = function() {
          return 0;
        };
        p.canSkipNow = function() {
          return false;
        };
        p.skip = function() {
        };
        p.pause = function() {
        };
        p.play = function() {
        };
        p.getVolume = function() {
          return 1;
        };
        p.setVolume = function() {
        };
        p.isMuted = function() {
          return false;
        };
        p.isLinear = function() {
          return this.i;
        };
        p.resize = function() {
        };
        p.setMuted = function() {
        };
        p.getSequenceLength = function() {
          return this.j;
        };
        p.getPositionInSequence = function() {
          return this.h;
        };
        p.getTitle = function() {
          return "";
        };
        p.getDescription = function() {
          return "";
        };
        p.getVastMediaBitrate = function() {
          return 0;
        };
        p.getVastMediaHeight = function() {
          return 0;
        };
        p.getVastMediaWidth = function() {
          return 0;
        };
        p.getVastAdId = function() {
          return "";
        };
        p.getAdId = function() {
          return this.g.id || "";
        };
        p.getCreativeAdId = function() {
          return "";
        };
        p.getAdvertiserName = function() {
          return "";
        };
        p.getMediaUrl = function() {
          return this.g.uri;
        };
        p.getTimeOffset = function() {
          return 0;
        };
        p.getPodIndex = function() {
          return 0;
        };
        p.release = function() {
        };
        S("shaka.ads.InterstitialStaticAd", ds);
        ds.prototype.release = ds.prototype.release;
        ds.prototype.getPodIndex = ds.prototype.getPodIndex;
        ds.prototype.getTimeOffset = ds.prototype.getTimeOffset;
        ds.prototype.getMediaUrl = ds.prototype.getMediaUrl;
        ds.prototype.getAdvertiserName = ds.prototype.getAdvertiserName;
        ds.prototype.getCreativeAdId = ds.prototype.getCreativeAdId;
        ds.prototype.getAdId = ds.prototype.getAdId;
        ds.prototype.getVastAdId = ds.prototype.getVastAdId;
        ds.prototype.getVastMediaWidth = ds.prototype.getVastMediaWidth;
        ds.prototype.getVastMediaHeight = ds.prototype.getVastMediaHeight;
        ds.prototype.getVastMediaBitrate = ds.prototype.getVastMediaBitrate;
        ds.prototype.getDescription = ds.prototype.getDescription;
        ds.prototype.getTitle = ds.prototype.getTitle;
        ds.prototype.getPositionInSequence = ds.prototype.getPositionInSequence;
        ds.prototype.getSequenceLength = ds.prototype.getSequenceLength;
        ds.prototype.setMuted = ds.prototype.setMuted;
        ds.prototype.resize = ds.prototype.resize;
        ds.prototype.isLinear = ds.prototype.isLinear;
        ds.prototype.isMuted = ds.prototype.isMuted;
        ds.prototype.setVolume = ds.prototype.setVolume;
        ds.prototype.getVolume = ds.prototype.getVolume;
        ds.prototype.play = ds.prototype.play;
        ds.prototype.pause = ds.prototype.pause;
        ds.prototype.skip = ds.prototype.skip;
        ds.prototype.canSkipNow = ds.prototype.canSkipNow;
        ds.prototype.getTimeUntilSkippable = ds.prototype.getTimeUntilSkippable;
        ds.prototype.isSkippable = ds.prototype.isSkippable;
        ds.prototype.isPaused = ds.prototype.isPaused;
        ds.prototype.getRemainingTime = ds.prototype.getRemainingTime;
        ds.prototype.getMinSuggestedDuration = ds.prototype.getMinSuggestedDuration;
        ds.prototype.getDuration = ds.prototype.getDuration;
        ds.prototype.isUsingAnotherMediaElement = ds.prototype.isUsingAnotherMediaElement;
        ds.prototype.hasCustomClick = ds.prototype.hasCustomClick;
        ds.prototype.isClientRendering = ds.prototype.isClientRendering;
        ds.prototype.needsSkipUI = ds.prototype.needsSkipUI;
        function es(a, b, c, d2) {
          var e = this;
          this.M = null;
          this.D = a;
          this.F = b;
          this.g = c;
          this.H = null;
          this.C = true;
          this.h = this.g;
          this.i = d2;
          this.S = /* @__PURE__ */ new Set();
          this.I = /* @__PURE__ */ new Set();
          this.G = /* @__PURE__ */ new Map();
          this.L = /* @__PURE__ */ new Map();
          this.j = new Y();
          fs(this);
          this.J = new Qc();
          this.l = new Qc();
          this.K = false;
          this.$ = this.u = this.A = this.m = null;
          this.aa = false;
          this.P = -1;
          this.Z = function() {
            if (!e.K && e.m && !e.F.Da()) {
              e.m = e.g.currentTime;
              var f = gs(e);
              f && hs(e, f, 1, 1, Date.now());
            }
          };
          this.V = function() {
            if (!(e.K || e.m || e.F.Da())) {
              e.m = e.g.currentTime;
              var f = gs(e, true);
              f || (f = gs(e));
              f && hs(e, f, 1, 1, Date.now());
            }
          };
          this.ea = function() {
            if (!e.K && e.m && !e.F.Da()) {
              var f = e.g.currentTime;
              e.A && !e.A.pre && !e.A.post && f < (e.A.endTime || e.A.startTime) && (e.A = null);
            }
          };
          this.R = new Cf(this.Z);
          this.O = new Cf(function() {
            var f, g, h, k2, l, m, n, q, r2, u, w;
            return P(function(v) {
              switch (v.g) {
                case 1:
                  if (!e.I.size || e.m == null) {
                    v.B(0);
                    break;
                  }
                  f = e.F.m;
                  if (f == uq || f == jq) return v.return();
                  g = false;
                  h = Array.from(e.I);
                  k2 = e.F.ya();
                  l = t2(h);
                  m = l.next();
                case 3:
                  if (m.done) {
                    v.B(5);
                    break;
                  }
                  n = m.value;
                  if (n == e.A) {
                    v.B(4);
                    break;
                  }
                  q = n.endTime || n.startTime;
                  if (!(k2.start - q >= 1)) {
                    r2 = n.startTime - e.m;
                    r2 > 0 && r2 <= 10 && (!e.G.has(n) && is(n) && e.G.set(n, e.j.preload(n.uri, null, n.mimeType || void 0)), js(e, n));
                    v.B(4);
                    break;
                  }
                  if (!e.G.has(n)) {
                    v.B(7);
                    break;
                  }
                  return G(v, e.G.get(n), 8);
                case 8:
                  (u = v.h) && u.destroy(), e.G.delete(n);
                case 7:
                  ks(e, n), w = JSON.stringify(n), e.S.has(w) && e.S.delete(w), e.I.delete(n), ls(e), n.overlay || (g = true);
                case 4:
                  m = l.next();
                  v.B(3);
                  break;
                case 5:
                  g && ms(e), H(v);
              }
            });
          });
          this.configure(this.F.getConfiguration().ads);
        }
        p = es.prototype;
        p.configure = function(a) {
          this.M = a;
          ns(this);
        };
        function os(a) {
          if (!a.aa && a.I.size) {
            a.J.o(a.g, "playing", a.V);
            a.J.o(a.g, "timeupdate", a.V);
            a.J.o(a.g, "seeked", a.ea);
            a.J.o(a.g, "ended", a.Z);
            if ("requestVideoFrameCallback" in a.g && !ps()) {
              var b = a.g, c = function() {
                a.P != -1 && (a.Z(), a.P != -1 && (a.P = b.requestVideoFrameCallback(c)));
              };
              a.P = b.requestVideoFrameCallback(c);
            } else a.R.za(0.025);
            a.O && a.O.za(1);
            a.aa = true;
          }
        }
        function ls(a) {
          a.aa && !a.I.size && (a.J.Ea(a.g, "playing", a.V), a.J.Ea(a.g, "timeupdate", a.V), a.J.Ea(a.g, "seeked", a.ea), a.J.Ea(a.g, "ended", a.Z), a.P != -1 && (a.g.cancelVideoFrameCallback(a.P), a.P = -1), a.R && a.R.stop(), a.O && a.O.stop(), a.aa = false);
        }
        function ns(a) {
          if (a.D && a.M && !a.K) {
            var b = a.M.supportsMultipleMediaElements, c = a.g;
            c.webkitPresentationMode && c.webkitPresentationMode !== "inline" && (b = false);
            a.C == b && (a.C = !b, a.C ? (a.h = a.g, a.H && (a.H.parentElement && a.D.removeChild(a.H), a.H = null)) : (a.H || (b = document.createElement(a.g.tagName), b.autoplay = true, b.style.position = "absolute", b.style.top = "0", b.style.left = "0", b.style.width = "100%", b.style.height = "100%", b.style.display = "none", b.setAttribute("playsinline", ""), a.H = b), a.h = a.H));
          } else a.C = true;
        }
        p.stop = function() {
          this.l && this.l.Ta();
          this.S.clear();
          this.I.clear();
          this.j.Vg();
          if (this.G.size) {
            var a = Array.from(this.G.values());
            a = t2(a);
            for (var b = a.next(); !b.done; b = a.next()) (b = b.value) && b.then(function(c) {
              c && c.destroy();
            });
          }
          this.G.clear();
          if (this.L.size) for (a = Array.from(this.L.keys()), a = t2(a), b = a.next(); !b.done; b = a.next()) ks(this, b.value);
          this.L.clear();
          this.j.detach();
          this.K = false;
          this.A = this.m = null;
          this.C = true;
          this.h = this.g;
          this.H = null;
          qs(this);
          ls(this);
          this.D && Sj(this.D);
          this.u && (this.u.stop(), this.u = null);
        };
        p.release = function() {
          this.stop();
          this.J && this.J.release();
          this.l && this.l.release();
          this.R && (this.R.stop(), this.R = null);
          this.O && (this.O.stop(), this.O = null);
          this.j.destroy();
        };
        p.Vb = function() {
          return this.j;
        };
        function rs(a, b) {
          var c;
          P(function(d2) {
            if (d2.g == 1) return fs(a), G(d2, ss(a, b), 2);
            c = d2.h;
            c.length ? ts2(a, c) : bb("Unsupported HLS interstitial", b);
            H(d2);
          });
        }
        function us(a, b) {
          var c = Xd(b.eventNode, "OverlayEvent"), d2 = c.attributes.uri, e = c.attributes.mimeType, f = c.attributes.loop == "true", g = $d(c, "z", fe);
          if (d2 && g != 0) {
            var h = null, k2 = Xd(c, "Background");
            if (k2) {
              var l = k2.attributes.uri;
              l ? h = "center / contain no-repeat url('" + l + "')" : h = Ud(k2);
            }
            k2 = 1920;
            l = 1080;
            var m = Xd(c, "Viewport");
            if (m) {
              k2 = $d(m, "x", fe);
              if (k2 == null) return;
              l = $d(m, "y", fe);
              if (l == null) return;
            }
            var n = {
              viewport: {
                x: k2,
                y: l
              },
              topLeft: {
                x: 0,
                y: 0
              },
              size: {
                x: k2,
                y: l
              }
            }, q = Xd(c, "Overlay");
            if (m && q) {
              var r2 = Xd(q, "TopLeft"), u = Xd(q, "Size");
              if (r2 && u) {
                q = $d(r2, "x", fe);
                if (q == null) return;
                r2 = $d(r2, "y", fe);
                if (r2 == null) return;
                var w = $d(u, "x", fe);
                if (w == null) return;
                u = $d(u, "y", fe);
                if (u == null) return;
                n.topLeft.x = q;
                n.topLeft.y = r2;
                n.size.x = w;
                n.size.y = u;
              }
            }
            q = null;
            c = Xd(c, "Squeeze");
            if (m && c && (u = Xd(c, "TopLeft"), c = Xd(c, "Size"), u && c)) {
              m = $d(u, "x", fe);
              if (m == null) return;
              q = $d(u, "y", fe);
              if (q == null) return;
              u = $d(c, "x", fe);
              if (u == null) return;
              c = $d(c, "y", fe);
              if (c == null) return;
              q = {
                viewport: {
                  x: k2,
                  y: l
                },
                topLeft: {
                  x: m,
                  y: q
                },
                size: {
                  x: u,
                  y: c
                }
              };
            }
            ts2(a, [{
              id: b.id,
              groupId: null,
              startTime: b.startTime,
              endTime: b.endTime,
              uri: d2,
              mimeType: e,
              isSkippable: false,
              skipOffset: null,
              skipFor: null,
              canJump: true,
              resumeOffset: null,
              playoutLimit: null,
              once: false,
              pre: false,
              post: false,
              timelineRange: true,
              loop: f,
              overlay: n,
              displayOnBackground: g == -1,
              currentVideo: q,
              background: h
            }]);
          }
        }
        p.addAdUrlInterstitial = function(a) {
          var b = this, c, d2, e, f, g, h, k2, l, m;
          return P(function(n) {
            if (n.g == 1) return c = {
              type: 12
            }, G(n, vs(b, a, c), 2);
            if (n.g != 3) {
              d2 = n.h;
              e = Kd(d2, "VAST,vmap:VMAP");
              if (!e) throw new U(2, 10, 10007);
              f = [];
              if (e.tagName == "VAST") return f = Ur(e, b.m), n.B(3);
              if (e.tagName != "vmap:VMAP") return n.B(3);
              g = function(q) {
                var r2, u;
                return P(function(w) {
                  if (w.g == 1) return G(w, vs(b, q.uri, c), 2);
                  r2 = w.h;
                  u = Kd(r2, "VAST");
                  if (!u) throw new U(2, 10, 10007);
                  f.push.apply(f, x(Ur(u, q.time)));
                  H(w);
                });
              };
              h = [];
              k2 = t2(Wr(e));
              for (l = k2.next(); !l.done; l = k2.next()) m = l.value, h.push(g(m));
              return h.length ? G(n, Promise.all(h), 3) : n.B(3);
            }
            ts2(b, f);
            H(n);
          });
        };
        function ts2(a, b) {
          var c, d2, e, f, g, h, k2, l;
          P(function(m) {
            switch (m.g) {
              case 1:
                c = false, d2 = t2(b), e = d2.next();
              case 2:
                if (e.done) {
                  m.B(4);
                  break;
                }
                f = e.value;
                if (!f.uri) {
                  bb("Missing URL in interstitial", f);
                  m.B(3);
                  break;
                }
                if (f.mimeType) {
                  m.B(5);
                  break;
                }
                sa(m, 6);
                g = a.j.Lb();
                return G(m, Jo(f.uri, g, a.F.getConfiguration().streaming.retryParameters), 8);
              case 8:
                f.mimeType = m.h;
                ua(m, 5);
                break;
              case 6:
                va(m);
              case 5:
                h = f.id || JSON.stringify(f);
                if (a.S.has(h)) {
                  m.B(3);
                  break;
                }
                f.loop && !f.overlay && bb("Loop is only supported in overlay interstitials", f);
                f.overlay || (c = true);
                a.S.add(h);
                a.I.add(f);
                k2 = false;
                f.pre && a.m == null ? k2 = true : f.startTime != 0 || f.canJump ? a.m != null && (l = f.startTime - a.m, l > 0 && l <= 10 && (k2 = true)) : k2 = true;
                k2 && (!a.G.has(f) && is(f) && a.G.set(f, a.j.preload(f.uri, null, f.mimeType || void 0)), js(a, f));
              case 3:
                e = d2.next();
                m.B(2);
                break;
              case 4:
                c && ms(a), os(a), H(m);
            }
          });
        }
        function gs(a, b, c) {
          b = b === void 0 ? false : b;
          c = c === void 0 ? null : c;
          var d2 = 0, e = null;
          if (a.I.size && a.m != null) {
            var f = a.g.ended, g = Array.from(a.I).sort(function(n, q) {
              return q.startTime - n.startTime;
            }), h = g;
            h = b ? g.filter(function(n) {
              return n.pre;
            }) : f ? g.filter(function(n) {
              return n.post;
            }) : g.filter(function(n) {
              return !n.pre && !n.post;
            });
            g = t2(h);
            for (h = g.next(); !h.done; h = g.next()) {
              h = h.value;
              var k2 = false;
              if (b) k2 = h.pre;
              else if (f) k2 = h.post;
              else if (!h.pre && !h.post) {
                var l = a.m - Math.round(h.startTime * 1e3) / 1e3, m = 1;
                a.M.allowStartInMiddleOfInterstitial && h.endTime && h.endTime != Infinity && (m = h.endTime - h.startTime);
                (l > 0 || l == 0 && a.m == 0) && (l <= m || !h.canJump) && (k2 = c == null && a.A && !a.A.pre && !a.A.post && a.A.startTime >= h.startTime ? false : true);
              }
              k2 && (!a.A || h.startTime >= a.A.startTime) && (d2 == (c || 0) ? e = h : e && !h.canJump && Math.round(h.startTime * 1e3) / 1e3 - Math.round(e.startTime * 1e3) / 1e3 > 1e-3 && (e = h, d2 = 0), d2++);
            }
          }
          return e;
        }
        function hs(a, b, c, d2, e, f) {
          f = f === void 0 ? 0 : f;
          a.A = b;
          ns(a);
          a.C || !a.D || a.h.parentElement || a.D.appendChild(a.h);
          d2 == 1 && c == 1 && (c = Array.from(a.I).filter(function(g) {
            return b.pre ? g.pre == b.pre : b.post ? g.post == b.post : Math.abs(g.startTime - b.startTime) < 1e-3;
          }).length);
          b.once && (f++, a.I.delete(b), ls(a), b.overlay || ms(a));
          b.mimeType && (b.mimeType.startsWith("image/") || b.mimeType === "text/html") ? b.overlay ? ws(a, b, c, d2, f) : bb("Unsupported interstitial", b) : a.C && b.overlay ? bb("Unsupported interstitial", b) : xs(a, b, c, d2, e, f);
        }
        function ws(a, b, c, d2, e) {
          function f() {
            a.u && (a.u.stop(), a.u = null);
            a.D.removeChild(k2);
            qs(a, b);
            a.i(new T("ad-stopped"));
            a.l.Ta();
            var q = gs(a, b.pre, d2 - e);
            q ? hs(a, q, c, ++d2, Date.now(), e) : a.K = false;
          }
          a.K = true;
          var g = b.overlay, h = b.mimeType == "text/html" ? "iframe" : "img", k2 = document.createElement(h);
          k2.style.objectFit = "contain";
          k2.style.position = "absolute";
          k2.style.border = "none";
          ys(a, b);
          a.i(new T("ad-started", (/* @__PURE__ */ new Map()).set("ad", new ds(b, c, d2))));
          h == "iframe" ? k2.src = b.uri : (k2.src = b.uri, k2.onerror = function(q) {
            a.i(new T("ad-error", (/* @__PURE__ */ new Map()).set("originalEvent", q)));
            f();
          });
          var l = g.viewport, m = g.topLeft;
          g = g.size;
          l.x == 0 && l.y == 0 ? (k2.width = b.overlay.size.x, k2.height = b.overlay.size.y, k2.style.bottom = "10%", k2.style.left = "0", k2.style.right = "0", k2.style.width = "100%", b.overlay.size.y || h != "iframe" || (k2.style.height = "auto")) : (k2.style.height = g.y / l.y * 100 + "%", k2.style.left = m.x / l.x * 100 + "%", k2.style.top = m.y / l.y * 100 + "%", k2.style.width = g.x / l.x * 100 + "%");
          a.D.appendChild(k2);
          var n = Date.now();
          a.u && a.u.stop();
          a.u = new Cf(function() {
            b.playoutLimit && (Date.now() - n) / 1e3 > b.playoutLimit ? (a.i(new T("ad-complete")), f()) : b.endTime && a.g.currentTime > b.endTime ? (a.i(new T("ad-complete")), f()) : a.g.currentTime < b.startTime && (a.i(new T("ad-skipped")), f());
          });
          b.playoutLimit && !b.endTime ? a.u.Y(b.playoutLimit) : b.endTime && a.u.za(0.025);
          a.l.o(a.g, "seeked", function() {
            var q = a.g.currentTime;
            if (q < b.startTime || b.endTime && q > b.endTime) a.u && a.u.stop(), a.i(new T("ad-skipped")), f();
          });
        }
        function xs(a, b, c, d2, e, f) {
          var g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I;
          P(function(J) {
            switch (J.g) {
              case 1:
                g = Date.now();
                a.K = true;
                h = false;
                k2 = function() {
                  if (!a.C && !b.overlay && b.resumeOffset == null) if (b.timelineRange && b.endTime && b.endTime != Infinity) a.g.currentTime != b.endTime && (a.g.currentTime = b.endTime);
                  else {
                    var K = Date.now();
                    a.g.currentTime += (K - e) / 1e3;
                    e = K;
                  }
                };
                l = function(K) {
                  var L, M;
                  return P(function(N) {
                    if (N.g == 1) {
                      k2();
                      L = gs(a, b.pre, d2 - f);
                      if (K && b.groupId) for (; L && L.groupId == b.groupId; ) d2++, L = gs(a, b.pre, d2 - f);
                      a.u && (!b.groupId || L && L.groupId != b.groupId) && (a.u.stop(), a.u = null);
                      qs(a, b);
                      if (L && !L.overlay) return N.B(2);
                      b.post && (a.m = null, a.A = null);
                      return a.C ? G(N, a.j.detach(), 4) : G(N, a.j.rc(), 4);
                    }
                    N.g != 2 && (a.C && (M = b.resumeOffset, M == null && (M = b.timelineRange && b.endTime && b.endTime != Infinity ? b.endTime - (a.m || 0) : (Date.now() - e) / 1e3), a.i(new T("ad-content-resume-requested", (/* @__PURE__ */ new Map()).set("offset", M)))), a.i(new T("ad-stopped")), a.l.Ta(), a.K = false, a.C ? ms(a) : (a.h.style.display = "none", k2(), a.g.ended || a.g.play()));
                    ns(a);
                    L && (a.i(new T("ad-stopped")), a.l.Ta(), hs(a, L, c, ++d2, e, f));
                    H(N);
                  });
                };
                m = function(K) {
                  return P(function(L) {
                    if (h) return L.return();
                    h = true;
                    a.i(new T("ad-error", (/* @__PURE__ */ new Map()).set("originalEvent", K)));
                    return G(L, l(false), 0);
                  });
                };
                n = function() {
                  return P(function(K) {
                    if (K.g == 1) {
                      if (h) return K.return();
                      h = true;
                      return G(K, l(false), 2);
                    }
                    a.i(new T("ad-complete"));
                    H(K);
                  });
                };
                a.$ = function() {
                  return P(function(K) {
                    if (h) return K.return();
                    h = true;
                    a.i(new T("ad-skipped"));
                    return G(K, l(true), 0);
                  });
                };
                q = new cs(a.h, b, a.$, c, d2, !a.C);
                a.C || (q.setMuted(a.g.muted), q.setVolume(a.g.volume));
                a.i(new T("ad-started", (/* @__PURE__ */ new Map()).set("ad", q)));
                (r2 = q.canSkipNow()) && a.i(new T("ad-skip-state-changed"));
                a.l.qa(a.j, "error", m);
                a.l.o(a.h, "timeupdate", function() {
                  if (a.h.duration) {
                    var K = q.canSkipNow();
                    r2 != K && q.getRemainingTime() > 0 && q.getDuration() > 0 && a.i(new T("ad-skip-state-changed"));
                    r2 = K;
                  }
                });
                a.l.qa(a.j, "firstquartile", function() {
                  k2();
                  a.i(new T("ad-first-quartile"));
                });
                a.l.qa(a.j, "midpoint", function() {
                  k2();
                  a.i(new T("ad-midpoint"));
                });
                a.l.qa(a.j, "thirdquartile", function() {
                  k2();
                  a.i(new T("ad-third-quartile"));
                });
                a.l.qa(a.j, "complete", n);
                a.l.o(a.h, "play", function() {
                  a.i(new T("ad-resumed"));
                });
                a.l.o(a.h, "pause", function() {
                  var K = a.j.getConfiguration();
                  a.h.currentTime >= K.playRangeEnd ? n() : a.i(new T("ad-paused"));
                });
                a.l.o(a.h, "volumechange", function() {
                  a.h.muted ? a.i(new T("ad-muted")) : a.i(new T("ad-volume-changed"));
                });
                if (!a.C || d2 != 1) {
                  J.B(2);
                  break;
                }
                a.i(new T("ad-content-pause-requested", (/* @__PURE__ */ new Map()).set("saveLivePosition", true)));
                u = new Mg();
                w = function(K) {
                  return P(function(L) {
                    if (L.g == 1) return K.state != "detach" ? L.B(0) : ps() ? G(L, new Promise(function(M) {
                      return new Cf(M).Y(0.1);
                    }), 3) : L.B(3);
                    u.resolve();
                    a.l.Ea(a.F, "onstatechange", w);
                    H(L);
                  });
                };
                a.l.o(a.F, "onstatechange", w);
                return G(J, u, 2);
              case 2:
                return ys(a, b), a.C || (a.h.style.display = "", b.overlay ? (a.h.loop = b.loop, v = b.overlay.viewport, y = b.overlay.topLeft, z = b.overlay.size, a.h.style.height = z.y / v.y * 100 + "%", a.h.style.left = y.x / v.x * 100 + "%", a.h.style.top = y.y / v.y * 100 + "%", a.h.style.width = z.x / v.x * 100 + "%") : (a.g.pause(), b.resumeOffset != null && b.resumeOffset != 0 && (a.g.currentTime += b.resumeOffset), a.h.loop = false, a.h.style.height = "100%", a.h.style.left = "0", a.h.style.top = "0", a.h.style.width = "100%")), sa(J, 4), fs(a), b.startTime && b.endTime && b.endTime != Infinity && b.startTime != b.endTime && (A = b.endTime - b.startTime, A > 0 && a.j.configure("playRangeEnd", A)), b.playoutLimit && !a.u && (a.u = new Cf(function() {
                  a.$();
                }).Y(b.playoutLimit), a.j.configure("playRangeEnd", b.playoutLimit)), G(J, a.j.bc(a.h), 6);
              case 6:
                return C = null, a.M.allowStartInMiddleOfInterstitial && a.m != null && (D = a.m - b.startTime, Math.abs(D) > 0.25 && (C = D)), a.G.has(b) ? G(J, a.G.get(b), 10) : G(J, a.j.load(b.uri, C, b.mimeType || void 0), 8);
              case 10:
                return F = J.h, a.G.delete(b), F ? G(J, a.j.load(F), 8) : G(J, a.j.load(b.uri, C, b.mimeType || void 0), 8);
              case 8:
                a.h.play();
                B = (Date.now() - g) / 1e3;
                a.i(new T("ads-loaded", (/* @__PURE__ */ new Map()).set("loadTime", B)));
                a.C && a.g.play();
                b.overlay && (E = function() {
                  var K = a.g.currentTime - b.startTime;
                  Math.abs(K - a.h.currentTime) > 0.1 && (a.h.currentTime = K);
                }, a.l.qa(a.h, "playing", E), a.l.o(a.g, "seeking", E), a.l.o(a.g, "seeked", function() {
                  var K = a.g.currentTime;
                  (K < b.startTime || b.endTime && K > b.endTime) && a.$();
                }));
                ua(J, 0);
                break;
              case 4:
                I = va(J);
                if (!a.K) return J.return();
                m(I);
                H(J);
            }
          });
        }
        function ys(a, b) {
          b.displayOnBackground && (a.g.style.zIndex = "1");
          if (b.currentVideo != null) {
            var c = b.currentVideo;
            a.g.style.transformOrigin = "top left";
            var d2 = true, e = [], f = c.topLeft.x / c.viewport.x * 100;
            f > 0 && f <= 100 && (e.push("translateX(" + f + "%)"), d2 = false);
            f = c.topLeft.y / c.viewport.y * 100;
            f > 0 && f <= 100 && (e.push("translateY(" + f + "%)"), d2 = false);
            f = c.size.x / c.viewport.x;
            f < 1 && e.push("scaleX(" + f + ")");
            c = c.size.y / c.viewport.y;
            f < 1 && e.push("scaleY(" + c + ")");
            e.length && (a.g.style.transform = e.join(" "));
            d2 && (a.g.style.transition = "transform 250ms");
          }
          a.D && (a.D.style.pointerEvents = "none", b.background && (a.D.style.background = b.background));
          a.H && (a.H.style.background = b.overlay ? "" : "rgb(0, 0, 0)");
        }
        function qs(a, b) {
          if (!b || b.displayOnBackground) a.g.style.zIndex = "";
          b && b.currentVideo == null || (a.g.style.transformOrigin = "", a.g.style.transition = "", a.g.style.transform = "");
          a.D && (a.D.style.pointerEvents = "", !b || b.background) && (a.D.style.background = "");
          a.H && (a.H.style.background = "");
        }
        function ss(a, b) {
          var c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N, O, Q, R, V, Ba, aa, Oa, La, Ja, Ea, ya, Fa, Da;
          return P(function(za) {
            switch (za.g) {
              case 1:
                c = [];
                if (!b) return za.return(c);
                d2 = b.values.find(function(Ca) {
                  return Ca.key == "X-ASSET-URI";
                });
                e = b.values.find(function(Ca) {
                  return Ca.key == "X-ASSET-LIST";
                });
                if (!d2 && !e) return za.return(c);
                f = null;
                if (g = b.values.find(function(Ca) {
                  return Ca.key == "ID";
                })) f = g.data;
                h = f == null ? Math.floor(b.startTime * 10) / 10 : b.startTime;
                (k2 = b.endTime) && b.endTime != Infinity && typeof b.endTime == "number" && (k2 = f == null ? Math.floor(b.endTime * 10) / 10 : b.endTime);
                l = b.values.find(function(Ca) {
                  return Ca.key == "X-RESTRICT";
                });
                n = m = true;
                l && l.data && (q = l.data, m = !q.includes("SKIP"), n = !q.includes("JUMP"));
                r2 = m ? 0 : null;
                if (u = b.values.find(function(Ca) {
                  return Ca.key == "X-ENABLE-SKIP-AFTER";
                })) w = u.data, r2 = parseFloat(w), isNaN(r2) && (r2 = m ? 0 : null);
                v = null;
                if (y = b.values.find(function(Ca) {
                  return Ca.key == "X-ENABLE-SKIP-FOR";
                })) z = y.data, v = parseFloat(z), isNaN(r2) && (v = null);
                A = null;
                if (C = b.values.find(function(Ca) {
                  return Ca.key == "X-RESUME-OFFSET";
                })) D = C.data, A = parseFloat(D), isNaN(A) && (A = null);
                F = null;
                if (B = b.values.find(function(Ca) {
                  return Ca.key == "X-PLAYOUT-LIMIT";
                })) E = B.data, F = parseFloat(E), isNaN(F) && (F = null);
                K = J = I = false;
                if (L = b.values.find(function(Ca) {
                  return Ca.key == "CUE";
                })) M = L.data, I = M.includes("ONCE"), J = M.includes("PRE"), K = M.includes("POST");
                N = false;
                (O = b.values.find(function(Ca) {
                  return Ca.key == "X-TIMELINE-OCCUPIES";
                })) ? (Q = O.data, N = Q.includes("RANGE")) : !C && a.F.U() && (N = !J && !K);
                if (d2) {
                  R = d2.data;
                  if (!R) return za.return(c);
                  c.push({
                    id: f,
                    groupId: null,
                    startTime: h,
                    endTime: k2,
                    uri: R,
                    mimeType: null,
                    isSkippable: m,
                    skipOffset: r2,
                    skipFor: v,
                    canJump: n,
                    resumeOffset: A,
                    playoutLimit: F,
                    once: I,
                    pre: J,
                    post: K,
                    timelineRange: N,
                    loop: false,
                    overlay: null,
                    displayOnBackground: false,
                    currentVideo: null,
                    background: null
                  });
                  za.B(2);
                  break;
                }
                if (!e) {
                  za.B(2);
                  break;
                }
                V = e.data;
                if (!V) return za.return(c);
                sa(za, 4);
                Ba = {
                  type: 11
                };
                return G(za, vs(a, V, Ba), 6);
              case 6:
                aa = za.h;
                Oa = Xb(aa);
                La = JSON.parse(Oa);
                if (Ja = La["SKIP-CONTROL"]) Ea = Ja["ENABLE-SKIP-AFTER"], typeof Ea == "number" && (r2 = parseFloat(Ea), isNaN(Ea) && (r2 = m ? 0 : null)), ya = Ja["ENABLE-SKIP-FOR"], typeof ya == "number" && (v = parseFloat(ya), isNaN(ya) && (v = null));
                for (Fa = 0; Fa < La.ASSETS.length; Fa++) Da = La.ASSETS[Fa], Da.URI && c.push({
                  id: f + "_shaka_asset_" + Fa,
                  groupId: f,
                  startTime: h,
                  endTime: k2,
                  uri: Da.URI,
                  mimeType: null,
                  isSkippable: m,
                  skipOffset: r2,
                  skipFor: v,
                  canJump: n,
                  resumeOffset: A,
                  playoutLimit: F,
                  once: I,
                  pre: J,
                  post: K,
                  timelineRange: N,
                  loop: false,
                  overlay: null,
                  displayOnBackground: false,
                  currentVideo: null,
                  background: null
                });
                ua(za, 2);
                break;
              case 4:
                va(za);
              case 2:
                return za.return(c);
            }
          });
        }
        function ms(a) {
          for (var b = [], c = t2(a.I), d2 = c.next(), e = {}; !d2.done; e = {
            Gc: void 0
          }, d2 = c.next()) d2 = d2.value, d2.overlay || (e.Gc = {
            start: d2.startTime,
            end: null
          }, d2.pre ? (e.Gc.start = 0, e.Gc.end = null) : d2.post ? (e.Gc.start = -1, e.Gc.end = null) : d2.timelineRange && (e.Gc.end = d2.endTime), b.find(/* @__PURE__ */ function(f) {
            return function(g) {
              return f.Gc.start == g.start && f.Gc.end == g.end;
            };
          }(e)) || b.push(e.Gc));
          a.i(new T("ad-cue-points-changed", (/* @__PURE__ */ new Map()).set("cuepoints", b)));
        }
        function fs(a) {
          a.j.configure(a.F.Zi());
          a.j.configure("ads.disableHLSInterstitial", true);
          a.j.configure("ads.disableDASHInterstitial", true);
          a.j.configure("playRangeEnd", Infinity);
          $g(a.F.Lb(), a.j.Lb());
        }
        function vs(a, b, c) {
          var d2, e, f;
          return P(function(g) {
            if (g.g == 1) return d2 = ah([b], Kg()), e = a.F.Lb().request(7, d2, c), G(g, e.promise, 2);
            f = g.h;
            return g.return(f.data);
          });
        }
        function is(a) {
          return (a = a.mimeType) ? !a.startsWith("image/") && a !== "text/html" : true;
        }
        function ps() {
          var a = Sb().Ka();
          return a == "TV" || a == "CONSOLE" || a == "CAST" ? true : false;
        }
        function js(a, b) {
          if (!(a.L.has(b) || a.M && !a.M.allowPreloadOnDomElements)) {
            var c = function(f) {
              var g = document.createElement("link");
              g.rel = "preload";
              g.href = f;
              g.as = "image";
              document.head.appendChild(g);
              return g;
            }, d2 = [];
            if (b.background) {
              var e = b.background.match(/url\(('|")?([^'"()]+)('|")\)?/);
              e && d2.push(c(e[2]));
            }
            b.mimeType.startsWith("image/") && d2.push(c(b.uri));
            a.L.set(b, d2);
          }
        }
        function ks(a, b) {
          if (a.L.has(b)) {
            var c = a.L.get(b);
            c = t2(c);
            for (var d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, d2.parentNode.removeChild(d2);
            a.L.delete(b);
          }
        }
        ;
        function zs(a, b, c, d2, e) {
          this.h = a;
          this.j = Fd(this.h.skipOffset);
          this.g = e;
          this.i = b;
          this.l = c;
          this.u = d2;
          this.m = false;
        }
        p = zs.prototype;
        p.needsSkipUI = function() {
          return true;
        };
        p.isClientRendering = function() {
          return false;
        };
        p.hasCustomClick = function() {
          return false;
        };
        p.isUsingAnotherMediaElement = function() {
          return false;
        };
        p.getDuration = function() {
          return this.h.durationInSeconds;
        };
        p.getMinSuggestedDuration = function() {
          return this.getDuration();
        };
        p.getRemainingTime = function() {
          return this.h.startTimeInSeconds + this.h.durationInSeconds - this.g.currentTime;
        };
        p.isPaused = function() {
          return this.g.paused;
        };
        p.isSkippable = function() {
          return typeof this.j == "number" ? true : false;
        };
        p.getTimeUntilSkippable = function() {
          if (typeof this.j != "number") return this.getRemainingTime();
          var a = this.getRemainingTime() + this.j - this.getDuration();
          return Math.max(a, 0);
        };
        p.canSkipNow = function() {
          return this.getTimeUntilSkippable() == 0;
        };
        p.skip = function() {
          this.m = true;
          this.g.currentTime += this.getRemainingTime();
        };
        p.pause = function() {
          return this.g.pause();
        };
        p.play = function() {
          return this.g.play();
        };
        p.getVolume = function() {
          return this.g.volume;
        };
        p.setVolume = function(a) {
          this.g.volume = a;
        };
        p.isMuted = function() {
          return this.g.muted;
        };
        p.isLinear = function() {
          return this.u;
        };
        p.resize = function() {
        };
        p.setMuted = function(a) {
          this.g.muted = a;
        };
        p.getSequenceLength = function() {
          return this.l ? this.l : 1;
        };
        p.getPositionInSequence = function() {
          return this.i ? this.i : 1;
        };
        p.getTitle = function() {
          return this.h.adTitle;
        };
        p.getDescription = function() {
          return "";
        };
        p.getVastMediaBitrate = function() {
          return 0;
        };
        p.getVastMediaHeight = function() {
          return 0;
        };
        p.getVastMediaWidth = function() {
          return 0;
        };
        p.getVastAdId = function() {
          return this.h.vastAdId || "";
        };
        p.getAdId = function() {
          return this.h.adId;
        };
        p.getCreativeAdId = function() {
          return this.h.creativeId;
        };
        p.getAdvertiserName = function() {
          return "";
        };
        p.getMediaUrl = function() {
          return null;
        };
        p.getTimeOffset = function() {
          return 0;
        };
        p.getPodIndex = function() {
          return 0;
        };
        p.release = function() {
          this.l = this.i = this.g = this.h = null;
        };
        S("shaka.ads.MediaTailorAd", zs);
        zs.prototype.release = zs.prototype.release;
        zs.prototype.getPodIndex = zs.prototype.getPodIndex;
        zs.prototype.getTimeOffset = zs.prototype.getTimeOffset;
        zs.prototype.getMediaUrl = zs.prototype.getMediaUrl;
        zs.prototype.getAdvertiserName = zs.prototype.getAdvertiserName;
        zs.prototype.getCreativeAdId = zs.prototype.getCreativeAdId;
        zs.prototype.getAdId = zs.prototype.getAdId;
        zs.prototype.getVastAdId = zs.prototype.getVastAdId;
        zs.prototype.getVastMediaWidth = zs.prototype.getVastMediaWidth;
        zs.prototype.getVastMediaHeight = zs.prototype.getVastMediaHeight;
        zs.prototype.getVastMediaBitrate = zs.prototype.getVastMediaBitrate;
        zs.prototype.getDescription = zs.prototype.getDescription;
        zs.prototype.getTitle = zs.prototype.getTitle;
        zs.prototype.getPositionInSequence = zs.prototype.getPositionInSequence;
        zs.prototype.getSequenceLength = zs.prototype.getSequenceLength;
        zs.prototype.setMuted = zs.prototype.setMuted;
        zs.prototype.resize = zs.prototype.resize;
        zs.prototype.isLinear = zs.prototype.isLinear;
        zs.prototype.isMuted = zs.prototype.isMuted;
        zs.prototype.setVolume = zs.prototype.setVolume;
        zs.prototype.getVolume = zs.prototype.getVolume;
        zs.prototype.play = zs.prototype.play;
        zs.prototype.pause = zs.prototype.pause;
        zs.prototype.skip = zs.prototype.skip;
        zs.prototype.canSkipNow = zs.prototype.canSkipNow;
        zs.prototype.getTimeUntilSkippable = zs.prototype.getTimeUntilSkippable;
        zs.prototype.isSkippable = zs.prototype.isSkippable;
        zs.prototype.isPaused = zs.prototype.isPaused;
        zs.prototype.getRemainingTime = zs.prototype.getRemainingTime;
        zs.prototype.getMinSuggestedDuration = zs.prototype.getMinSuggestedDuration;
        zs.prototype.getDuration = zs.prototype.getDuration;
        zs.prototype.isUsingAnotherMediaElement = zs.prototype.isUsingAnotherMediaElement;
        zs.prototype.hasCustomClick = zs.prototype.hasCustomClick;
        zs.prototype.isClientRendering = zs.prototype.isClientRendering;
        zs.prototype.needsSkipUI = zs.prototype.needsSkipUI;
        function As(a, b, c, d2) {
          this.D = a;
          this.K = b;
          this.h = c;
          this.l = null;
          this.P = NaN;
          this.i = d2;
          this.J = false;
          this.C = null;
          this.j = [];
          this.M = [];
          this.L = this.F = this.g = null;
          this.G = /* @__PURE__ */ new Map();
          this.m = [];
          this.A = [];
          this.H = "";
          this.O = true;
          this.I = "";
          this.u = new Qc();
        }
        As.prototype.stop = function() {
          for (var a = t2(this.m), b = a.next(); !b.done; b = a.next()) b = b.value, this.u.Ea(b.target, b.type, b.listener);
          Bs(this);
          this.m = [];
          this.A = [];
          this.H = "";
          this.O = true;
          this.I = "";
          this.C = null;
          this.j = [];
          this.M = [];
          this.G.clear();
        };
        As.prototype.release = function() {
          this.stop();
          this.u && this.u.release();
        };
        As.prototype.onManifestUpdated = function(a) {
          this.J = a;
          this.H != "" && (Cs(this, this.H, this.O), this.O = false);
        };
        As.prototype.getCuePoints = function() {
          for (var a = [], b = t2(this.j), c = b.next(); !c.done; c = b.next()) {
            c = t2(c.value.ads);
            for (var d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, a.push({
              start: d2.startTimeInSeconds,
              end: d2.startTimeInSeconds + d2.durationInSeconds
            });
          }
          return a;
        };
        function Ds(a, b, c) {
          var d2, e, f, g, h, k2, l, m, n, q, r2, u;
          P(function(w) {
            if (w.g == 1) return d2 = {
              type: 7
            }, e = ah([b], Kg()), e.method = "POST", c && (f = JSON.stringify(c), e.body = ac(f)), g = a.K.request(7, e, d2), sa(w, 2), G(w, g.promise, 4);
            if (w.g != 2) {
              h = w.h;
              k2 = Xb(h.data);
              l = JSON.parse(k2);
              if (l.manifestUrl && l.trackingUrl) m = new rb(b), n = new rb(l.trackingUrl), a.H = m.resolve(n).toString(), q = Date.now() / 1e3, r2 = q - a.P, a.i(new T("ads-loaded", (/* @__PURE__ */ new Map()).set("loadTime", r2))), u = new rb(l.manifestUrl), a.l.resolve(m.resolve(u).toString()), a.l = null;
              else throw Error("Insufficient data from MediaTailor.");
              return ua(w, 0);
            }
            va(w);
            if (!a.I.length) return a.l.reject("MediaTailor request returned an error and there was no backup asset uri provided."), a.l = null, w.return();
            a.l.resolve(a.I);
            a.l = null;
            H(w);
          });
        }
        function Cs(a, b, c) {
          var d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z;
          P(function(A) {
            if (A.g == 1) return d2 = {
              type: 8
            }, e = ah([b], Kg()), f = a.K.request(7, e, d2), sa(A, 2), G(A, f.promise, 4);
            if (A.g != 2) {
              g = A.h;
              h = [];
              k2 = Xb(g.data);
              l = JSON.parse(k2);
              if (l.avails.length > 0) {
                if (JSON.stringify(a.j) != JSON.stringify(l.avails)) {
                  a.j = l.avails;
                  m = t2(a.j);
                  for (n = m.next(); !n.done; n = m.next()) for (q = n.value, r2 = t2(q.nonLinearAdsList), u = r2.next(); !u.done; u = r2.next()) for (w = u.value, v = t2(w.nonLinearAdList), y = v.next(); !y.done; y = v.next()) z = y.value, Es(a, z);
                  h = a.getCuePoints();
                  a.i(new T("ad-cue-points-changed", (/* @__PURE__ */ new Map()).set("cuepoints", h)));
                }
              } else a.j.length && a.i(new T("ad-cue-points-changed", (/* @__PURE__ */ new Map()).set("cuepoints", h))), Bs(a), a.j = [];
              c && (a.J || h.length > 0) && Fs(a);
              return ua(A, 0);
            }
            va(A);
            H(A);
          });
        }
        function Es(a, b) {
          var c, d2, e, f, g, h, k2, l, m;
          P(function(n) {
            if (n.g == 1) {
              if (!b.staticResource) return n.return();
              c = Gs(b);
              if (d2 = a.G.get(c)) return n.return();
              e = {
                type: 9
              };
              f = ah([b.staticResource], Kg());
              g = a.K.request(7, f, e);
              sa(n, 2);
              a.G.set(c, []);
              return G(n, g.promise, 4);
            }
            if (n.g != 2) return h = n.h, k2 = Xb(h.data), l = JSON.parse(k2), m = l.apps, a.G.set(c, m), ua(n, 0);
            va(n);
            a.G.delete(c);
            H(n);
          });
        }
        function Gs(a) {
          return [a.adId, a.adParameters, a.adSystem, a.adTitle, a.creativeAdId, a.creativeId, a.creativeSequence, a.height, a.width, a.staticResource].join("");
        }
        function Fs(a) {
          Hs(a);
          a.J || (Is(a), a.u.o(a.h, "seeked", function() {
            Is(a);
          }), a.u.o(a.h, "ended", function() {
            Bs(a);
          }));
          a.u.o(a.h, "timeupdate", function() {
            Hs(a);
          });
        }
        function Is(a) {
          var b = a.h.currentTime;
          if (b != 0 && a.C == null) {
            for (var c, d2, e = t2(a.j), f = e.next(); !f.done; f = e.next()) {
              f = f.value;
              for (var g = t2(f.ads), h = g.next(); !h.done; h = g.next()) if (h = h.value, !d2) h.startTimeInSeconds < b && (d2 = h, c = f);
              else if (h.startTimeInSeconds < b && h.startTimeInSeconds > d2.startTimeInSeconds + d2.durationInSeconds) {
                d2 = h;
                c = f;
                break;
              }
            }
            c && d2 && !a.M.includes(d2.adId) && (a.C = b, a.h.currentTime = c.startTimeInSeconds);
          }
        }
        function Hs(a) {
          if (a.h.duration && (a.g || a.j.length)) {
            var b = a.h.currentTime, c = false;
            if (a.g) {
              c = true;
              var d2 = a.F, e = d2.startTimeInSeconds + 0.5 * d2.durationInSeconds, f = d2.startTimeInSeconds + 0.75 * d2.durationInSeconds;
              b >= d2.startTimeInSeconds + 0.25 * d2.durationInSeconds && !a.A.includes("firstQuartile") ? (a.A.push("firstQuartile"), Js(a, "firstQuartile")) : b >= e && !a.A.includes("midpoint") ? (a.A.push("midpoint"), Js(a, "midpoint")) : b >= f && !a.A.includes("thirdQuartile") && (a.A.push("thirdQuartile"), Js(a, "thirdQuartile"));
              d2 = a.g.getRemainingTime();
              e = a.g.getDuration();
              a.g.canSkipNow() && d2 > 0 && e > 0 && Js(a, "skipStateChanged");
              e > 0 && (d2 <= 0 || d2 > e) && Bs(a);
            }
            if (!a.g || !a.g.isLinear()) {
              a: for (d2 = t2(a.j), e = d2.next(); !e.done; e = d2.next()) {
                e = e.value;
                if (a.g && a.g.isLinear()) break;
                for (f = 0; f < e.ads.length; f++) {
                  var g = e.ads[f], h = g.startTimeInSeconds + g.durationInSeconds;
                  if (g.startTimeInSeconds <= b && h > b) {
                    if (a.M.includes(g.adId)) {
                      if (a.h.ended) continue;
                      a.h.currentTime = h;
                      break a;
                    }
                    Bs(a);
                    a.L = e;
                    a.g = new zs(g, f + 1, e.ads.length, true, a.h);
                    a.F = g;
                    f === 0 && Js(a, "breakStart");
                    Ks(a);
                    break;
                  }
                }
              }
              if (!a.g) for (d2 = t2(a.j), e = d2.next(); !e.done; e = d2.next()) {
                e = e.value;
                if (a.g) break;
                for (f = 0; f < e.nonLinearAdsList.length; f++) if (g = e.nonLinearAdsList[f], g.nonLinearAdList.length) {
                  h = e.startTimeInSeconds;
                  var k2 = a.G.get(Gs(g.nonLinearAdList[0]));
                  if (h <= b && k2 && k2.length) {
                    Bs(a);
                    h = a;
                    k2 = t2(k2);
                    for (var l = k2.next(); !l.done; l = k2.next()) if (l = l.value, l.data.source.length) {
                      var m = document.createElement("img");
                      m.src = l.data.source[0].url;
                      m.style.top = (l.placeholder.top || 0) + "%";
                      m.style.height = 100 - (l.placeholder.top || 0) + "%";
                      m.style.left = (l.placeholder.left || 0) + "%";
                      m.style.maxWidth = 100 - (l.placeholder.left || 0) + "%";
                      m.style.objectFit = "contain";
                      m.style.position = "absolute";
                      h.D.appendChild(m);
                    }
                    a.L = e;
                    a.g = new zs(g, f + 1, e.ads.length, false, a.h);
                    a.F = g;
                    f === 0 && Js(a, "breakStart");
                    Ks(a);
                    break;
                  }
                }
              }
              c && !a.g && (b = a.h.currentTime, a.C && a.C > b && (a.h.currentTime = a.C), a.C = null);
            }
          }
        }
        function Bs(a) {
          if (a.g) {
            for (; a.D.lastChild; ) a.D.removeChild(a.D.firstChild);
            a.J || a.M.push(a.F.adId);
            var b = a.g.m;
            (b === void 0 ? 0 : b) ? Js(a, "skip") : Js(a, "complete");
            b = t2(a.m);
            for (var c = b.next(); !c.done; c = b.next()) c = c.value, a.u.Ea(c.target, c.type, c.listener);
            a.m = [];
            a.A = [];
            b = a.g.getPositionInSequence();
            c = a.g.getSequenceLength();
            b === c && Js(a, "breakEnd");
            a.g = null;
            a.F = null;
            a.L = null;
          }
        }
        function Ks(a) {
          var b = false;
          a.h.paused ? b = true : (Js(a, "impression"), Js(a, "start"));
          a.m.push({
            target: a.h,
            type: "volumechange",
            listener: function() {
              a.h.muted && Js(a, "mute");
            }
          });
          a.m.push({
            target: a.h,
            type: "volumechange",
            listener: function() {
              a.h.muted || Js(a, "unmute");
            }
          });
          a.m.push({
            target: a.h,
            type: "play",
            listener: function() {
              b ? (Js(a, "impression"), Js(a, "start"), b = false) : Js(a, "resume");
            }
          });
          a.m.push({
            target: a.h,
            type: "pause",
            listener: function() {
              Js(a, "pause");
            }
          });
          for (var c = t2(a.m), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, a.u.o(d2.target, d2.type, d2.listener);
        }
        function Js(a, b) {
          var c = a.F.trackingEvents.find(function(f) {
            return f.eventType == b;
          });
          c || (c = a.L.adBreakTrackingEvents.find(function(f) {
            return f.eventType == b;
          }));
          if (c) {
            var d2 = {
              type: 10
            };
            c = t2(c.beaconUrls);
            for (var e = c.next(); !e.done; e = c.next()) (e = e.value) && e != "" && (e = ah([e], Kg()), e.method = "POST", a.K.request(7, e, d2));
          }
          switch (b) {
            case "impression":
              a.i(new T("ad-impression"));
              break;
            case "start":
              a.i(new T("ad-started", (/* @__PURE__ */ new Map()).set("ad", a.g)));
              break;
            case "mute":
              a.i(new T("ad-muted"));
              break;
            case "unmute":
              a.i(new T("ad-volume-changed"));
              break;
            case "resume":
              a.i(new T("ad-resumed"));
              break;
            case "pause":
              a.i(new T("ad-paused"));
              break;
            case "firstQuartile":
              a.i(new T("ad-first-quartile"));
              break;
            case "midpoint":
              a.i(new T("ad-midpoint"));
              break;
            case "thirdQuartile":
              a.i(new T("ad-third-quartile"));
              break;
            case "complete":
              a.i(new T("ad-complete"));
              a.i(new T("ad-stopped"));
              break;
            case "skip":
              a.i(new T("ad-skipped"));
              a.i(new T("ad-stopped"));
              break;
            case "breakStart":
              a.D.setAttribute("ad-active", "true");
              break;
            case "breakEnd":
              a.D.removeAttribute("ad-active");
              break;
            case "skipStateChanged":
              a.i(new T("ad-skip-state-changed"));
          }
        }
        ;
        function Ls(a, b) {
          this.g = a;
          this.i = null;
          this.h = b;
        }
        p = Ls.prototype;
        p.needsSkipUI = function() {
          return true;
        };
        p.isClientRendering = function() {
          return false;
        };
        p.hasCustomClick = function() {
          return true;
        };
        p.isUsingAnotherMediaElement = function() {
          return false;
        };
        p.getDuration = function() {
          return this.i ? this.i.duration : -1;
        };
        p.getMinSuggestedDuration = function() {
          return this.getDuration();
        };
        p.getRemainingTime = function() {
          return this.i ? this.i.duration - this.i.currentTime : -1;
        };
        p.isPaused = function() {
          return this.h.paused;
        };
        p.isSkippable = function() {
          return this.g.isSkippable();
        };
        p.getTimeUntilSkippable = function() {
          var a = this.g.getSkipTimeOffset();
          a = this.getRemainingTime() - a;
          return Math.max(a, 0);
        };
        p.canSkipNow = function() {
          return this.getTimeUntilSkippable() == 0;
        };
        p.skip = function() {
          this.h.currentTime += this.getRemainingTime();
        };
        p.pause = function() {
          return this.h.pause();
        };
        p.play = function() {
          return this.h.play();
        };
        p.getVolume = function() {
          return this.h.volume;
        };
        p.setVolume = function(a) {
          this.h.volume = a;
        };
        p.isMuted = function() {
          return this.h.muted;
        };
        p.isLinear = function() {
          return true;
        };
        p.resize = function() {
        };
        p.setMuted = function(a) {
          this.h.muted = a;
        };
        p.getSequenceLength = function() {
          var a = this.g.getAdPodInfo();
          return a == null ? 1 : a.getTotalAds();
        };
        p.getPositionInSequence = function() {
          var a = this.g.getAdPodInfo();
          return a == null ? 1 : a.getAdPosition();
        };
        p.getTitle = function() {
          return this.g.getTitle();
        };
        p.getDescription = function() {
          return this.g.getDescription();
        };
        p.getVastMediaBitrate = function() {
          return 0;
        };
        p.getVastMediaHeight = function() {
          return this.g.getVastMediaHeight();
        };
        p.getVastMediaWidth = function() {
          return this.g.getVastMediaWidth();
        };
        p.getVastAdId = function() {
          return "";
        };
        p.getAdId = function() {
          return this.g.getAdId();
        };
        p.getCreativeAdId = function() {
          return this.g.getCreativeAdId();
        };
        p.getAdvertiserName = function() {
          return this.g.getAdvertiserName();
        };
        p.getMediaUrl = function() {
          return null;
        };
        p.getTimeOffset = function() {
          var a = this.g.getAdPodInfo();
          return a == null ? 0 : a.getTimeOffset();
        };
        p.getPodIndex = function() {
          var a = this.g.getAdPodInfo();
          return a == null ? 0 : a.getPodIndex();
        };
        p.release = function() {
          this.h = this.i = this.g = null;
        };
        S("shaka.ads.ServerSideAd", Ls);
        Ls.prototype.release = Ls.prototype.release;
        Ls.prototype.getPodIndex = Ls.prototype.getPodIndex;
        Ls.prototype.getTimeOffset = Ls.prototype.getTimeOffset;
        Ls.prototype.getMediaUrl = Ls.prototype.getMediaUrl;
        Ls.prototype.getAdvertiserName = Ls.prototype.getAdvertiserName;
        Ls.prototype.getCreativeAdId = Ls.prototype.getCreativeAdId;
        Ls.prototype.getAdId = Ls.prototype.getAdId;
        Ls.prototype.getVastAdId = Ls.prototype.getVastAdId;
        Ls.prototype.getVastMediaWidth = Ls.prototype.getVastMediaWidth;
        Ls.prototype.getVastMediaHeight = Ls.prototype.getVastMediaHeight;
        Ls.prototype.getVastMediaBitrate = Ls.prototype.getVastMediaBitrate;
        Ls.prototype.getDescription = Ls.prototype.getDescription;
        Ls.prototype.getTitle = Ls.prototype.getTitle;
        Ls.prototype.getPositionInSequence = Ls.prototype.getPositionInSequence;
        Ls.prototype.getSequenceLength = Ls.prototype.getSequenceLength;
        Ls.prototype.setMuted = Ls.prototype.setMuted;
        Ls.prototype.resize = Ls.prototype.resize;
        Ls.prototype.isLinear = Ls.prototype.isLinear;
        Ls.prototype.isMuted = Ls.prototype.isMuted;
        Ls.prototype.setVolume = Ls.prototype.setVolume;
        Ls.prototype.getVolume = Ls.prototype.getVolume;
        Ls.prototype.play = Ls.prototype.play;
        Ls.prototype.pause = Ls.prototype.pause;
        Ls.prototype.skip = Ls.prototype.skip;
        Ls.prototype.canSkipNow = Ls.prototype.canSkipNow;
        Ls.prototype.getTimeUntilSkippable = Ls.prototype.getTimeUntilSkippable;
        Ls.prototype.isSkippable = Ls.prototype.isSkippable;
        Ls.prototype.isPaused = Ls.prototype.isPaused;
        Ls.prototype.getRemainingTime = Ls.prototype.getRemainingTime;
        Ls.prototype.getMinSuggestedDuration = Ls.prototype.getMinSuggestedDuration;
        Ls.prototype.getDuration = Ls.prototype.getDuration;
        Ls.prototype.isUsingAnotherMediaElement = Ls.prototype.isUsingAnotherMediaElement;
        Ls.prototype.hasCustomClick = Ls.prototype.hasCustomClick;
        Ls.prototype.isClientRendering = Ls.prototype.isClientRendering;
        Ls.prototype.needsSkipUI = Ls.prototype.needsSkipUI;
        function Ms(a, b, c, d2) {
          var e = this;
          this.A = a;
          this.l = b;
          this.j = null;
          this.G = NaN;
          this.i = d2;
          this.H = false;
          this.C = this.m = this.u = null;
          this.D = "";
          this.F = [];
          this.h = new Qc();
          a = new google.ima.dai.api.UiSettings();
          a.setLocale(c);
          this.g = new google.ima.dai.api.StreamManager(this.l, this.A, a);
          this.i(new T("ima-stream-manager-loaded", (/* @__PURE__ */ new Map()).set("imaStreamManager", this.g)));
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.LOADED, function(f) {
            Ns(e, f);
          });
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.ERROR, function() {
            e.D.length ? e.j.resolve(e.D) : e.j.reject("IMA Stream request returned an error and there was no backup asset uri provided.");
            e.j = null;
          });
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.AD_BREAK_STARTED, function() {
          });
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.STARTED, function(f) {
            f = f.getAd();
            e.m = new Ls(f, e.l);
            e.C && (e.m.i = e.C);
            e.i(new T("ad-started", (/* @__PURE__ */ new Map()).set("ad", e.m)));
            e.A.setAttribute("ad-active", "true");
          });
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.AD_BREAK_ENDED, function() {
            e.A.removeAttribute("ad-active");
            var f = e.l.currentTime;
            e.u && e.u > f && (e.l.currentTime = e.u, e.u = null);
          });
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.AD_PROGRESS, function(f) {
            e.C = f.getStreamData().adProgressData;
            e.m && (e.m.i = e.C);
          });
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.FIRST_QUARTILE, function() {
            e.i(new T("ad-first-quartile"));
          });
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.MIDPOINT, function() {
            e.i(new T("ad-midpoint"));
          });
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.THIRD_QUARTILE, function() {
            e.i(new T("ad-third-quartile"));
          });
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.COMPLETE, function() {
            e.i(new T("ad-complete"));
            e.i(new T("ad-stopped"));
            e.A.removeAttribute("ad-active");
            e.m = null;
          });
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.SKIPPED, function() {
            e.i(new T("ad-skipped"));
            e.i(new T("ad-stopped"));
          });
          this.h.o(this.g, google.ima.dai.api.StreamEvent.Type.CUEPOINTS_CHANGED, function(f) {
            var g = f.getStreamData();
            f = [];
            g = t2(g.cuepoints);
            for (var h = g.next(); !h.done; h = g.next()) h = h.value, f.push({
              start: h.start,
              end: h.end
            });
            e.F = f;
            e.i(new T("ad-cue-points-changed", (/* @__PURE__ */ new Map()).set("cuepoints", f)));
          });
        }
        p = Ms.prototype;
        p.configure = function() {
        };
        p.stop = function() {
          this.D = "";
          this.u = null;
          this.F = [];
        };
        p.release = function() {
          this.stop();
          this.h && this.h.release();
        };
        p.onCueMetadataChange = function(a) {
          if (a.key && a.data) {
            var b = {};
            b[a.key] = a.data;
            this.g.onTimedMetadata(b);
          }
        };
        p.getCuePoints = function() {
          return this.F;
        };
        function Ns(a, b) {
          a.i(new T("ads-loaded", (/* @__PURE__ */ new Map()).set("loadTime", Date.now() / 1e3 - a.G)));
          b = b.getStreamData().url;
          a.j.resolve(b);
          a.j = null;
          a.H || a.h.o(a.l, "seeked", function() {
            var c = a.l.currentTime;
            if (c != 0) {
              a.g.streamTimeForContentTime(c);
              var d2 = a.g.previousCuePointForStreamTime(c);
              d2 && !d2.played && (a.u = c, a.l.currentTime = d2.start);
            }
          });
        }
        ;
        function Os() {
          lb.call(this);
          this.h = this.i = this.j = this.g = null;
          this.m = new Qr();
          this.u = navigator.language;
          this.l = null;
        }
        ma(Os, lb);
        p = Os.prototype;
        p.setLocale = function(a) {
          this.u = a;
        };
        p.configure = function(a) {
          this.l = a;
          this.g && this.g.configure(this.l);
          this.j && this.j.configure(this.l);
          this.h && this.h.configure(this.l);
        };
        p.initInterstitial = function(a, b, c) {
          var d2 = this;
          this.g && this.g.release();
          this.g = new es(a, b, c, function(e) {
            return Ps(d2, e);
          });
          this.g.configure(this.l);
        };
        p.initClientSide = function(a, b, c) {
          var d2 = this;
          if (!window7.google || !google.ima || !google.ima.AdsLoader) throw new U(2, 10, 1e4);
          this.j && this.j.release();
          this.j = new Xr(a, b, this.u, c, function(e) {
            return Ps(d2, e);
          });
          this.j.configure(this.l);
        };
        p.release = function() {
          this.g && (this.g.release(), this.g = null);
          this.j && (this.j.release(), this.j = null);
          this.i && (this.i.release(), this.i = null);
          this.h && (this.h.release(), this.h = null);
          lb.prototype.release.call(this);
        };
        p.onAssetUnload = function() {
          this.g && this.g.stop();
          this.j && this.j.stop();
          this.i && this.i.stop();
          this.h && this.h.stop();
          this.dispatchEvent(new T("ad-stopped"));
          this.dispatchEvent(new T("ad-content-attach-requested"));
          this.m = new Qr();
        };
        p.requestClientSideAds = function(a) {
          if (!this.j) throw new U(1, 10, 10001);
          var b = this.j;
          b.g && b.g.destroy();
          b.m && b.m.contentComplete();
          b.H = Date.now() / 1e3;
          b.m.requestAds(a);
        };
        p.updateClientSideAdsRenderingSettings = function(a) {
          if (!this.j) throw new U(1, 10, 10001);
          var b = this.j;
          b.D = a;
          b.g && b.g.updateAdsRenderingSettings(b.D);
        };
        p.initMediaTailor = function(a, b, c) {
          var d2 = this;
          this.i && this.i.release();
          this.i = new As(a, b, c, function(e) {
            return Ps(d2, e);
          });
        };
        p.requestMediaTailorStream = function(a, b, c) {
          if (!this.i) throw new U(1, 10, 10005);
          var d2 = this.i;
          c = c === void 0 ? "" : c;
          d2.l ? a = Promise.reject(new U(1, 10, 10004)) : (d2.l = new Mg(), Ds(d2, a, b), d2.I = c || "", d2.P = Date.now() / 1e3, a = d2.l);
          return a;
        };
        p.addMediaTailorTrackingUrl = function(a) {
          if (!this.i) throw new U(1, 10, 10005);
          var b = this.i;
          b.H = a;
          b.i(new T("ads-loaded", (/* @__PURE__ */ new Map()).set("loadTime", 0)));
        };
        p.initServerSide = function(a, b) {
          var c = this;
          if (!window7.google || !google.ima || !google.ima.dai) throw new U(2, 10, 10002);
          this.h && this.h.release();
          this.h = new Ms(a, b, this.u, function(d2) {
            return Ps(c, d2);
          });
          this.h.configure(this.l);
        };
        p.requestServerSideStream = function(a, b) {
          b = b === void 0 ? "" : b;
          if (!this.h) throw new U(1, 10, 10003);
          a.adTagParameters || (a.adTagParameters = {});
          var c = a.adTagParameters;
          (c.mpt || c.mpv) && bb('You have attempted to set "mpt" and/or "mpv" parameters of the ad tag. Please note that those parameters are used for Shaka adoption tracking and will be overridden.');
          a.adTagParameters.mpt = "shaka-player";
          a.adTagParameters.mpv = "v4.15.10";
          c = this.h;
          c.j ? a = Promise.reject(new U(1, 10, 10004)) : (a instanceof google.ima.dai.api.LiveStreamRequest && (c.H = true), c.j = new Mg(), c.g.requestStream(a), c.D = b || "", c.G = Date.now() / 1e3, a = c.j);
          return a;
        };
        p.replaceServerSideAdTagParameters = function(a) {
          if (!this.h) throw new U(1, 10, 10003);
          (a.mpt || a.mpv) && bb('You have attempted to set "mpt" and/or "mpv" parameters of the ad tag. Please note that those parameters are used for Shaka adoption tracking and will be overridden.');
          a.mpt = "Shaka Player";
          a.mpv = "v4.15.10";
          this.h.g.replaceAdTagParameters(a);
        };
        p.getServerSideCuePoints = function() {
          Wc("AdManager.getServerSideCuePoints", "Please use getCuePoints function.");
          return this.getCuePoints();
        };
        p.getCuePoints = function() {
          var a = [];
          this.h && (a = a.concat(this.h.getCuePoints()));
          this.i && (a = a.concat(this.i.getCuePoints()));
          return a;
        };
        p.getStats = function() {
          var a = this.m;
          return {
            loadTimes: a.g,
            averageLoadTime: Rr(a),
            started: a.h,
            overlayAds: a.j,
            playedCompletely: a.l,
            skipped: a.m,
            errors: a.i
          };
        };
        p.onManifestUpdated = function(a) {
          if (this.i) this.i.onManifestUpdated(a);
        };
        p.onDashTimedMetadata = function(a) {
          this.h && a.schemeIdUri == "urn:google:dai:2018" && this.h.g.processMetadata(a.schemeIdUri, a.eventNode ? a.eventNode.attributes.messageData : null, a.startTime);
        };
        p.onHlsTimedMetadata = function(a, b) {
          this.h && this.h.g.processMetadata("ID3", a.data, b);
        };
        p.onCueMetadataChange = function(a) {
          if (this.h) this.h.onCueMetadataChange(a);
        };
        p.onHLSInterstitialMetadata = function(a, b, c) {
          this.l && this.l.disableHLSInterstitial || (this.g || this.initInterstitial(null, a, b), this.g && rs(this.g, c));
        };
        p.onDASHInterstitialMetadata = function(a, b, c) {
          if (!this.l || !this.l.disableDASHInterstitial) {
            var d2 = c.schemeIdUri;
            if (d2 == "urn:mpeg:dash:event:alternativeMPD:insert:2025" || d2 == "urn:mpeg:dash:event:alternativeMPD:replace:2025") {
              if (this.g || this.initInterstitial(null, a, b), this.g && (a = this.g, b = c.schemeIdUri == "urn:mpeg:dash:event:alternativeMPD:replace:2025", d2 = c.schemeIdUri == "urn:mpeg:dash:event:alternativeMPD:insert:2025", b || d2)) {
                for (var e = c.startTime, f = c.endTime, g = null, h = 0, k2, l = t2(c.eventNode.children), m = l.next(); !m.done; m = l.next()) if (m = m.value, m.tagName == "AlternativeMPD") {
                  if (m = m.attributes.uri) {
                    k2 = m;
                    break;
                  }
                } else if (m.tagName == "InsertPresentation" || m.tagName == "ReplacePresentation") {
                  var n = m.attributes.url;
                  if (n) {
                    k2 = n;
                    (l = $d(m, "maxDuration", fe)) && (g = l / c.timescale);
                    (l = $d(m, "returnOffset", fe)) && (h = l / c.timescale);
                    b && h && (f = e + h);
                    break;
                  }
                }
                k2 && ts2(a, [{
                  id: c.id,
                  groupId: null,
                  startTime: e,
                  endTime: f,
                  uri: k2,
                  mimeType: null,
                  isSkippable: false,
                  skipOffset: null,
                  skipFor: null,
                  canJump: true,
                  resumeOffset: d2 ? h : null,
                  playoutLimit: g,
                  once: false,
                  pre: false,
                  post: false,
                  timelineRange: b && !d2,
                  loop: false,
                  overlay: null,
                  displayOnBackground: false,
                  currentVideo: null,
                  background: null
                }]);
              }
            } else (d2 == "urn:mpeg:dash:event:2012" || d2 == "urn:scte:dash:scte214-events") && c.eventNode && Xd(c.eventNode, "OverlayEvent") && (this.g || this.initInterstitial(null, a, b), this.g && us(this.g, c));
          }
        };
        p.addCustomInterstitial = function(a) {
          if (!this.g) throw new U(1, 10, 10006);
          ts2(this.g, [a]);
        };
        p.addAdUrlInterstitial = function(a) {
          if (!this.g) throw new U(1, 10, 10006);
          return this.g.addAdUrlInterstitial(a);
        };
        p.getInterstitialPlayer = function() {
          if (!this.g) throw new U(1, 10, 10006);
          return this.g.Vb();
        };
        function Ps(a, b) {
          if (b && b.type) switch (b.type) {
            case "ads-loaded":
              a.m.g.push(b.loadTime);
              break;
            case "ad-started":
              a.m.h++;
              var c = b.ad;
              c && !c.isLinear() && a.m.j++;
              break;
            case "ad-complete":
              a.m.l++;
              break;
            case "ad-skipped":
              a.m.m++;
              break;
            case "ad-error":
              a.m.i++;
          }
          a.dispatchEvent(b);
        }
        S("shaka.ads.AdManager", Os);
        Os.prototype.getInterstitialPlayer = Os.prototype.getInterstitialPlayer;
        Os.prototype.addAdUrlInterstitial = Os.prototype.addAdUrlInterstitial;
        Os.prototype.addCustomInterstitial = Os.prototype.addCustomInterstitial;
        Os.prototype.onDASHInterstitialMetadata = Os.prototype.onDASHInterstitialMetadata;
        Os.prototype.onHLSInterstitialMetadata = Os.prototype.onHLSInterstitialMetadata;
        Os.prototype.onCueMetadataChange = Os.prototype.onCueMetadataChange;
        Os.prototype.onHlsTimedMetadata = Os.prototype.onHlsTimedMetadata;
        Os.prototype.onDashTimedMetadata = Os.prototype.onDashTimedMetadata;
        Os.prototype.onManifestUpdated = Os.prototype.onManifestUpdated;
        Os.prototype.getStats = Os.prototype.getStats;
        Os.prototype.getCuePoints = Os.prototype.getCuePoints;
        Os.prototype.getServerSideCuePoints = Os.prototype.getServerSideCuePoints;
        Os.prototype.replaceServerSideAdTagParameters = Os.prototype.replaceServerSideAdTagParameters;
        Os.prototype.requestServerSideStream = Os.prototype.requestServerSideStream;
        Os.prototype.initServerSide = Os.prototype.initServerSide;
        Os.prototype.addMediaTailorTrackingUrl = Os.prototype.addMediaTailorTrackingUrl;
        Os.prototype.requestMediaTailorStream = Os.prototype.requestMediaTailorStream;
        Os.prototype.initMediaTailor = Os.prototype.initMediaTailor;
        Os.prototype.updateClientSideAdsRenderingSettings = Os.prototype.updateClientSideAdsRenderingSettings;
        Os.prototype.requestClientSideAds = Os.prototype.requestClientSideAds;
        Os.prototype.onAssetUnload = Os.prototype.onAssetUnload;
        Os.prototype.release = Os.prototype.release;
        Os.prototype.initClientSide = Os.prototype.initClientSide;
        Os.prototype.initInterstitial = Os.prototype.initInterstitial;
        Os.prototype.configure = Os.prototype.configure;
        Os.prototype.setLocale = Os.prototype.setLocale;
        Os.ADS_LOADED = "ads-loaded";
        Os.AD_STARTED = "ad-started";
        Os.AD_FIRST_QUARTILE = "ad-first-quartile";
        Os.AD_MIDPOINT = "ad-midpoint";
        Os.AD_THIRD_QUARTILE = "ad-third-quartile";
        Os.AD_COMPLETE = "ad-complete";
        Os.AD_STOPPED = "ad-stopped";
        Os.AD_SKIPPED = "ad-skipped";
        Os.AD_VOLUME_CHANGED = "ad-volume-changed";
        Os.AD_MUTED = "ad-muted";
        Os.AD_PAUSED = "ad-paused";
        Os.AD_RESUMED = "ad-resumed";
        Os.AD_SKIP_STATE_CHANGED = "ad-skip-state-changed";
        Os.CUEPOINTS_CHANGED = "ad-cue-points-changed";
        Os.IMA_AD_MANAGER_LOADED = "ima-ad-manager-loaded";
        Os.IMA_STREAM_MANAGER_LOADED = "ima-stream-manager-loaded";
        Os.AD_CLICKED = "ad-clicked";
        Os.AD_PROGRESS = "ad-progress";
        Os.AD_BUFFERING = "ad-buffering";
        Os.AD_IMPRESSION = "ad-impression";
        Os.AD_DURATION_CHANGED = "ad-duration-changed";
        Os.AD_CLOSED = "ad-closed";
        Os.AD_LOADED = "ad-loaded";
        Os.ALL_ADS_COMPLETED = "all-ads-completed";
        Os.AD_LINEAR_CHANGED = "ad-linear-changed";
        Os.AD_METADATA = "ad-metadata";
        Os.AD_RECOVERABLE_ERROR = "ad-recoverable-error";
        Os.AD_ERROR = "ad-error";
        Os.AD_BREAK_READY = "ad-break-ready";
        Os.AD_INTERACTION = "ad-interaction";
        Os.AD_CONTENT_PAUSE_REQUESTED = "ad-content-pause-requested";
        Os.AD_CONTENT_RESUME_REQUESTED = "ad-content-resume-requested";
        Os.AD_CONTENT_ATTACH_REQUESTED = "ad-content-attach-requested";
        nq = function() {
          return new Os();
        };
        function Qs(a) {
          return JSON.stringify(a, function(b, c) {
            if (typeof c != "function") {
              if (c instanceof Event || c instanceof T) {
                var d2 = {};
                for (e in c) (b = c[e]) && typeof b == "object" ? e == "detail" && (d2[e] = b) : e in Event || (d2[e] = b);
                return d2;
              }
              if (c instanceof Error) {
                var e = /* @__PURE__ */ new Set(["name", "message", "stack"]);
                for (d2 in c) e.add(d2);
                d2 = t2(Object.getOwnPropertyNames(c));
                for (b = d2.next(); !b.done; b = d2.next()) e.add(b.value);
                d2 = {};
                e = t2(e);
                for (b = e.next(); !b.done; b = e.next()) b = b.value, d2[b] = c[b];
                c = {
                  __type__: "Error",
                  contents: d2
                };
              } else if (c instanceof TimeRanges) {
                e = {
                  __type__: "TimeRanges",
                  length: c.length,
                  start: [],
                  end: []
                };
                c = t2(Lj(c));
                for (d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, b = d2.end, e.start.push(d2.start), e.end.push(b);
                c = e;
              } else c = ArrayBuffer.isView(c) && c.BYTES_PER_ELEMENT === 1 ? {
                __type__: "Uint8Array",
                entries: Array.from(c)
              } : typeof c == "number" ? isNaN(c) ? "NaN" : isFinite(c) ? c : c < 0 ? "-Infinity" : "Infinity" : c;
              return c;
            }
          });
        }
        function Rs(a) {
          return JSON.parse(a, function(b, c) {
            if (c == "NaN") var d2 = NaN;
            else if (c == "-Infinity") d2 = -Infinity;
            else if (c == "Infinity") d2 = Infinity;
            else if (c && typeof c == "object" && c.__type__ == "TimeRanges") d2 = Ss(c);
            else if (c && typeof c == "object" && c.__type__ == "Uint8Array") d2 = new Uint8Array(c.entries);
            else if (c && typeof c == "object" && c.__type__ == "Error") {
              b = c.contents;
              c = Error(b.message);
              for (d2 in b) c[d2] = b[d2];
              d2 = c;
            } else d2 = c;
            return d2;
          });
        }
        function Ss(a) {
          return {
            length: a.length,
            start: function(b) {
              return a.start[b];
            },
            end: function(b) {
              return a.end[b];
            }
          };
        }
        var Ts = "ended play playing pause pausing ratechange seeked seeking timeupdate volumechange".split(" "), Us = "buffered currentTime duration ended loop muted paused playbackRate seeking videoHeight videoWidth volume".split(" "), Vs = ["loop", "playbackRate"], Ws = ["pause", "play"], Xs = (/* @__PURE__ */ new Map()).set("getAssetUri", 2).set("getAudioLanguages", 4).set("getAudioLanguagesAndRoles", 4).set("getBufferFullness", 1).set("getBufferedInfo", 2).set("getExpiration", 2).set("getKeyStatuses", 2).set("getPlaybackRate", 2).set("getTextLanguages", 4).set("getTextLanguagesAndRoles", 4).set("isAudioOnly", 10).set("isBuffering", 1).set("isInProgress", 1).set("isLive", 10).set("isTextTrackVisible", 1).set("isVideoOnly", 10).set("keySystem", 10).set("seekRange", 1).set("getLoadMode", 10).set("getManifestType", 10).set("isFullyLoaded", 1).set("isEnded", 1), Ys = (/* @__PURE__ */ new Map()).set("getConfiguration", 4).set("getConfigurationForLowLatency", 4).set("getStats", 5).set("getAudioTracks", 2).set("getChaptersTracks", 2).set("getImageTracks", 2).set("getVideoTracks", 2).set("getTextTracks", 2).set("getVariantTracks", 2), Zs = (/* @__PURE__ */ new Map()).set("getPlayheadTimeAsDate", 1).set("getPresentationStartTimeAsDate", 20).set("getSegmentAvailabilityDuration", 20), $s = [["getConfiguration", "configure", "getConfigurationForLowLatency", "configurationForLowLatency"]], at = [["isTextTrackVisible", "setTextTrackVisibility"]], bt = "cancelTrickPlay configure configurationForLowLatency getChapters resetConfiguration retryStreaming selectAudioLanguage selectAudioTrack selectTextLanguage selectTextTrack selectVariantTrack selectVariantsByLabel selectVideoTrack setTextTrackVisibility trickPlay updateStartTime goToLive useTrickPlayTrackIfAvailable".split(" "), ct = "addChaptersTrack addTextTrackAsync addThumbnailsTrack getAllThumbnails getChaptersAsync getThumbnails attach attachCanvas detach load unload".split(" ");
        function dt(a, b, c, d2, e, f, g) {
          var h = this;
          this.H = a;
          this.K = g;
          this.l = new Cf(b);
          this.L = c;
          this.A = false;
          this.C = d2;
          this.G = e;
          this.M = f;
          this.i = this.m = false;
          this.J = "";
          this.u = null;
          this.D = function() {
            return et(h);
          };
          this.F = function(k2, l) {
            k2 = Rs(l);
            switch (k2.type) {
              case "event":
                var m = k2.targetName, n = Ya(k2.event);
                h.C(m, n);
                break;
              case "update":
                m = k2.update;
                for (n in m) {
                  k2 = h.g[n] || {};
                  for (var q in m[n]) k2[q] = m[n][q];
                }
                h.A && (h.L(), h.A = false);
                break;
              case "asyncComplete":
                if (q = k2.id, n = k2.error, l = k2.res, k2 = h.h.get(q), h.h.delete(q), k2) if (n) {
                  q = new U(n.severity, n.category, n.code);
                  for (m in n) q[m] = n[m];
                  k2.reject(q);
                } else k2.resolve(l);
            }
          };
          this.g = {
            video: {},
            player: {}
          };
          this.I = 0;
          this.h = /* @__PURE__ */ new Map();
          this.j = null;
          ft.add(this);
        }
        p = dt.prototype;
        p.destroy = function() {
          ft.delete(this);
          gt(this);
          ht && it(this);
          this.l && (this.l.stop(), this.l = null);
          this.G = this.C = null;
          this.i = this.m = false;
          this.F = this.D = this.j = this.h = this.g = this.u = null;
          return Promise.resolve();
        };
        p.Qa = function() {
          return this.i;
        };
        p.Yf = function() {
          return this.J;
        };
        p.init = function() {
          if (this.H.length) if (window7.chrome && chrome.cast && chrome.cast.isAvailable) {
            this.m = true;
            this.l.La();
            var a = new chrome.cast.SessionRequest(this.H, [], null, this.K, null);
            a = new chrome.cast.ApiConfig(a, function(b) {
              for (var c = t2(ft), d2 = c.next(); !d2.done; d2 = c.next()) {
                d2 = d2.value;
                var e = b;
                d2.j = new Mg();
                d2.A = true;
                jt(d2, e);
              }
            }, function(b) {
              for (var c = t2(ft), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, kt = b == "available", d2.l.La();
            }, "origin_scoped");
            chrome.cast.initialize(a, function() {
            }, function() {
            });
            kt && this.l.Y(lt);
            (a = ht) && a.status != chrome.cast.SessionStatus.STOPPED ? (this.j = new Mg(), this.A = true, jt(this, a)) : ht = null;
          } else window7.__onGCastApiAvailable !== mt && (nt = window7.__onGCastApiAvailable || null, window7.__onGCastApiAvailable = mt);
        };
        p.bi = function(a) {
          this.u = a;
          this.i && ot(this, {
            type: "appData",
            appData: this.u
          });
        };
        p.cast = function() {
          var a = this;
          return P(function(b) {
            if (!a.m) throw new U(1, 8, 8e3);
            if (!kt) throw new U(1, 8, 8001);
            if (a.i) throw new U(1, 8, 8002);
            a.j = new Mg();
            chrome.cast.requestSession(function(c) {
              return jt(a, c);
            }, function(c) {
              return pt(a, c);
            });
            return G(b, a.j, 0);
          });
        };
        function qt(a) {
          a.i && chrome.cast.requestSession(function(b) {
            return jt(a, b);
          }, function(b) {
            return pt(a, b);
          });
        }
        p.Fd = function() {
          if (this.i) {
            gt(this);
            if (ht) {
              it(this);
              try {
                ht.stop(function() {
                }, function() {
                });
              } catch (a) {
              }
              ht = null;
            }
            et(this);
          }
        };
        p.get = function(a, b) {
          var c = this;
          if (a == "video") {
            if (Ws.includes(b)) return function() {
              return c.xj.apply(c, [a, b].concat(x(Na.apply(0, arguments))));
            };
          } else if (a == "player") {
            if (Zs.has(b) && !this.get("player", "isLive")()) return function() {
            };
            if (bt.includes(b)) return function() {
              return c.xj.apply(c, [a, b].concat(x(Na.apply(0, arguments))));
            };
            if (ct.includes(b)) return function() {
              return c.dm.apply(c, [a, b].concat(x(Na.apply(0, arguments))));
            };
            if (Xs.has(b) || Ys.has(b)) return function() {
              return c.g[a][b];
            };
          }
          return this.g[a][b];
        };
        p.set = function(a, b, c) {
          this.g[a][b] = c;
          ot(this, {
            type: "set",
            targetName: a,
            property: b,
            value: c
          });
        };
        function jt(a, b) {
          var c = a.M();
          ht = b;
          b.addUpdateListener(a.D);
          b.addMessageListener("urn:x-cast:com.google.shaka.v2", a.F);
          et(a);
          ot(a, {
            type: "init",
            initState: c,
            appData: a.u
          });
          a.j.resolve();
        }
        function pt(a, b) {
          var c = 8003;
          switch (b.code) {
            case "cancel":
              c = 8004;
              break;
            case "timeout":
              c = 8005;
              break;
            case "receiver_unavailable":
              c = 8006;
          }
          a.j.reject(new U(2, 8, c, b));
        }
        p.xj = function(a, b) {
          ot(this, {
            type: "call",
            targetName: a,
            methodName: b,
            args: Na.apply(2, arguments)
          });
        };
        p.dm = function(a, b) {
          var c = Na.apply(2, arguments), d2 = new Mg(), e = this.I.toString();
          this.I++;
          this.h.set(e, d2);
          try {
            ot(this, {
              type: "asyncCall",
              targetName: a,
              methodName: b,
              args: c,
              id: e
            });
          } catch (f) {
            d2.reject(f);
          }
          return d2;
        };
        function it(a) {
          var b = ht;
          b.removeUpdateListener(a.D);
          b.removeMessageListener("urn:x-cast:com.google.shaka.v2", a.F);
        }
        function et(a) {
          var b = ht ? ht.status == "connected" : false;
          if (a.i && !b) {
            a.G();
            for (var c in a.g) a.g[c] = {};
            gt(a);
          }
          a.i = b;
          a.J = b ? ht.receiver.friendlyName : "";
          a.l.La();
        }
        function gt(a) {
          if (a.h) for (var b = t2(a.h.keys()), c = b.next(); !c.done; c = b.next()) {
            c = c.value;
            var d2 = a.h.get(c);
            a.h.delete(c);
            d2.reject(new U(1, 7, 7e3));
          }
        }
        function ot(a, b) {
          b = Qs(b);
          var c = ht;
          try {
            c.sendMessage("urn:x-cast:com.google.shaka.v2", b, function() {
            }, eb);
          } catch (d2) {
            throw b = new U(2, 8, 8005, d2), c = new T("error", (/* @__PURE__ */ new Map()).set("detail", b)), a.C("player", c), a.Fd(), b;
          }
        }
        var lt = 0.02, kt = false, ht = null, nt = null, ft = /* @__PURE__ */ new Set();
        function mt(a) {
          nt ? window7.__onGCastApiAvailable = nt : delete window7.__onGCastApiAvailable;
          nt = null;
          if (a) for (var b = t2(ft), c = b.next(); !c.done; c = b.next()) c.value.init();
          typeof window7.__onGCastApiAvailable === "function" && window7.__onGCastApiAvailable(a);
        }
        ;
        function rt(a, b, c, d2) {
          d2 = d2 === void 0 ? false : d2;
          lb.call(this);
          var e = this;
          this.i = a;
          this.h = b;
          this.l = this.u = this.m = this.A = this.j = null;
          this.I = c;
          this.H = d2;
          this.F = [];
          this.D = [];
          this.C = [];
          this.G = /* @__PURE__ */ new Map();
          this.g = null;
          window7.chrome ? (this.g = new dt(c, function() {
            return st(e);
          }, function() {
            return tt(e);
          }, function(f, g) {
            return ut(e, f, g);
          }, function() {
            return vt(e);
          }, function() {
            return wt(e);
          }, d2), xt(this)) : (this.j = this.i, this.A = this.h);
        }
        ma(rt, lb);
        p = rt.prototype;
        p.destroy = function(a) {
          this.g && (a === void 0 ? 0 : a) && this.g.Fd();
          this.l && (this.l.release(), this.l = null);
          a = [];
          this.h && (a.push(this.h.destroy()), this.h = null);
          this.g && (a.push(this.g.destroy()), this.g = null);
          this.A = this.j = this.i = null;
          lb.prototype.release.call(this);
          return Promise.all(a);
        };
        p.Pc = function() {
          return this.j;
        };
        p.Vb = function() {
          return this.A;
        };
        p.Kg = function() {
          return this.g ? this.g.m && kt : false;
        };
        p.Qa = function() {
          return this.g ? this.g.Qa() : false;
        };
        p.Yf = function() {
          return this.g ? this.g.Yf() : "";
        };
        p.cast = function() {
          var a = this;
          return P(function(b) {
            return b.g == 1 ? a.g ? G(b, a.g.cast(), 2) : b.return() : a.h ? G(b, a.h.rc(), 0) : b.return();
          });
        };
        p.bi = function(a) {
          this.g && this.g.bi(a);
        };
        p.Vj = function() {
          this.g && qt(this.g);
        };
        p.Fd = function() {
          this.g && this.g.Fd();
        };
        p.Mi = function(a, b) {
          b = b === void 0 ? false : b;
          var c = this;
          return P(function(d2) {
            if (d2.g == 1) {
              if (a == c.I && b == c.H) return d2.return();
              c.I = a;
              c.H = b;
              if (!c.g) return d2.return();
              c.g.Fd();
              return G(d2, c.g.destroy(), 2);
            }
            c.g = null;
            c.g = new dt(a, function() {
              return st(c);
            }, function() {
              return tt(c);
            }, function(e, f) {
              return ut(c, e, f);
            }, function() {
              return vt(c);
            }, function() {
              return wt(c);
            }, b);
            c.g.init();
            H(d2);
          });
        };
        function xt(a) {
          a.g.init();
          a.l = new Qc();
          for (var b = t2(Ts), c = b.next(); !c.done; c = b.next()) a.l.o(a.i, c.value, function(f) {
            a.g.Qa() || (f = Ya(f), a.m.dispatchEvent(f));
          });
          for (var d2 in Za) a.l.o(a.h, Za[d2], function(f) {
            a.g.Qa() || a.u.dispatchEvent(f);
          });
          a.j = {};
          b = {};
          for (var e in a.i) b = {
            ue: b.ue
          }, b.ue = e, Object.defineProperty(a.j, b.ue, {
            configurable: false,
            enumerable: true,
            get: /* @__PURE__ */ function(f) {
              return function() {
                return yt(a, f.ue);
              };
            }(b),
            set: /* @__PURE__ */ function(f) {
              return function(g) {
                var h = f.ue;
                a.g.Qa() ? a.g.set("video", h, g) : a.i[h] = g;
              };
            }(b)
          });
          a.A = {};
          zt(a, function(f) {
            Object.defineProperty(a.A, f, {
              configurable: false,
              enumerable: true,
              get: function() {
                return At(a, f);
              }
            });
          });
          Bt(a);
          a.m = new lb();
          a.m.Ue = a.j;
          a.u = new lb();
          a.u.Ue = a.A;
          a.l.o(a.h, "unloading", function() {
            a.g && a.g.Qa() || Ct(a);
          });
        }
        function Bt(a) {
          var b = /* @__PURE__ */ new Map();
          zt(a, function(c, d2) {
            b.has(d2) ? (d2 = b.get(d2), c.length < d2.length ? a.G.set(c, d2) : a.G.set(d2, c)) : b.set(d2, c);
          });
        }
        function zt(a, b) {
          function c(k2) {
            return k2 == "constructor" || typeof d2[k2] != "function" ? false : !e.has(k2);
          }
          var d2 = a.h, e = /* @__PURE__ */ new Set(), f;
          for (f in d2) c(f) && (e.add(f), b(f, d2[f]));
          a = Object.getPrototypeOf(d2);
          for (f = Object.getPrototypeOf({}); a && a != f; ) {
            for (var g = t2(Object.getOwnPropertyNames(a)), h = g.next(); !h.done; h = g.next()) h = h.value, c(h) && (e.add(h), b(h, d2[h]));
            a = Object.getPrototypeOf(a);
          }
        }
        function wt(a) {
          var b = {
            video: {},
            player: {},
            playerAfterLoad: {},
            manifest: a.h.ed(),
            startTime: null,
            addThumbnailsTrackCalls: a.F,
            addTextTrackAsyncCalls: a.D,
            addChaptersTrackCalls: a.C
          };
          a.i.pause();
          for (var c = t2(Vs), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, b.video[d2] = a.i[d2];
          a.i.ended || (b.startTime = a.i.currentTime);
          c = t2($s);
          for (d2 = c.next(); !d2.done; d2 = c.next()) {
            var e = d2.value;
            d2 = e[1];
            e = a.h[e[0]]();
            b.player[d2] = e;
          }
          c = t2(at);
          for (d2 = c.next(); !d2.done; d2 = c.next()) e = d2.value, d2 = e[1], e = a.h[e[0]](), b.playerAfterLoad[d2] = e;
          return b;
        }
        function st(a) {
          var b = new T("caststatuschanged");
          a.dispatchEvent(b);
        }
        function tt(a) {
          var b = new T(a.j.paused ? "pause" : "play");
          a.m.dispatchEvent(b);
        }
        function vt(a) {
          for (var b = t2($s), c = b.next(); !c.done; c = b.next()) {
            var d2 = c.value;
            c = d2[1];
            d2 = a.g.get("player", d2[0])();
            a.h[c](d2);
          }
          var e = a.F, f = a.D, g = a.C;
          Ct(a);
          var h = a.g.get("player", "getAssetUri")();
          d2 = a.g.get("video", "ended");
          b = Promise.resolve();
          var k2 = a.i.autoplay;
          c = null;
          d2 || (c = a.g.get("video", "currentTime"));
          var l;
          (d2 = a.g.get("player", "getTextTracks")()) && d2.length && (l = d2.find(function(q) {
            return q.active;
          }));
          var m = a.g.get("player", "isTextTrackVisible")();
          h && (a.i.autoplay = false, b = a.h.load(h, c));
          var n = {};
          c = t2(Vs);
          for (d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, n[d2] = a.g.get("video", d2);
          b.then(function() {
            if (a.i) {
              for (var q = t2(e), r2 = q.next(); !r2.done; r2 = q.next()) {
                r2 = r2.value;
                var u;
                (u = a.Vb()).cf.apply(u, x(r2));
              }
              q = t2(f);
              for (u = q.next(); !u.done; u = q.next()) {
                u = u.value;
                var w;
                (w = a.Vb()).be.apply(w, x(u));
              }
              w = t2(g);
              for (q = w.next(); !q.done; q = w.next()) {
                q = q.value;
                var v;
                (v = a.Vb()).bf.apply(v, x(q));
              }
              v = t2(Vs);
              for (w = v.next(); !w.done; w = v.next()) w = w.value, a.i[w] = n[w];
              v = t2(at);
              for (w = v.next(); !w.done; w = v.next()) q = w.value, w = q[1], q = a.g.get("player", q[0])(), a.h[w](q);
              a.h.Fe(m);
              l && a.h.ai(l.language, l.roles, l.forced);
              a.i.autoplay = k2;
              h && a.i.play();
            }
          }, function(q) {
            q = (/* @__PURE__ */ new Map()).set("detail", q);
            q = new T("error", q);
            a.h.dispatchEvent(q);
          });
        }
        function yt(a, b) {
          if (b == "addEventListener") return function(d2, e, f) {
            return a.m.addEventListener(d2, e, f);
          };
          if (b == "removeEventListener") return function(d2, e, f) {
            return a.m.removeEventListener(d2, e, f);
          };
          if (a.g.Qa() && Object.keys(a.g.g.video).length == 0) {
            var c = a.i[b];
            if (typeof c != "function") return c;
          }
          return a.g.Qa() ? a.g.get("video", b) : (b = a.i[b], typeof b == "function" && (b = b.bind(a.i)), b);
        }
        function At(a, b, c) {
          c = c === void 0 ? false : c;
          a.G.has(b) && (b = a.G.get(b));
          if (b == "addEventListener") return function(d2, e, f) {
            return a.u.addEventListener(d2, e, f);
          };
          if (b == "removeEventListener") return function(d2, e, f) {
            return a.u.removeEventListener(d2, e, f);
          };
          if (b == "getMediaElement") return function() {
            return a.j;
          };
          if (b == "getSharedConfiguration") return a.g.get("player", "getConfiguration");
          if (b == "getNetworkingEngine") return function() {
            return a.h.Lb();
          };
          if (b == "getDrmEngine") return function() {
            return a.h.F;
          };
          if (b == "getAdManager") return function() {
            return a.h.rf();
          };
          if (b == "getQueueManager") return function() {
            return a.h.uh();
          };
          if (b == "setVideoContainer") return function(d2) {
            return a.h.ji(d2);
          };
          if (!c) {
            if (b == "addThumbnailsTrack") return function() {
              var d2 = Na.apply(0, arguments);
              a.F.push(d2);
              return At(a, b, true).apply(null, x(d2));
            };
            if (b == "addTextTrackAsync") return function() {
              var d2 = Na.apply(0, arguments);
              a.D.push(d2);
              return At(a, b, true).apply(null, x(d2));
            };
            if (b == "addChaptersTrack") return function() {
              var d2 = Na.apply(0, arguments);
              a.C.push(d2);
              return At(a, b, true).apply(null, x(d2));
            };
          }
          if (a.g.Qa()) {
            if (b == "getManifest" || b == "drmInfo") return function() {
              bb(b + "() does not work while casting!");
              return null;
            };
            if (b == "attach" || b == "detach") return function() {
              bb(b + "() does not work while casting!");
              return Promise.resolve();
            };
            if (b == "getChapters") return function() {
              bb(b + "() does not work while casting!");
              return [];
            };
          }
          return a.g.Qa() && Object.keys(a.g.g.video).length == 0 && (Xs.has(b) || Ys.has(b)) || !a.g.Qa() ? a.h[b].bind(a.h) : a.g.get("player", b);
        }
        function ut(a, b, c) {
          a.g.Qa() && (b == "video" ? a.m.dispatchEvent(c) : b == "player" && (c.type == "unloading" && Ct(a), a.u.dispatchEvent(c)));
        }
        function Ct(a) {
          a.F = [];
          a.D = [];
          a.C = [];
        }
        S("shaka.cast.CastProxy", rt);
        rt.prototype.changeReceiverId = rt.prototype.Mi;
        rt.prototype.forceDisconnect = rt.prototype.Fd;
        rt.prototype.suggestDisconnect = rt.prototype.Vj;
        rt.prototype.setAppData = rt.prototype.bi;
        rt.prototype.cast = rt.prototype.cast;
        rt.prototype.receiverName = rt.prototype.Yf;
        rt.prototype.isCasting = rt.prototype.Qa;
        rt.prototype.canCast = rt.prototype.Kg;
        rt.prototype.getPlayer = rt.prototype.Vb;
        rt.prototype.getVideo = rt.prototype.Pc;
        rt.prototype.destroy = rt.prototype.destroy;
        function Dt(a, b, c, d2) {
          lb.call(this);
          var e = this;
          this.h = a;
          this.g = b;
          this.j = new Qc();
          this.I = {
            video: a,
            player: b
          };
          this.G = c || function() {
          };
          this.J = d2 || function(f) {
            return f;
          };
          this.i = null;
          this.H = false;
          this.u = true;
          this.m = 0;
          this.D = false;
          this.C = true;
          this.A = this.l = null;
          this.F = new Cf(function() {
            Et(e);
          });
          Ft(this);
        }
        ma(Dt, lb);
        p = Dt.prototype;
        p.isConnected = function() {
          return this.H;
        };
        p.Dl = function() {
          return this.u;
        };
        p.rm = function(a) {
          this.i = a;
        };
        p.tk = function() {
          this.i = null;
        };
        p.sm = function(a) {
          this.i || (this.i = {
            metadataType: cast.receiver.media.MetadataType.GENERIC
          });
          this.i.title = a;
        };
        p.qm = function(a) {
          this.i || (this.i = {
            metadataType: cast.receiver.media.MetadataType.GENERIC
          });
          this.i.images = [{
            url: a
          }];
        };
        p.pm = function(a) {
          this.i || (this.i = {});
          this.i.artist = a;
          this.i.metadataType = cast.receiver.media.MetadataType.MUSIC_TRACK;
        };
        p.destroy = function() {
          var a = this, b, c;
          return P(function(d2) {
            if (d2.g == 1) return a.j && (a.j.release(), a.j = null), b = [], a.g && (b.push(a.g.destroy()), a.g = null), a.F && (a.F.stop(), a.F = null), a.h = null, a.I = null, a.G = null, a.H = false, a.u = true, a.l = null, a.A = null, lb.prototype.release.call(a), G(d2, Promise.all(b), 2);
            c = cast.receiver.CastReceiverManager.getInstance();
            c.stop();
            H(d2);
          });
        };
        function Ft(a) {
          var b = cast.receiver.CastReceiverManager.getInstance();
          b.onSenderConnected = function() {
            return Gt(a);
          };
          b.onSenderDisconnected = function() {
            return Gt(a);
          };
          b.onSystemVolumeChanged = function() {
            var e = cast.receiver.CastReceiverManager.getInstance().getSystemVolume();
            e && Ht(a, {
              type: "update",
              update: {
                video: {
                  volume: e.level,
                  muted: e.muted
                }
              }
            }, a.l);
            Ht(a, {
              type: "event",
              targetName: "video",
              event: {
                type: "volumechange"
              }
            }, a.l);
          };
          a.A = b.getCastMessageBus("urn:x-cast:com.google.cast.media");
          a.A.onMessage = function(e) {
            return It(a, e);
          };
          a.l = b.getCastMessageBus("urn:x-cast:com.google.shaka.v2");
          a.l.onMessage = function(e) {
            return Jt(a, e);
          };
          b.start();
          b = t2(Ts);
          for (var c = b.next(); !c.done; c = b.next()) a.j.o(a.h, c.value, function(e) {
            return Kt(a, "video", e);
          });
          for (var d2 in Za) a.j.o(a.g, Za[d2], function(e) {
            return Kt(a, "player", e);
          });
          a.j.o(a.h, "loadeddata", function() {
            a.D = true;
          });
          a.j.o(a.g, "loading", function() {
            a.u = false;
            Lt(a);
          });
          a.j.o(a.h, "playing", function() {
            a.u = false;
            Lt(a);
          });
          a.j.o(a.h, "pause", function() {
            Lt(a);
          });
          a.j.o(a.g, "unloading", function() {
            a.u = true;
            Lt(a);
          });
          a.j.o(a.h, "ended", function() {
            new Cf(function() {
              a.h && a.h.ended && (a.u = true, Lt(a));
            }).Y(Mt);
          });
        }
        function Gt(a) {
          a.m = 0;
          a.C = true;
          a.H = cast.receiver.CastReceiverManager.getInstance().getSenders().length != 0;
          Lt(a);
        }
        function Lt(a) {
          var b;
          P(function(c) {
            if (c.g == 1) return G(c, Promise.resolve(), 2);
            if (!a.g) return c.return();
            b = new T("caststatuschanged");
            a.dispatchEvent(b);
            Nt(a) || Ot(a);
            H(c);
          });
        }
        function Pt(a, b, c) {
          var d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D;
          P(function(F) {
            switch (F.g) {
              case 1:
                for (d2 in b.player) e = b.player[d2], a.g[d2](e);
                a.G(c);
                f = a.h.autoplay;
                return b.manifest ? (a.h.autoplay = false, sa(F, 5), G(F, a.g.load(b.manifest, b.startTime), 7)) : G(F, Promise.resolve(), 3);
              case 7:
                if (b.addThumbnailsTrackCalls) for (g = t2(b.addThumbnailsTrackCalls), h = g.next(); !h.done; h = g.next()) k2 = h.value, a.g.cf.apply(a.g, x(k2));
                if (b.addTextTrackAsyncCalls) for (l = t2(b.addTextTrackAsyncCalls), m = l.next(); !m.done; m = l.next()) n = m.value, a.g.be.apply(a.g, x(n));
                if (b.addChaptersTrackCalls) for (q = t2(b.addChaptersTrackCalls), r2 = q.next(); !r2.done; r2 = q.next()) u = r2.value, a.g.bf.apply(a.g, x(u));
                ua(F, 3);
                break;
              case 5:
                return w = va(F), v = (/* @__PURE__ */ new Map()).set("detail", w), y = new T("error", v), a.g && a.g.dispatchEvent(y), F.return();
              case 3:
                if (!a.g) return F.return();
                for (z in b.video) A = b.video[z], a.h[z] = A;
                for (C in b.playerAfterLoad) D = b.playerAfterLoad[C], a.g[C](D);
                a.h.autoplay = f;
                b.manifest && (a.h.play(), Ot(a));
                H(F);
            }
          });
        }
        function Kt(a, b, c) {
          a.g && (Et(a), Ht(a, {
            type: "event",
            targetName: b,
            event: c
          }, a.l));
        }
        function Et(a) {
          a.F.Y(Qt);
          for (var b = {
            video: {},
            player: {}
          }, c = t2(Us), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, b.video[d2] = a.h[d2];
          a.g.U() && Zs.forEach(function(e, f) {
            a.m % e == 0 && (b.player[f] = a.g[f]());
          });
          Xs.forEach(function(e, f) {
            a.m % e == 0 && (b.player[f] = a.g[f]());
          });
          if (c = cast.receiver.CastReceiverManager.getInstance().getSystemVolume()) b.video.volume = c.level, b.video.muted = c.muted;
          Ht(a, {
            type: "update",
            update: b
          }, a.l);
          Ys.forEach(function(e, f) {
            a.m % e == 0 && (e = {
              player: {}
            }, e.player[f] = a.g[f](), Ht(a, {
              type: "update",
              update: e
            }, a.l));
          });
          a.D && (a.m += 1);
          Nt(a);
        }
        function Nt(a) {
          return a.C && (a.h.duration || a.g.U()) ? (Rt(a), a.C = false, true) : false;
        }
        function Rt(a, b) {
          var c = {
            contentId: a.g.ed(),
            streamType: a.g.U() ? "LIVE" : "BUFFERED",
            contentType: ""
          };
          a.g.U() || (c.duration = a.h.duration);
          a.i && (c.metadata = a.i);
          Ot(a, b === void 0 ? 0 : b, c);
        }
        function Jt(a, b) {
          var c = Rs(b.data);
          switch (c.type) {
            case "init":
              a.m = 0;
              a.D = false;
              a.C = true;
              Pt(a, c.initState, c.appData);
              Et(a);
              break;
            case "appData":
              a.G(c.appData);
              break;
            case "set":
              var d2 = c.targetName, e = c.property;
              c = c.value;
              if (d2 == "video") {
                if (b = cast.receiver.CastReceiverManager.getInstance(), e == "volume") {
                  b.setSystemVolumeLevel(c);
                  break;
                } else if (e == "muted") {
                  b.setSystemVolumeMuted(c);
                  break;
                }
              }
              a.I[d2][e] = c;
              break;
            case "call":
              d2 = a.I[c.targetName];
              d2[c.methodName].apply(d2, c.args);
              break;
            case "asyncCall":
              d2 = c.targetName;
              e = c.methodName;
              d2 == "player" && e == "load" && (a.m = 0, a.D = false);
              var f = c.id, g = b.senderId;
              b = a.I[d2];
              c = b[e].apply(b, c.args);
              d2 == "player" && e == "load" && (c = c.then(function() {
                a.C = true;
              }));
              c.then(function(h) {
                return St(a, g, f, null, h);
              }, function(h) {
                return St(a, g, f, h, null);
              });
          }
        }
        function It(a, b) {
          var c = Rs(b.data);
          switch (c.type) {
            case "PLAY":
              a.h.play();
              Ot(a);
              break;
            case "PAUSE":
              a.h.pause();
              Ot(a);
              break;
            case "SEEK":
              b = c.currentTime;
              var d2 = c.resumeState;
              b != null && (a.h.currentTime = Number(b));
              d2 && d2 == "PLAYBACK_START" ? (a.h.play(), Ot(a)) : d2 && d2 == "PLAYBACK_PAUSE" && (a.h.pause(), Ot(a));
              break;
            case "STOP":
              a.g.rc().then(function() {
                a.g && Ot(a);
              });
              break;
            case "GET_STATUS":
              Rt(a, Number(c.requestId));
              break;
            case "VOLUME":
              d2 = c.volume;
              b = d2.level;
              d2 = d2.muted;
              var e = a.h.volume, f = a.h.muted;
              b != null && (a.h.volume = Number(b));
              d2 != null && (a.h.muted = d2);
              e == a.h.volume && f == a.h.muted || Ot(a);
              break;
            case "LOAD":
              a.m = 0;
              a.D = false;
              a.C = false;
              b = c.media;
              d2 = c.currentTime;
              e = a.J(b.contentId);
              f = c.autoplay || true;
              a.G(b.customData);
              f && (a.h.autoplay = true);
              a.g.load(e, d2).then(function() {
                a.g && Rt(a);
              }).catch(function(g) {
                var h = "LOAD_FAILED";
                g.category == 7 && g.code == 7e3 && (h = "LOAD_CANCELLED");
                Ht(a, {
                  requestId: Number(c.requestId),
                  type: h
                }, a.A);
              });
              break;
            default:
              Ht(a, {
                requestId: Number(c.requestId),
                type: "INVALID_REQUEST",
                reason: "INVALID_COMMAND"
              }, a.A);
          }
        }
        function St(a, b, c, d2, e) {
          a.g && Ht(a, {
            type: "asyncComplete",
            id: c,
            error: d2,
            res: e
          }, a.l, b);
        }
        function Ht(a, b, c, d2) {
          a.H && (a = Qs(b), d2 ? c.getCastChannel(d2).send(a) : c.broadcast(a));
        }
        function Ot(a, b, c) {
          c = c === void 0 ? null : c;
          var d2 = {
            mediaSessionId: 0,
            playbackRate: a.h.playbackRate,
            playerState: a.u ? Tt : a.g.Bf() ? Ut : a.h.paused ? Vt : Wt,
            currentTime: a.h.currentTime,
            supportedMediaCommands: 63,
            volume: {
              level: a.h.volume,
              muted: a.h.muted
            }
          };
          c && (d2.media = c);
          Ht(a, {
            requestId: b === void 0 ? 0 : b,
            type: "MEDIA_STATUS",
            status: [d2]
          }, a.A);
        }
        S("shaka.cast.CastReceiver", Dt);
        Dt.prototype.destroy = Dt.prototype.destroy;
        Dt.prototype.setContentArtist = Dt.prototype.pm;
        Dt.prototype.setContentImage = Dt.prototype.qm;
        Dt.prototype.setContentTitle = Dt.prototype.sm;
        Dt.prototype.clearContentMetadata = Dt.prototype.tk;
        Dt.prototype.setContentMetadata = Dt.prototype.rm;
        Dt.prototype.isIdle = Dt.prototype.Dl;
        Dt.prototype.isConnected = Dt.prototype.isConnected;
        var Qt = 0.5, Mt = 5, Tt = "IDLE", Wt = "PLAYING", Ut = "BUFFERING", Vt = "PAUSED";
        function Xt(a, b, c, d2, e) {
          if (d2 >= e) return null;
          for (var f = -1, g = -1, h = 0; h < c.length; h++) if (c[h].some(function(C) {
            return C != null && C.g.trim() != "";
          })) {
            f = h;
            break;
          }
          for (h = c.length - 1; h >= 0; h--) if (c[h].some(function(C) {
            return C != null && C.g.trim() != "";
          })) {
            g = h;
            break;
          }
          if (f === -1 || g === -1) return null;
          for (var k2 = h = false, l = "white", m = "black", n = Yt(d2, e, h, k2, l, m); f <= g; f++) {
            for (var q = c[f], r2 = -1, u = -1, w = 0; w < q.length; w++) if (q[w] != null && q[w].g.trim() !== "") {
              r2 = w;
              break;
            }
            for (w = q.length - 1; w >= 0; w--) if (q[w] != null && q[w].g.trim() !== "") {
              u = w;
              break;
            }
            if (r2 === -1 || u === -1) q = Zt(d2, e), a.nestedCues.push(q);
            else {
              for (; r2 <= u; r2++) if (w = q[r2]) {
                var v = w.l, y = w.i, z = w.j, A = w.h;
                if (v != h || y != k2 || z != l || A != m) n.payload && a.nestedCues.push(n), n = Yt(d2, e, v, y, z, A), h = v, k2 = y, l = z, m = A;
                n.payload += w.g;
              } else n.payload += " ";
              n.payload && a.nestedCues.push(n);
              f !== g && (n = Zt(d2, e), a.nestedCues.push(n));
              n = Yt(d2, e, h, k2, l, m);
            }
          }
          return a.nestedCues.length ? {
            cue: a,
            stream: b
          } : null;
        }
        function Yt(a, b, c, d2, e, f) {
          a = new se(a, b, "");
          c && a.textDecoration.push(Re);
          d2 && (a.fontStyle = Qe);
          a.color = e;
          a.backgroundColor = f;
          return a;
        }
        function Zt(a, b) {
          a = new se(a, b, "");
          a.lineBreak = true;
          return a;
        }
        function $t(a, b, c, d2, e) {
          this.g = a;
          this.l = b;
          this.i = c;
          this.h = d2;
          this.j = e;
        }
        ;
        function au(a, b) {
          this.i = [];
          this.g = 1;
          this.h = 0;
          this.F = a;
          this.D = b;
          this.j = this.m = false;
          this.l = "white";
          this.u = "black";
          this.A = this.C = null;
          bu(this);
        }
        function cu(a, b, c) {
          var d2 = "CC" + ((a.F << 1 | a.D) + 1), e = new se(b, c, "");
          e.lineInterpretation = 1;
          var f = du.get(a.g);
          f && (e.line = f);
          a.A != null && a.C != null && (e.position = 10 + Math.min(70, a.A * 10) + a.C * 2.5);
          (b = Xt(e, d2, a.i, b, c)) && a.g + b.cue.nestedCues.length - 3 > 15 && (f = du.get(a.g + 3 - b.cue.nestedCues.length)) && (e.line = f);
          return b;
        }
        function bu(a) {
          eu(a, 0, 15);
          a.g = 1;
        }
        function fu(a, b, c) {
          if (!(c < 32 || c > 127)) {
            var d2 = "";
            switch (b) {
              case 0:
                d2 = gu.has(c) ? gu.get(c) : String.fromCharCode(c);
                break;
              case 1:
                d2 = hu.get(c);
                break;
              case 2:
                a.i[a.g].pop();
                d2 = iu.get(c);
                break;
              case 3:
                a.i[a.g].pop(), d2 = ju.get(c);
            }
            d2 && a.i[a.g].push(new $t(d2, a.m, a.j, a.u, a.l));
          }
        }
        function ku(a, b, c, d2) {
          if (!(c < 0 || b < 0)) if (b >= c) for (--d2; d2 >= 0; d2--) a.i[b + d2] = a.i[c + d2].map(function(f) {
            return f;
          });
          else for (var e = 0; e < d2; e++) a.i[b + e] = a.i[c + e].map(function(f) {
            return f;
          });
        }
        function eu(a, b, c) {
          for (var d2 = 0; d2 <= c; d2++) a.i[b + d2] = [];
        }
        var gu = /* @__PURE__ */ new Map([[39, "\u2019"], [42, "\xE1"], [92, "\xE9"], [92, "\xE9"], [94, "\xED"], [95, "\xF3"], [96, "\xFA"], [123, "\xE7"], [124, "\xF7"], [125, "\xD1"], [126, "\xF1"], [127, "\u2588"]]), hu = /* @__PURE__ */ new Map([[48, "\xAE"], [49, "\xB0"], [50, "\xBD"], [51, "\xBF"], [52, "\u2122"], [53, "\xA2"], [54, "\xA3"], [55, "\u266A"], [56, "\xE0"], [57, " "], [58, "\xE8"], [59, "\xE2"], [60, "\xEA"], [61, "\xEE"], [62, "\xF4"], [63, "\xFB"]]), iu = /* @__PURE__ */ new Map([[32, "\xC1"], [33, "\xC9"], [34, "\xD3"], [35, "\xDA"], [36, "\xDC"], [37, "\xFC"], [38, "\u2018"], [39, "\xA1"], [40, "*"], [41, "'"], [42, "\u2500"], [43, "\xA9"], [44, "\u2120"], [45, "\xB7"], [46, "\u201C"], [47, "\u201D"], [48, "\xC0"], [49, "\xC2"], [50, "\xC7"], [51, "\xC8"], [52, "\xCA"], [53, "\xCB"], [54, "\xEB"], [55, "\xCE"], [56, "\xCF"], [57, "\xEF"], [58, "\xD4"], [59, "\xD9"], [60, "\xF9"], [61, "\xDB"], [62, "\xAB"], [63, "\xBB"]]), ju = /* @__PURE__ */ new Map([[32, "\xC3"], [33, "\xE3"], [34, "\xCD"], [35, "\xCC"], [36, "\xEC"], [37, "\xD2"], [38, "\xF2"], [39, "\xD5"], [40, "\xF5"], [41, "{"], [42, "}"], [43, "\\"], [44, "^"], [45, "_"], [46, "|"], [47, "~"], [48, "\xC4"], [49, "\xE4"], [50, "\xD6"], [51, "\xF6"], [52, "\xDF"], [53, "\xA5"], [54, "\xA4"], [55, "\u2502"], [56, "\xC5"], [57, "\xE5"], [58, "\xD8"], [59, "\xF8"], [60, "\u250C"], [61, "\u2510"], [62, "\u2514"], [63, "\u2518"]]), du = /* @__PURE__ */ new Map([[1, 10], [2, 15.33], [3, 20.66], [4, 26], [5, 31.33], [6, 36.66], [7, 42], [8, 47.33], [9, 52.66], [10, 58], [11, 63.33], [12, 68.66], [13, 74], [14, 79.33], [15, 84.66]]);
        function lu(a, b) {
          this.h = 0;
          this.u = new au(a, b);
          this.i = new au(a, b);
          this.g = this.j = new au(a, b);
          this.l = 0;
          this.m = null;
        }
        function mu(a, b, c) {
          a.g = a.i;
          var d2 = a.g, e = null;
          a.h !== 3 && a.h !== 4 && (e = cu(d2, a.l, c), c = a.i, c.g = c.h > 0 ? c.h : 0, eu(c, 0, 15), c = a.j, c.g = c.h > 0 ? c.h : 0, eu(c, 0, 15), d2.g = 15);
          a.h = 3;
          d2.h = b;
          return e;
        }
        function nu(a) {
          a.h = 1;
          a.g = a.j;
          a.g.h = 0;
        }
        function ou(a) {
          cb("Cea608DataChannel", "CEA-608 text mode entered, but is unsupported");
          a.g = a.u;
          a.h = 4;
        }
        var pu = "black green blue cyan red yellow magenta black".split(" "), qu = "white green blue cyan red yellow magenta white_italics".split(" ");
        function ru(a, b) {
          this.J = b;
          this.M = a;
          this.K = this.l = false;
          this.m = this.u = this.H = this.L = this.I = 0;
          this.G = 2;
          this.i = [];
          this.g = this.h = this.j = 0;
          this.F = this.C = false;
          this.D = "white";
          this.A = "black";
          su(this);
        }
        function su(a) {
          a.i = [];
          for (var b = 0; b < 16; b++) a.i.push(tu());
        }
        function tu() {
          for (var a = [], b = 0; b < 42; b++) a.push(null);
          return a;
        }
        function uu(a, b) {
          vu(a) && (a.i[a.h][a.g] = new $t(b, a.F, a.C, a.A, a.D), a.g++);
        }
        function vu(a) {
          var b = a.g < a.m && a.g >= 0;
          return a.h < a.u && a.h >= 0 && b;
        }
        ru.prototype.isVisible = function() {
          return this.l;
        };
        function wu(a) {
          for (var b = 0, c = 1; c < 16; c++, b++) a.i[b] = a.i[c];
          for (c = 0; c < 1; c++, b++) a.i[b] = tu();
        }
        function xu(a, b, c) {
          var d2 = new se(a.j, b, "");
          d2.textAlign = a.G === 0 ? "left" : a.G === 1 ? "right" : ue;
          var e = d2.region;
          a.J && (e.id += "svc" + a.J);
          e.id += "win" + a.M;
          e.height = a.u;
          e.width = a.m;
          e.heightUnits = 2;
          e.widthUnits = 2;
          e.viewportAnchorX = a.I;
          e.viewportAnchorY = a.L;
          e.viewportAnchorUnits = a.K ? rd : 2;
          switch (a.H) {
            case 0:
              e.regionAnchorX = 0;
              e.regionAnchorY = 0;
              break;
            case 1:
              e.regionAnchorX = 50;
              e.regionAnchorY = 0;
              break;
            case 2:
              e.regionAnchorX = 100;
              e.regionAnchorY = 0;
              break;
            case 3:
              e.regionAnchorX = 0;
              e.regionAnchorY = 50;
              break;
            case 4:
              e.regionAnchorX = 50;
              e.regionAnchorY = 50;
              break;
            case 5:
              e.regionAnchorX = 100;
              e.regionAnchorY = 50;
              break;
            case 6:
              e.regionAnchorX = 0;
              e.regionAnchorY = 100;
              break;
            case 7:
              e.regionAnchorX = 50;
              e.regionAnchorY = 100;
              break;
            case 8:
              e.regionAnchorX = 100, e.regionAnchorY = 100;
          }
          if (c = Xt(d2, "svc" + c, a.i, a.j, b)) a.j = b;
          return c;
        }
        ru.prototype.display = function() {
          this.l = true;
        };
        function yu() {
          this.i = [];
          this.h = null;
          this.g = 0;
        }
        function zu(a, b) {
          b.type === 3 ? (a.g = (b.value & 63) * 2 - 1, a.h = []) : a.h && (a.g > 0 && (a.h.push(b), a.g--), a.g === 0 && (a.i.push(new Au(a.h)), a.h = null, a.g = 0));
        }
        function Au(a) {
          this.g = 0;
          this.h = a;
        }
        Au.prototype.Pa = function() {
          return this.g < this.h.length;
        };
        Au.prototype.Ua = function() {
          return this.g;
        };
        function Bu(a) {
          if (!a.Pa()) throw new U(2, 2, 3e3);
          return a.h[a.g++];
        }
        Au.prototype.skip = function(a) {
          if (this.g + a > this.h.length) throw new U(2, 2, 3e3);
          this.g += a;
        };
        Au.prototype.Cj = function(a) {
          if (this.g - a < 0) throw new U(2, 2, 3e3);
          this.g -= a;
        };
        function Cu(a) {
          this.i = a;
          this.h = [null, null, null, null, null, null, null, null];
          this.g = null;
        }
        function Du(a, b, c, d2) {
          if (!a.g) return [];
          if (c == 24) return c = Bu(b).value, d2 = Bu(b).value, c = function(f) {
            return f.map(function(g) {
              return ("0" + (g & 255).toString(16)).slice(-2);
            }).join("");
          }([c, d2]), uu(a.g, String.fromCharCode(parseInt(c, 16))), [];
          b = a.g;
          var e = null;
          switch (c) {
            case 8:
              !vu(b) || b.g <= 0 && b.h <= 0 || (b.g <= 0 ? (b.g = b.m - 1, b.h--) : b.g--, b.i[b.h][b.g] = null);
              break;
            case 13:
              b.isVisible() && (e = xu(b, d2, a.i));
              b.h + 1 >= b.u ? wu(b) : b.h++;
              b.g = 0;
              break;
            case 14:
              b.isVisible() && (e = xu(b, d2, a.i));
              b.i[b.h] = tu();
              b.g = 0;
              break;
            case 12:
              b.isVisible() && (e = xu(b, d2, a.i)), su(b), b.h = 0, b.g = 0;
          }
          return e ? [e] : [];
        }
        function Eu(a, b, c, d2) {
          if (c >= 128 && c <= 135) d2 = c & 7, a.h[d2] && (a.g = a.h[d2]);
          else {
            if (c === 136) {
              c = Bu(b).value;
              b = [];
              c = t2(Fu(a, c));
              for (var e = c.next(); !e.done; e = c.next()) {
                e = a.h[e.value];
                if (e.isVisible()) {
                  var f = xu(e, d2, a.i);
                  f && b.push(f);
                }
                su(e);
              }
              return b;
            }
            if (c === 137) for (b = Bu(b).value, b = t2(Fu(a, b)), c = b.next(); !c.done; c = b.next()) c = a.h[c.value], c.isVisible() || (c.j = d2), c.display();
            else {
              if (c === 138) {
                c = Bu(b).value;
                b = null;
                c = t2(Fu(a, c));
                for (e = c.next(); !e.done; e = c.next()) e = a.h[e.value], e.isVisible() && (b = xu(e, d2, a.i)), e.l = false;
                return b ? [b] : [];
              }
              if (c === 139) {
                c = Bu(b).value;
                b = null;
                c = t2(Fu(a, c));
                for (e = c.next(); !e.done; e = c.next()) e = a.h[e.value], e.isVisible() ? b = xu(e, d2, a.i) : e.j = d2, e.l = !e.l;
                return b ? [b] : [];
              }
              if (c === 140) return b = Bu(b).value, Gu(a, b, d2);
              if (c === 143) return d2 = Gu(a, 255, d2), Hu(a), d2;
              if (c === 144) b.skip(1), d2 = Bu(b).value, a.g && (a.g.C = (d2 & 128) > 0, a.g.F = (d2 & 64) > 0);
              else if (c === 145) d2 = Bu(b).value, c = Bu(b).value, b.skip(1), a.g && (b = Iu((c & 48) >> 4, (c & 12) >> 2, c & 3), a.g.D = Iu((d2 & 48) >> 4, (d2 & 12) >> 2, d2 & 3), a.g.A = b);
              else if (c === 146) d2 = Bu(b).value, b = Bu(b).value, a.g && (a = a.g, a.h = d2 & 15, a.g = b & 63);
              else if (c === 151) b.skip(1), b.skip(1), d2 = Bu(b).value, b.skip(1), a.g && (a.g.G = d2 & 3);
              else if (c >= 152 && c <= 159) {
                c = (c & 15) - 8;
                e = a.h[c] !== null;
                e || (f = new ru(c, a.i), f.j = d2, a.h[c] = f);
                d2 = Bu(b).value;
                f = Bu(b).value;
                var g = Bu(b).value, h = Bu(b).value, k2 = Bu(b).value;
                b = Bu(b).value;
                e && (b & 7) === 0 || (b = a.h[c], b.h = 0, b.g = 0, b.F = false, b.C = false, b.D = "white", b.A = "black");
                b = a.h[c];
                b.l = (d2 & 32) > 0;
                b.L = f & 127;
                b.I = g;
                b.H = (h & 240) >> 4;
                b.K = (f & 128) > 0;
                b.u = (h & 15) + 1;
                b.m = (k2 & 63) + 1;
                a.g = a.h[c];
              }
            }
          }
          return [];
        }
        function Fu(a, b) {
          for (var c = [], d2 = 0; d2 < 8; d2++) (b & 1) === 1 && a.h[d2] && c.push(d2), b >>= 1;
          return c;
        }
        function Gu(a, b, c) {
          var d2 = [];
          b = t2(Fu(a, b));
          for (var e = b.next(); !e.done; e = b.next()) {
            e = e.value;
            var f = a.h[e];
            f.isVisible() && (f = xu(f, c, a.i)) && d2.push(f);
            a.h[e] = null;
          }
          return d2;
        }
        function Hu(a) {
          a.g = null;
          a.h = [null, null, null, null, null, null, null, null];
        }
        function Iu(a, b, c) {
          var d2 = {
            0: 0,
            1: 0,
            2: 1,
            3: 1
          };
          a = d2[a];
          b = d2[b];
          c = d2[c];
          return Ju[a << 2 | b << 1 | c];
        }
        var Ku = /* @__PURE__ */ new Map([[32, " "], [33, "\xA0"], [37, "\u2026"], [42, "\u0160"], [44, "\u0152"], [48, "\u2588"], [49, "\u2018"], [50, "\u2019"], [51, "\u201C"], [52, "\u201D"], [53, "\u2022"], [57, "\u2122"], [58, "\u0161"], [60, "\u0153"], [61, "\u2120"], [63, "\u0178"], [118, "\u215B"], [119, "\u215C"], [120, "\u215D"], [121, "\u215E"], [122, "\u2502"], [123, "\u2510"], [124, "\u2514"], [125, "\u2500"], [126, "\u2518"], [127, "\u250C"]]), Ju = "black blue green cyan red magenta yellow white".split(" ");
        function Lu() {
          this.h = [];
          this.g = [];
          this.i = new yu();
          this.l = 0;
          this.m = /* @__PURE__ */ new Map([["CC1", new lu(0, 0)], ["CC2", new lu(0, 1)], ["CC3", new lu(1, 0)], ["CC4", new lu(1, 1)]]);
          this.A = this.u = 0;
          this.j = /* @__PURE__ */ new Map();
          this.D = true;
          this.C = /* @__PURE__ */ new Set();
          Mu(this);
        }
        Lu.prototype.clear = function() {
          this.l = 0;
          this.h = [];
          this.g = [];
          var a = this.i;
          a.i = [];
          a.h = [];
          a.g = 0;
          Mu(this);
          a = t2(this.j.values());
          for (var b = a.next(); !b.done; b = a.next()) Hu(b.value);
        };
        function Mu(a) {
          a.u = 0;
          a.A = 0;
          for (var b = t2(a.m.values()), c = b.next(); !c.done; c = b.next()) c = c.value, c.h = 0, c.g = c.j, c.m = null, bu(c.i), bu(c.j), bu(c.u);
          a.D = true;
        }
        Lu.prototype.extract = function(a, b) {
          if (this.D) {
            for (var c = t2(this.m.values()), d2 = c.next(); !d2.done; d2 = c.next()) d2.value.l = b;
            this.D = false;
          }
          a = new mh(a, 0);
          if (!(a.getLength() < 8) && a.ba() === 181 && a.Ha() === 49 && a.X() === 1195456820 && a.ba() === 3 && (c = a.ba(), (c & 64) !== 0)) for (c &= 31, a.skip(1), d2 = 0; d2 < c; d2++) {
            var e = a.ba(), f = (e & 4) >> 2, g = a.ba(), h = a.ba();
            f && (e &= 3, e === 0 || e === 1 ? this.h.push({
              pts: b,
              type: e,
              Hb: g,
              sc: h,
              order: this.h.length
            }) : (this.g.push({
              pts: b,
              type: e,
              value: g,
              order: this.g.length
            }), this.g.push({
              pts: b,
              type: 2,
              value: h,
              order: this.g.length
            })));
          }
        };
        Lu.prototype.decode = function() {
          function a(e, f) {
            return e.pts - f.pts || e.order - f.order;
          }
          var b = [];
          this.h.sort(a);
          this.g.sort(a);
          for (var c = t2(this.h), d2 = c.next(); !d2.done; d2 = c.next()) (d2 = Nu(this, d2.value)) && b.push(d2);
          c = t2(this.g);
          for (d2 = c.next(); !d2.done; d2 = c.next()) zu(this.i, d2.value);
          c = t2(this.i.i);
          for (d2 = c.next(); !d2.done; d2 = c.next()) d2 = Ou(this, d2.value), b.push.apply(b, x(d2));
          this.i.i = [];
          this.h = [];
          this.g = [];
          return b;
        };
        function Nu(a, b) {
          var c = b.type;
          if ((b.Hb & 112) === 16) {
            var d2 = b.Hb >> 3 & 1;
            c === 0 ? a.u = d2 : a.A = d2;
          }
          d2 = "CC" + ((c << 1 | (c ? a.A : a.u)) + 1);
          c = a.m.get(d2);
          if (b.Hb === 255 && b.sc === 255 || !b.Hb && !b.sc || !Pu(b.Hb) || !Pu(b.sc)) return ++a.l >= 45 && Mu(a), null;
          a.l = 0;
          b.Hb &= 127;
          b.sc &= 127;
          var e = b.Hb;
          if (e >= 1 && e <= 15 || !b.Hb && !b.sc) return null;
          e = null;
          if ((b.Hb & 112) === 16) a: {
            a.C.add(d2), d2 = b.Hb;
            a = b.sc;
            if (c.m === (d2 << 8 | a)) c.m = null;
            else if (c.m = d2 << 8 | a, (d2 & 240) === 16 && (a & 192) === 64) {
              b = [11, 11, 1, 2, 3, 4, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10][(d2 & 7) << 1 | a >> 5 & 1];
              d2 = "white";
              e = false;
              var f = null;
              var g = a > 95 ? a - 96 : a - 64;
              g <= 13 ? d2 = qu[Math.floor(g / 2)] : g <= 15 ? e = true : f = Math.floor((g - 16) / 2);
              a = (a & 1) === 1;
              c.h !== 4 && (g = c.g, c.h === 3 && b !== g.g && (c = 1 + b - g.h, ku(g, c, 1 + g.g - g.h, g.h), eu(g, 0, c - 1), eu(g, b + 1, 15 - b)), g.g = b, g.m = a, g.j = e, g.l = d2, g.A = f, g.u = "black");
            } else if ((d2 & 247) === 17 && (a & 240) === 32) c.g.m = false, c.g.j = false, c.g.l = "white", fu(c.g, 0, 32), d2 = false, b = qu[(a & 14) >> 1], b === "white_italics" && (b = "white", d2 = true), c.g.m = (a & 1) === 1, c.g.j = d2, c.g.l = b;
            else if ((d2 & 247) === 16 && (a & 240) === 32 || (d2 & 247) === 23 && (a & 255) === 45) b = "black", (d2 & 7) === 0 && (b = pu[(a & 14) >> 1]), c.g.u = b;
            else if ((d2 & 247) === 17 && (a & 240) === 48) fu(c.g, 1, a);
            else if ((d2 & 246) === 18 && (a & 224) === 32) fu(c.g, d2 & 1 ? 3 : 2, a);
            else {
              if ((d2 & 246) === 20 && (a & 240) === 32) {
                a = b.pts;
                d2 = null;
                switch (b.sc) {
                  case 32:
                    nu(c);
                    break;
                  case 33:
                    c = c.g;
                    c.i[c.g].pop();
                    break;
                  case 37:
                    d2 = mu(c, 2, a);
                    break;
                  case 38:
                    d2 = mu(c, 3, a);
                    break;
                  case 39:
                    d2 = mu(c, 4, a);
                    break;
                  case 40:
                    fu(c.g, 0, 32);
                    break;
                  case 41:
                    c.h = 2;
                    c.g = c.i;
                    c.g.h = 0;
                    c.l = a;
                    break;
                  case 42:
                    bu(c.u);
                    ou(c);
                    break;
                  case 43:
                    ou(c);
                    break;
                  case 44:
                    b = c.i;
                    d2 = null;
                    c.h !== 4 && (d2 = cu(b, c.l, a));
                    eu(b, 0, 15);
                    break;
                  case 45:
                    b = c.g;
                    c.h !== 3 ? d2 = null : (d2 = cu(b, c.l, a), e = b.g - b.h + 1, ku(b, e - 1, e, b.h), eu(b, 0, e - 1), eu(b, b.g, 15 - b.g), c.l = a);
                    break;
                  case 46:
                    eu(c.j, 0, 15);
                    break;
                  case 47:
                    b = null, c.h !== 4 && (b = cu(c.i, c.l, a)), d2 = c.j, c.j = c.i, c.i = d2, nu(c), c.l = a, d2 = b;
                }
                e = d2;
                break a;
              }
              (d2 == 23 || d2 == 31) && a >= 33 && a <= 35 && (c.g.C = a - 32);
            }
            e = null;
          }
          else a = b.sc, fu(c.g, 0, b.Hb), fu(c.g, 0, a);
          return e;
        }
        function Ou(a, b) {
          var c = [];
          try {
            for (; b.Pa(); ) {
              var d2 = Bu(b).value, e = (d2 & 224) >> 5, f = d2 & 31;
              e === 7 && f != 0 && (e = Bu(b).value & 63);
              if (e != 0) {
                a.C.add("svc" + e);
                a.j.has(e) || a.j.set(e, new Cu(e));
                for (var g = a.j.get(e), h = b.Ua(); b.Ua() - h < f; ) {
                  e = g;
                  var k2 = b, l = Bu(k2), m = l.value, n = l.pts;
                  if (m === 16) {
                    var q = Bu(k2);
                    m = m << 16 | q.value;
                  }
                  if (m >= 0 && m <= 31) var r2 = Du(e, k2, m, n);
                  else if (m >= 128 && m <= 159) r2 = Eu(e, k2, m, n);
                  else {
                    if (m >= 4096 && m <= 4127) e = k2, k2 = m & 255, k2 >= 8 && k2 <= 15 ? e.skip(1) : k2 >= 16 && k2 <= 23 ? e.skip(2) : k2 >= 24 && k2 <= 31 && e.skip(3);
                    else if (m >= 4224 && m <= 4255) e = k2, k2 = m & 255, k2 >= 128 && k2 <= 135 ? e.skip(4) : k2 >= 136 && k2 <= 143 && e.skip(5);
                    else if (m >= 32 && m <= 127) k2 = m, e.g && (k2 === 127 ? uu(e.g, "\u266A") : uu(e.g, String.fromCharCode(k2)));
                    else if (m >= 160 && m <= 255) e.g && uu(e.g, String.fromCharCode(m));
                    else if (m >= 4128 && m <= 4223) {
                      if (k2 = m & 255, e.g) if (Ku.has(k2)) {
                        var u = Ku.get(k2);
                        uu(e.g, u);
                      } else uu(e.g, "_");
                    } else m >= 4256 && m <= 4351 && e.g && ((m & 255) != 160 ? uu(e.g, "_") : uu(e.g, "[CC]"));
                    r2 = [];
                  }
                  c.push.apply(c, x(r2));
                }
              }
            }
          } catch (w) {
            if (w instanceof U && w.code === 3e3) cb("CEA708_INVALID_DATA", "Buffer read out of bounds / invalid CEA-708 Data.");
            else throw w;
          }
          return c;
        }
        function Pu(a) {
          for (var b = 0; a; ) b ^= a & 1, a >>= 1;
          return b === 1;
        }
        Lu.prototype.getStreams = function() {
          return Array.from(this.C);
        };
        S("shaka.cea.CeaDecoder", Lu);
        nd = function() {
          return new Lu();
        };
        function Qu(a) {
          for (var b = [], c = a, d2 = a = 0; d2 < c.length; ) a == 2 && c[d2] == 3 ? (a = 0, c = [].concat(x(c)), c.splice(d2, 1), c = new Uint8Array(c)) : c[d2] == 0 ? a++ : a = 0, d2++;
          a = c;
          for (d2 = 0; d2 < a.length; ) {
            for (c = 0; a[d2] == 255; ) c += 255, d2++;
            c += a[d2++];
            for (var e = 0; a[d2] == 255; ) e += 255, d2++;
            e += a[d2++];
            c == 4 && b.push(a.subarray(d2, d2 + e));
            d2 += e;
          }
          return b;
        }
        ;
        function Ru() {
          this.j = /* @__PURE__ */ new Map();
          this.i = this.h = 0;
          this.g = Su;
        }
        Ru.prototype.init = function(a) {
          function b(f) {
            f = f.name;
            Tu.has(f) && (c.g = Tu.get(f));
          }
          var c = this, d2 = [], e = [];
          new ph().box("moov", uh).box("mvex", uh).W("trex", function(f) {
            var g = f.reader;
            g.skip(4);
            g.skip(4);
            f = g.X();
            g = g.X();
            c.h = f;
            c.i = g;
          }).box("trak", uh).W("tkhd", function(f) {
            var g = f.reader;
            f = f.version;
            f == 1 ? (g.skip(8), g.skip(8)) : (g.skip(4), g.skip(4));
            var h = g.X();
            f == 1 ? g.skip(8) : g.skip(4);
            g.skip(4);
            g.skip(8);
            g.skip(2);
            g.skip(2);
            g.skip(2);
            g.skip(2);
            g.skip(36);
            g.Ha();
            g.Ha();
            g.Ha();
            g.Ha();
            d2.push(h);
          }).box("mdia", uh).W("mdhd", function(f) {
            f = Oi(f.reader, f.version);
            e.push(f.timescale);
          }).box("minf", uh).box("stbl", uh).W("stsd", wh).box("avc1", b).box("avc3", b).box("dvav", b).box("dva1", b).box("hev1", b).box("hvc1", b).box("dvh1", b).box("dvhe", b).box("vvc1", b).box("vvi1", b).box("dvc1", b).box("dvi1", b).box("encv", xh).box("sinf", uh).box("frma", function(f) {
            f = Ri(f.reader).codec;
            Tu.has(f) && (c.g = Tu.get(f));
          }).parse(a, true, true);
          if (!d2.length || !e.length || d2.length != e.length) throw new U(2, 2, 2010);
          this.g == Su && bb("Unable to determine bitstream format for CEA parsing!");
          d2.forEach(function(f, g) {
            c.j.set(f, e[g]);
          });
        };
        Ru.prototype.parse = function(a) {
          var b = this;
          if (this.g == Su) return [];
          var c = [], d2 = 0, e = [];
          new ph().box("moof", function(f) {
            d2 = f.start;
            e = [];
            uh(f);
          }).box("traf", function(f) {
            e.push({
              baseMediaDecodeTime: null,
              ge: b.h,
              ie: b.i,
              tj: [],
              timescale: 9e4
            });
            uh(f);
          }).W("trun", function(f) {
            var g = e[e.length - 1];
            f = Pi(f.reader, f.version, f.flags);
            g.tj.push(f);
          }).W("tfhd", function(f) {
            var g = e[e.length - 1];
            f = Mi(f.reader, f.flags);
            g.ge = f.ge || b.h;
            g.ie = f.ie || b.i;
            f = f.trackId;
            b.j.has(f) && (g.timescale = b.j.get(f));
          }).W("tfdt", function(f) {
            var g = e[e.length - 1];
            f = Ni(f.reader, f.version);
            g.baseMediaDecodeTime = f.baseMediaDecodeTime;
          }).box("mdat", function(f) {
            for (var g = d2 - f.start - 8, h = f.reader.Ua(), k2 = t2(e), l = k2.next(); !l.done; l = k2.next()) l = l.value, l.baseMediaDecodeTime === null ? bb("Unable to find base media decode time for CEA captions!") : (f.reader.seek(h), Uu(b, f.reader, l.baseMediaDecodeTime, l.timescale, l.ge, l.ie, g, l.tj, c));
          }).parse(a, false, true);
          return c;
        };
        function Uu(a, b, c, d2, e, f, g, h, k2) {
          var l = 0, m = f, n = h.map(function(u) {
            return u.Zh;
          });
          n = [].concat.apply([], x(n));
          n.length && (m = n[0].sampleSize || f);
          for (b.skip(g + h[0].Ug); b.Pa(); ) {
            g = b.X();
            var q = b.ba(), r2 = null;
            r2 = false;
            h = 1;
            switch (a.g) {
              case Vu:
                r2 = q & 31;
                r2 = r2 == 6;
                break;
              case Wu:
                h = 2;
                b.skip(1);
                r2 = q >> 1 & 63;
                r2 = r2 == 39 || r2 == 40;
                break;
              case Xu:
                h = 2;
                b.skip(1);
                r2 = q >> 1 & 63;
                r2 = r2 == 23 || r2 == 24;
                break;
              default:
                return;
            }
            if (r2) for (q = 0, l < n.length && (q = n[l].cg || 0), q = (c + q) / d2, h = t2(Qu(b.$b(g - h))), r2 = h.next(); !r2.done; r2 = h.next()) k2.push({
              packet: r2.value,
              pts: q
            });
            else try {
              b.skip(g - h);
            } catch (u) {
              break;
            }
            m -= g + 4;
            m == 0 && (c = l < n.length ? c + (n[l].$h || e) : c + e, l++, l < n.length ? m = n[l].sampleSize || f : m = f);
          }
        }
        S("shaka.cea.Mp4CeaParser", Ru);
        var Su = 0, Vu = 1, Wu = 2, Xu = 3, Tu = (/* @__PURE__ */ new Map()).set("avc1", Vu).set("avc3", Vu).set("dvav", Vu).set("dva1", Vu).set("hev1", Wu).set("hvc1", Wu).set("dvh1", Wu).set("dvhe", Wu).set("vvc1", Xu).set("vvi1", Xu).set("dvc1", Xu).set("dvi1", Xu);
        od("video/mp4", function() {
          return new Ru();
        });
        function Yu() {
          this.g = null;
        }
        Yu.prototype.init = function() {
        };
        Yu.prototype.parse = function(a) {
          this.g ? this.g.clearData() : this.g = new pk();
          var b = [];
          a = Lb(a);
          if (!xk(a)) return b;
          a = this.g.parse(a);
          var c = a.je(), d2 = a.xf();
          a = [];
          switch (c.video) {
            case "avc":
              a.push(6);
              break;
            case "hvc":
              a.push(39), a.push(40);
          }
          if (!a.length) return b;
          c = t2(d2);
          for (d2 = c.next(); !d2.done; d2 = c.next()) if (d2 = d2.value, a.includes(d2.type) && d2.time != null) for (var e = t2(Qu(d2.data)), f = e.next(); !f.done; f = e.next()) b.push({
            packet: f.value,
            pts: d2.time
          });
          return b;
        };
        S("shaka.cea.TsCeaParser", Yu);
        od("video/mp2t", function() {
          return new Yu();
        });
        function Zu(a) {
          var b = 0, c = Pb(a), d2 = c.getUint32(b, true);
          if (d2 != a.byteLength) return [];
          a: {
            a = b + 4 + 2;
            for (b = []; a < c.byteLength - 1; ) {
              d2 = c.getUint16(a, true);
              a += 2;
              var e = c.getUint16(a, true);
              a += 2;
              if ((e & 1) != 0 || e + a > c.byteLength) {
                c = [];
                break a;
              }
              var f = Lb(c, a, e);
              b.push({
                type: d2,
                value: f
              });
              a += e;
            }
            c = b;
          }
          return c;
        }
        function $u(a) {
          a = jc(Td(a));
          a = Zu(a).filter(function(b) {
            return b.type === av;
          })[0];
          if (!a) return null;
          a = Yb(a.value, true);
          return (a = Ld(a, "WRMHEADER")) ? a : null;
        }
        function bv(a) {
          try {
            var b = $u(a);
            if (b) a: {
              for (var c = t2(Vd(b, "DATA")), d2 = c.next(); !d2.done; d2 = c.next()) {
                var e = d2.value;
                if (e.children) for (var f = t2(e.children), g = f.next(); !g.done; g = f.next()) {
                  var h = g.value;
                  if (h.tagName == "LA_URL") {
                    var k2 = Td(h);
                    break a;
                  }
                }
              }
              k2 = "";
            }
            else k2 = "";
            return k2;
          } catch (l) {
            return "";
          }
        }
        var av = 1;
        function cv(a, b, c) {
          var d2 = dv(a), e = null;
          a = [];
          var f = [], g = null, h = new Set(d2.map(function(l) {
            return l.keyId;
          }));
          h.delete(null);
          var k2 = "cenc";
          if (h.size > 1) throw new U(2, 4, 4010);
          if (!b) {
            f = d2.filter(function(l) {
              return l.Td == "urn:mpeg:dash:sea:2012";
            });
            if (f.length > 1) throw new U(2, 4, 4050);
            f.length && (g = ev(f[0]));
            (f = d2.find(function(l) {
              return l.Td == "urn:mpeg:dash:mp4protection:2011";
            })) && f.encryptionScheme && (k2 = f.encryptionScheme);
            f = d2.filter(function(l) {
              return l.Td == "urn:mpeg:dash:mp4protection:2011" ? (e = l.init || e, false) : l.Td != "urn:mpeg:dash:sea:2012";
            });
            f.length && (a = fv(e, k2, f, c, h), a.length == 0 && (a = [oc("", k2, e)]));
          }
          if (d2.length && !g && (b || !f.length)) for (a = [], b = t2(Object.values(c)), c = b.next(); !c.done; c = b.next()) c = c.value, c != "org.w3.clearkey" && a.push(oc(c, k2, e));
          if (h = Array.from(h)[0] || null) for (k2 = t2(a), b = k2.next(); !b.done; b = k2.next()) for (b = t2(b.value.initData), c = b.next(); !c.done; c = b.next()) c.value.keyId = h;
          return {
            Qi: h,
            Qn: e,
            drmInfos: a,
            Hg: g,
            Vi: true
          };
        }
        function gv(a, b, c, d2) {
          var e = cv(a, c, d2);
          if (b.Vi) {
            a = b.drmInfos.length == 1 && !b.drmInfos[0].keySystem;
            c = e.drmInfos.length == 0;
            if (b.drmInfos.length == 0 || a && !c) b.drmInfos = e.drmInfos;
            b.Vi = false;
          } else if (e.drmInfos.length > 0 && (b.drmInfos = b.drmInfos.filter(function(f) {
            return e.drmInfos.some(function(g) {
              return g.keySystem == f.keySystem;
            });
          }), b.drmInfos.length == 0)) throw new U(2, 4, 4008);
          return e.Qi || b.Qi;
        }
        function hv(a) {
          var b = Yd(a.node, "https://dashif.org/CPS", "Laurl");
          if (b && (b = Td(b))) return b;
          if ((b = Yd(a.node, "urn:microsoft:playready", "pro")) && Td(b)) return bv(b);
          if (a = Yd(a.node, "urn:mpeg:cenc:2013", "pssh")) {
            if (a = Td(a)) {
              b = jc(a);
              a = 8;
              b = Pb(b);
              var c = b.getUint8(a);
              a += 20;
              c > 0 && (a += 4 + 16 * b.getUint32(a));
              a = Lb(b, a + 4);
              a = hc(a);
              a = Ld("<pro>" + a + "</pro>");
              return bv(a);
            }
          }
          return "";
        }
        function fv(a, b, c, d2, e) {
          var f = [];
          c = t2(c);
          for (var g = c.next(); !g.done; g = c.next()) {
            g = g.value;
            var h = d2[g.Td];
            if (h) {
              var k2;
              if ((k2 = Yd(g.node, "urn:microsoft:playready", "pro")) && Td(k2)) {
                k2 = Td(k2);
                k2 = jc(k2);
                var l = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]);
                k2 = [{
                  initData: Bh(k2, l, /* @__PURE__ */ new Set(), 0),
                  initDataType: "cenc",
                  keyId: g.keyId
                }];
              } else k2 = null;
              l = null;
              if (g.Td === "urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e") {
                l = g;
                var m = e;
                if (m.size == 0) l = null;
                else {
                  var n = new Uint8Array([16, 119, 239, 236, 192, 178, 77, 2, 172, 227, 60, 30, 82, 226, 251, 75]), q = new Uint8Array([]);
                  l = [{
                    initData: Bh(q, n, m, 1),
                    initDataType: "cenc",
                    keyId: l.keyId
                  }];
                }
              }
              k2 = oc(h, b, g.init || a || k2 || l);
              if (h = iv.get(h)) k2.licenseServerUri = h(g);
              f.push(k2);
            }
          }
          return f;
        }
        function dv(a) {
          var b = [];
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) (c = jv(c.value)) && b.push(c);
          return b;
        }
        function jv(a) {
          var b = a.attributes.schemeIdUri, c = ae(a, "urn:mpeg:cenc:2013", "default_KID"), d2 = Zd(a, "urn:mpeg:cenc:2013", "pssh").map(Ud), e = a.attributes.value;
          if (!b) return null;
          b = b.toLowerCase();
          if (c && (c = c.replace(/-/g, "").toLowerCase(), c.includes(" "))) throw new U(2, 4, 4009);
          var f = [];
          try {
            f = d2.map(function(g) {
              return {
                initDataType: "cenc",
                initData: jc(g),
                keyId: null
              };
            });
          } catch (g) {
            throw new U(2, 4, 4007);
          }
          return {
            node: a,
            Td: b,
            keyId: c,
            init: f.length > 0 ? f : null,
            encryptionScheme: e
          };
        }
        function ev(a) {
          if (!window7.crypto || !window7.crypto.subtle) throw bb("Web Crypto API is not available to decrypt AES-128. (Web Crypto only exists in secure origins like https)"), new U(2, 4, 4042);
          var b = Yd(a.node, "urn:mpeg:dash:schema:sea:2012", "SegmentEncryption");
          if (!b) throw new U(2, 4, 4051);
          if (b.attributes.schemeIdUri != "urn:mpeg:dash:sea:aes128-cbc:2013") throw new U(2, 4, 4051);
          b = Yd(a.node, "urn:mpeg:dash:schema:sea:2012", "CryptoPeriod");
          if (!b) throw new U(2, 4, 4051);
          a = b.attributes.IV;
          b = dc(b.attributes.keyUriTemplate);
          if (!a || !b) throw new U(2, 4, 4051);
          a = kc(a.substr(2));
          if (a.byteLength != 16) throw new U(2, 4, 4048);
          return {
            Jl: b,
            iv: a
          };
        }
        var iv = (/* @__PURE__ */ new Map()).set("com.apple.fps", function(a) {
          if ("apple" === window7.shakaMediaKeysPolyfill) throw new U(2, 4, 4054);
          if (a = Yd(a.node, "https://dashif.org/CPS", "Laurl")) {
            if (a = Td(a)) return a;
          }
          return "";
        }).set("com.widevine.alpha", function(a) {
          var b = Yd(a.node, "https://dashif.org/CPS", "Laurl");
          return b && (b = Td(b)) ? b : (a = Yd(a.node, "urn:microsoft", "laurl")) ? dc(a.attributes.licenseUrl) || "" : "";
        }).set("com.microsoft.playready", hv).set("com.microsoft.playready.recommendation", hv).set("com.microsoft.playready.software", hv).set("com.microsoft.playready.hardware", hv).set("org.w3.clearkey", function(a) {
          var b = Yd(a.node, "https://dashif.org/CPS", "Laurl");
          return b && (b = Td(b)) ? b : (a = Yd(a.node, "http://dashif.org/guidelines/clearKey", "Laurl")) && a.attributes.Lic_type === "EME-1.0" && a && (a = Td(a)) ? a : "";
        });
        function kv(a, b, c, d2, e, f) {
          var g = (/* @__PURE__ */ new Map()).set("RepresentationID", b).set("Number", c).set("SubNumber", d2).set("Bandwidth", e).set("Time", f);
          return a.replace(/\$(RepresentationID|Number|SubNumber|Bandwidth|Time)?(?:%0([0-9]+)([diouxX]))?\$/g, function(h, k2, l, m) {
            if (h == "$$") return "$";
            var n = g.get(k2);
            if (n == null) return h;
            k2 == "RepresentationID" && l && (l = void 0);
            k2 == "Time" && typeof n != "bigint" && (Math.abs(n - Math.round(n)) >= 0.2 && bb("Calculated $Time$ values must be close to integers"), n = Math.round(n));
            switch (m) {
              case void 0:
              case "d":
              case "i":
              case "u":
                h = n.toString();
                break;
              case "o":
                h = n.toString(8);
                break;
              case "x":
                h = n.toString(16);
                break;
              case "X":
                h = n.toString(16).toUpperCase();
                break;
              default:
                h = n.toString();
            }
            l = window7.parseInt(l, 10) || 1;
            return Array(Math.max(0, l - h.length) + 1).join("0") + h;
          });
        }
        function lv(a, b) {
          var c = mv(a, b, "timescale"), d2 = 1;
          c && (d2 = ge(c) || 1);
          c = mv(a, b, "duration");
          var e = (c = ge(c || "")) ? c / d2 : null, f = mv(a, b, "startNumber"), g = Number(mv(a, b, "presentationTimeOffset")) || 0, h = he(f || "");
          if (f == null || h == null) h = 1;
          f = null;
          if (b = nv(a, b, "SegmentTimeline")) {
            b = Sd(b, "S");
            f = d2;
            a = a.ra.duration || Infinity;
            for (var k2 = h, l = [], m = -g, n = 0; n < b.length; ++n) {
              var q = b[n], r2 = b[n + 1], u = $d(q, "t", he), w = $d(q, "d", he), v = $d(q, "r", fe);
              q = $d(q, "k", fe) || 0;
              u != null && (u -= g);
              if (w) {
                u = u != null ? u : m;
                v = v || 0;
                if (v < 0) if (r2) {
                  r2 = $d(r2, "t", he);
                  if (r2 == null) break;
                  else if (u >= r2) break;
                  v = Math.ceil((r2 - u) / w) - 1;
                } else {
                  if (a == Infinity) break;
                  else if (u / f >= a) break;
                  v = Math.ceil((a * f - u) / w) - 1;
                }
                l.length > 0 && u != m && (l[l.length - 1].end = u / f);
                for (r2 = 0; r2 <= v; ++r2) m = u + w, l.push({
                  start: u / f,
                  end: m / f,
                  xi: u,
                  Cc: q,
                  nm: l.length + k2
                }), u = m;
              }
            }
            f = l;
          }
          return {
            timescale: d2,
            og: c,
            ob: e,
            Ge: h,
            Qb: g / d2 || 0,
            vd: g,
            timeline: f
          };
        }
        function ov(a, b) {
          return [b(a.N), b(a.wa), b(a.Aa)].filter(Ff);
        }
        function mv(a, b, c) {
          b = ov(a, b);
          a = null;
          b = t2(b);
          for (var d2 = b.next(); !d2.done && !(a = d2.value.attributes[c]); d2 = b.next()) ;
          return a;
        }
        function nv(a, b, c) {
          b = ov(a, b);
          a = null;
          b = t2(b);
          for (var d2 = b.next(); !d2.done && !(a = Xd(d2.value, c)); d2 = b.next()) ;
          return a;
        }
        function pv(a, b, c, d2, e, f) {
          for (var g = ae(a, "http://www.w3.org/1999/xlink", "href"), h = ae(a, "http://www.w3.org/1999/xlink", "actuate") || "onRequest", k2 = t2(Object.keys(a.attributes)), l = k2.next(); !l.done; l = k2.next()) {
            l = l.value;
            var m = l.split(":"), n = Nd("http://www.w3.org/1999/xlink");
            m[0] == n && delete a.attributes[l];
          }
          if (f >= 5) return Og(new U(2, 4, 4028));
          if (h != "onLoad") return Og(new U(2, 4, 4027));
          var q = nc([d2], [g]);
          return e.request(0, ah(q, b)).cb(function(r2) {
            r2 = Kd(r2.data, a.tagName);
            if (!r2) return Og(new U(2, 4, 4001, g));
            for (a.children = []; r2.children.length; ) {
              var u = r2.children.shift();
              a.children.push(u);
            }
            u = t2(Object.keys(r2.attributes));
            for (var w = u.next(); !w.done; w = u.next()) w = w.value, a.attributes[w] = r2.attributes[w];
            return qv(a, b, c, q[0], e, f + 1);
          });
        }
        function qv(a, b, c, d2, e, f) {
          f = f === void 0 ? 0 : f;
          if (ae(a, "http://www.w3.org/1999/xlink", "href")) {
            var g = pv(a, b, c, d2, e, f);
            c && (g = g.cb(void 0, function() {
              return qv(a, b, c, d2, e, f);
            }));
            return g;
          }
          g = [];
          for (var h = t2(Rd(a)), k2 = h.next(), l = {}; !k2.done; l = {
            ce: void 0
          }, k2 = h.next()) l.ce = k2.value, ae(l.ce, "http://www.w3.org/1999/xlink", "href") == "urn:mpeg:dash:resolve-to-zero:2013" ? a.children = a.children.filter(/* @__PURE__ */ function(m) {
            return function(n) {
              return n !== m.ce;
            };
          }(l)) : l.ce.tagName != "SegmentTimeline" && g.push(qv(l.ce, b, c, d2, e, f));
          return Sg(g).cb(function() {
            return a;
          });
        }
        ;
        function rv(a, b, c, d2, e, f, g) {
          var h, k2 = new ph().W("sidx", function(l) {
            h = sv(b, d2, e, f, g, c, l);
          });
          a && k2.parse(a);
          if (h) return h;
          throw new U(2, 3, 3004);
        }
        function sv(a, b, c, d2, e, f, g) {
          var h = [];
          g.reader.skip(4);
          var k2 = g.reader.X();
          if (k2 == 0) throw new U(2, 3, 3005);
          if (g.version == 0) {
            var l = g.reader.X();
            var m = g.reader.X();
          } else l = g.reader.Qd(), m = g.reader.Qd();
          g.reader.skip(2);
          var n = g.reader.Ha();
          a = a + g.size + m;
          for (m = 0; m < n; m++) {
            var q = g.reader.X(), r2 = (q & 2147483648) >>> 31;
            q &= 2147483647;
            var u = g.reader.X();
            g.reader.skip(4);
            if (r2 == 1) throw new U(2, 3, 3006);
            h.push(new Cj(l / k2 + c, (l + u) / k2 + c, function() {
              return f;
            }, a, a + q - 1, b, c, d2, e));
            l += u;
            a += q;
          }
          g.parser.stop();
          return h;
        }
        ;
        function tv(a) {
          this.h = Pb(a);
          this.g = new mh(this.h, 0);
        }
        tv.prototype.Pa = function() {
          return this.g.Pa();
        };
        function uv(a) {
          var b = vv(a);
          if (b.length > 7) throw new U(2, 3, 3002);
          var c = 0;
          b = t2(b);
          for (var d2 = b.next(); !d2.done; d2 = b.next()) c = 256 * c + d2.value;
          b = vv(a);
          a: {
            d2 = t2(wv);
            for (var e = d2.next(); !e.done; e = d2.next()) if (Kb(b, new Uint8Array(e.value))) {
              d2 = true;
              break a;
            }
            d2 = false;
          }
          if (d2) b = a.h.byteLength - a.g.Ua();
          else {
            if (b.length == 8 && b[1] & 224) throw new U(2, 3, 3001);
            for (e = d2 = 0; e < b.length; e++) {
              var f = b[e];
              d2 = e == 0 ? f & (1 << 8 - b.length) - 1 : 256 * d2 + f;
            }
            b = d2;
          }
          b = a.g.Ua() + b <= a.h.byteLength ? b : a.h.byteLength - a.g.Ua();
          d2 = Pb(a.h, a.g.Ua(), b);
          a.g.skip(b);
          return new xv(c, d2);
        }
        function vv(a) {
          var b = a.g.Ua(), c = a.g.ba();
          if (c == 0) throw new U(2, 3, 3002);
          c = 8 - Math.floor(Math.log2(c));
          a.g.skip(c - 1);
          return Lb(a.h, b, c);
        }
        var wv = [[255], [127, 255], [63, 255, 255], [31, 255, 255, 255], [15, 255, 255, 255, 255], [7, 255, 255, 255, 255, 255], [3, 255, 255, 255, 255, 255, 255], [1, 255, 255, 255, 255, 255, 255, 255]];
        function xv(a, b) {
          this.id = a;
          this.g = b;
        }
        function yv(a) {
          if (a.g.byteLength > 8) throw new U(2, 3, 3002);
          if (a.g.byteLength == 8 && a.g.getUint8(0) & 224) throw new U(2, 3, 3001);
          for (var b = 0, c = 0; c < a.g.byteLength; c++) {
            var d2 = a.g.getUint8(c);
            b = 256 * b + d2;
          }
          return b;
        }
        ;
        function zv(a, b, c, d2, e, f, g, h, k2) {
          function l() {
            return e;
          }
          var m = [];
          a = new tv(a.g);
          for (var n = null, q = null; a.Pa(); ) {
            var r2 = uv(a);
            if (r2.id == 187) {
              var u = Av(r2);
              u && (r2 = c * u.Bm, u = b + u.am, n != null && m.push(new Cj(n + g, r2 + g, l, q, u - 1, f, g, h, k2)), n = r2, q = u);
            }
          }
          n != null && m.push(new Cj(n + g, d2 + g, l, q, null, f, g, h, k2));
          return m;
        }
        function Av(a) {
          var b = new tv(a.g);
          a = uv(b);
          if (a.id != 179) throw new U(2, 3, 3013);
          a = yv(a);
          b = uv(b);
          if (b.id != 183) throw new U(2, 3, 3012);
          b = new tv(b.g);
          for (var c = 0; b.Pa(); ) {
            var d2 = uv(b);
            if (d2.id == 241) {
              c = yv(d2);
              break;
            }
          }
          return {
            Bm: a,
            am: c
          };
        }
        ;
        function Bv(a, b, c) {
          b = nv(a, b, "Initialization");
          if (!b) return null;
          var d2 = a.N.kb(), e = b.attributes.sourceURL;
          e && (d2 = nc(d2, [dc(e)], a.Sb()));
          e = 0;
          var f = null;
          if (b = $d(b, "range", ee)) e = b.start, f = b.end;
          c = new Aj(function() {
            return d2;
          }, e, f, Cv(a), null, null, c, a.wa.encrypted);
          c.codecs = a.N.codecs;
          c.mimeType = a.N.mimeType;
          a.ra && !a.ra.Cf && (c.g = a.ra.start + a.ra.duration);
          return c;
        }
        function Dv(a, b, c) {
          var d2 = Number(mv(a, Ev, "presentationTimeOffset")) || 0, e = mv(a, Ev, "timescale"), f = 1;
          e && (f = ge(e) || 1);
          var g = d2 / f || 0, h = Bv(a, Ev, c);
          Fv(a, h);
          var k2 = Id(a);
          return {
            endTime: -1,
            timeline: -1,
            dd: function() {
              var l = nv(k2, Ev, "RepresentationIndex");
              var m = k2.N.kb();
              l && (l = dc(l.attributes.sourceURL)) && (m = nc(m, [l], k2.Sb()));
              l = Gv(k2);
              return Hv(k2, b, h, m, l.start, l.end, g);
            },
            timescale: f
          };
        }
        function Hv(a, b, c, d2, e, f, g) {
          var h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E;
          return P(function(I) {
            if (I.g == 1) return h = a.presentationTimeline, k2 = !a.Jb || !a.ra.Cf, l = a.ra.start, m = a.ra.duration, n = a.N.mimeType.split("/")[1], q = b, r2 = null, u = [q(d2, e, f, false), n == "webm" ? q(c.T(), c.startByte, c.endByte, true) : null], q = null, G(I, Promise.all(u), 2);
            w = I.h;
            v = w[0];
            y = w[1] || null;
            z = null;
            A = l - g;
            C = l;
            D = m ? l + m : Infinity;
            if (n == "mp4") var J = rv(v, e, d2, c, A, C, D);
            else {
              J = v;
              var K = new tv(y);
              if (uv(K).id != 440786851) throw new U(2, 3, 3008);
              var L = uv(K);
              if (L.id != 408125543) throw new U(2, 3, 3009);
              K = L.g.byteOffset;
              L = new tv(L.g);
              for (var M = null; L.Pa(); ) {
                var N = uv(L);
                if (N.id == 357149030) {
                  M = N;
                  break;
                }
              }
              if (!M) throw new U(2, 3, 3010);
              M = new tv(M.g);
              N = 1e6;
              for (L = null; M.Pa(); ) {
                var O = uv(M);
                if (O.id == 2807729) N = yv(O);
                else if (O.id == 17545) if (O.g.byteLength == 4) L = O.g.getFloat32(0);
                else if (O.g.byteLength == 8) L = O.g.getFloat64(0);
                else throw new U(2, 3, 3003);
              }
              if (L == null) throw new U(2, 3, 3011);
              M = N / 1e9;
              L *= M;
              J = uv(new tv(J));
              if (J.id != 475249515) throw new U(2, 3, 3007);
              J = zv(J, K, M, L, d2, c, A, C, D);
            }
            z = J;
            F = t2(z);
            for (B = F.next(); !B.done; B = F.next()) E = B.value, E.codecs = a.N.codecs, E.mimeType = a.N.mimeType, E.bandwidth = a.bandwidth;
            h.ye(z);
            r2 = new Zl(z);
            k2 && r2.Ed(C, D, true);
            return I.return(r2);
          });
        }
        function Ev(a) {
          return a.Ud;
        }
        function Gv(a) {
          var b = nv(a, Ev, "RepresentationIndex");
          a = mv(a, Ev, "indexRange");
          a = ee(a || "");
          b && (a = $d(b, "range", ee, a));
          return a;
        }
        function Fv(a, b) {
          Iv(a, b);
          if (!Gv(a)) throw new U(2, 4, 4002);
        }
        function Iv(a, b) {
          var c = a.N.mimeType.split("/")[1];
          if (a.N.contentType != tc && c != "mp4" && c != "webm") throw new U(2, 4, 4006);
          if (c == "webm" && !b) throw new U(2, 4, 4005);
        }
        function Cv(a) {
          var b = a.N;
          return {
            bandwidth: a.bandwidth,
            audioSamplingRate: b.audioSamplingRate,
            codecs: b.codecs,
            contentType: b.contentType,
            frameRate: b.frameRate || null,
            height: b.height || null,
            mimeType: b.mimeType,
            channelsCount: b.Pf,
            pixelAspectRatio: b.pixelAspectRatio || null,
            width: b.width || null,
            label: a.wa.label || null,
            roles: a.roles || null,
            language: a.wa.language || null
          };
        }
        ;
        function Jv(a, b, c) {
          var d2 = Bv(a, Kv, c), e = Lv(a);
          if (!e.ob && !e.timeline && e.Ld.length > 1) throw new U(2, 4, 4002);
          if (!e.ob && !a.ra.duration && !e.timeline && e.Ld.length == 1) throw new U(2, 4, 4002);
          if (e.timeline && e.timeline.length == 0) throw new U(2, 4, 4002);
          var f = null, g = null;
          a.Aa.id && a.N.id && (g = b.get(a.Aa.id + "," + a.N.id)) && (f = g.segmentIndex);
          var h = Mv(a.ra.start, a.ra.duration, a.N.kb, e, d2, c, a.N.mimeType, a.N.codecs, a.bandwidth, a.Sb);
          b = !f;
          f ? f.we(h, a.presentationTimeline.Nb()) : f = new Zl(h);
          a.presentationTimeline.ye(h);
          a.Jb && a.ra.Cf || f.Ed(a.ra.start, a.ra.duration ? a.ra.start + a.ra.duration : Infinity, b);
          g && (g.segmentIndex = f);
          return {
            endTime: -1,
            timeline: -1,
            dd: function() {
              f && f.getNumReferences() != 0 || f.Kf(h);
              return Promise.resolve(f);
            },
            timescale: e.timescale
          };
        }
        function Kv(a) {
          return a.Fc;
        }
        function Lv(a) {
          var b = Nv(a);
          a = lv(a, Kv);
          var c = a.Ge;
          c == 0 && (c = 1);
          var d2 = 0;
          a.ob ? d2 = a.ob * (c - 1) : a.timeline && a.timeline.length > 0 && (d2 = a.timeline[0].start);
          return {
            ob: a.ob,
            startTime: d2,
            Ge: c,
            Qb: a.Qb,
            timescale: a.timescale,
            timeline: a.timeline,
            Ld: b
          };
        }
        function Mv(a, b, c, d2, e, f, g, h, k2, l) {
          var m = d2.Ld.length;
          d2.timeline && d2.timeline.length != d2.Ld.length && (m = Math.min(d2.timeline.length, d2.Ld.length));
          for (var n = a - d2.Qb, q = b ? a + b : Infinity, r2 = [], u = d2.startTime, w = {}, v = 0; v < m; w = {
            qg: void 0,
            dg: void 0
          }, v++) {
            w.dg = d2.Ld[v];
            var y = u;
            u = void 0;
            u = d2.ob != null ? y + d2.ob : d2.timeline ? d2.timeline[v].end : y + b;
            w.qg = null;
            w = new Cj(a + y, a + u, /* @__PURE__ */ function(z) {
              return function() {
                z.qg == null && (z.qg = nc(c(), [z.dg.Ql], l()));
                return z.qg;
              };
            }(w), w.dg.start, w.dg.end, e, n, a, q, [], "", null, null, Dj, f);
            w.codecs = h;
            w.mimeType = g;
            w.bandwidth = k2;
            r2.push(w);
          }
          return r2;
        }
        function Nv(a) {
          return [a.N.Fc, a.wa.Fc, a.Aa.Fc].filter(Ff).map(function(b) {
            return Sd(b, "SegmentURL");
          }).reduce(function(b, c) {
            return b.length > 0 ? b : c;
          }).map(function(b) {
            b.attributes.indexRange && !a.Ch && (a.Ch = true);
            var c = dc(b.attributes.media);
            b = $d(b, "mediaRange", ee, {
              start: 0,
              end: null
            });
            return {
              Ql: c,
              start: b.start,
              end: b.end
            };
          });
        }
        ;
        function Ov(a, b, c, d2, e, f, g, h, k2, l) {
          k2 || a.N.zf || (a.N.zf = mv(a, Pv, "initialization"));
          var m = a.N.zf ? Qv(a, g) : null, n = Rv(a);
          Sv(n);
          var q = Id(a);
          if (n.re) return Iv(a, m), {
            endTime: -1,
            timeline: -1,
            dd: function() {
              var y = kv(n.re, q.N.originalId, null, null, q.bandwidth || null, null);
              y = nc(q.N.kb(), [y]);
              return Hv(q, b, m, y, 0, null, n.Qb);
            },
            timescale: n.timescale
          };
          if (n.ob) return d2 || a.wa.contentType === "image" || a.wa.contentType === "text" || (d2 = a.ra.start, l = a.Aa.id, c = a.ra.duration, l = (l = l != null && f.get(l) || c) ? d2 + l : Infinity, a.presentationTimeline.Lh(n.ob), a.presentationTimeline.rj(d2, l)), {
            endTime: -1,
            timeline: -1,
            dd: function() {
              return Tv(q, n, e, m, f, g, h, a.N.eg);
            },
            timescale: n.timescale
          };
          var r2 = null;
          d2 = d2 = null;
          a.Aa.id && a.N.id && (d2 = a.Aa.id + "," + a.N.id, d2 = c.get(d2)) && (r2 = d2.segmentIndex);
          var u = a.ra.start, w = a.ra.duration ? u + a.ra.duration : Infinity;
          if (r2) l = r2, Uv(l, n, u, w, m, a.Jb), l.ib(a.presentationTimeline.Nb());
          else {
            c = 0;
            k2 = -1;
            if (a.Aa.id != null && a.N.id != null) {
              var v = l.get(a.Aa.id);
              if (v) k2 = v.timeline;
              else for (l = t2(l.values()), v = l.next(); !v.done; v = l.next()) if (v = v.value, Math.abs(n.Qb - v.endTime) <= wc && v.Uh.includes(a.N.id)) {
                k2 = v.timeline;
                break;
              } else v.timeline >= c && (c = v.timeline + 1);
            }
            k2 == -1 && (k2 = c);
            r2 = new Vv(a.Jb, n, a.N.originalId, a.bandwidth, a.N.kb, a.Sb, u, w, m, g, a.N.eg, k2);
          }
          n.timeline && a.wa.contentType !== "image" && a.wa.contentType !== "text" && a.presentationTimeline.sj(r2.h ? r2.h.timeline : [], u);
          d2 && a.Jb && (d2.segmentIndex = r2);
          d2 = (d2 = (d2 = n.timeline) && d2[d2.length - 1]) ? d2.end + n.Qb : -1;
          l = -1;
          r2 instanceof Vv && (l = r2.mf());
          return {
            endTime: d2,
            timeline: l,
            dd: function() {
              r2 instanceof Vv && r2.getNumReferences() == 0 && Uv(r2, n, u, w, m, a.Jb);
              return Promise.resolve(r2);
            },
            timescale: n.timescale
          };
        }
        function Pv(a) {
          return a.Tc;
        }
        function Rv(a) {
          var b = lv(a, Pv), c = mv(a, Pv, "media"), d2 = mv(a, Pv, "index"), e = mv(a, Pv, "k"), f = 0;
          e && (f = parseInt(e, 10));
          return {
            og: b.og,
            ob: b.ob,
            timescale: b.timescale,
            Ge: b.Ge,
            Qb: b.Qb,
            vd: b.vd,
            timeline: b.timeline,
            hc: c && dc(c),
            re: d2,
            mimeType: a.N.mimeType,
            codecs: a.N.codecs,
            bandwidth: a.bandwidth,
            Rl: f
          };
        }
        function Sv(a) {
          var b = a.re ? 1 : 0;
          b += a.timeline ? 1 : 0;
          b += a.ob ? 1 : 0;
          if (b == 0) throw new U(2, 4, 4002);
          b != 1 && (a.re && (a.timeline = null), a.og = null, a.ob = null);
          if (!a.re && !a.hc) throw new U(2, 4, 4002);
        }
        function Tv(a, b, c, d2, e, f, g, h) {
          function k2(L) {
            var M = L - v, N = M * w, O = b.og, Q = M * O;
            "BigInt" in window7 && Q > Number.MAX_SAFE_INTEGER && (Q = BigInt(M) * BigInt(O));
            N += q;
            M = N + w;
            O = Math.min(M, m());
            var R = [], V = b.Rl;
            if (V) for (var Ba = (O - N) / V, aa = {}, Oa = 0; Oa < V; aa = {
              Tj: void 0
            }, Oa++) {
              var La = N + Ba * Oa, Ja = La + Ba;
              aa.Tj = Oa;
              aa = new Cj(La, Ja, /* @__PURE__ */ function(Ea) {
                return function() {
                  var ya = kv(y, A, L, Ea.Tj, z, Q);
                  return nc(C(), [ya], D());
                };
              }(aa), 0, null, d2, F, q, m(), [], "", null, null, Dj, f);
              aa.codecs = a.N.codecs;
              aa.mimeType = a.N.mimeType;
              h == 0 ? Oa > 0 && aa.Jd() : Oa % h != 0 && aa.Jd();
              R.push(aa);
            }
            N = new Cj(N, O, function() {
              if (V) return [];
              var Ea = kv(y, A, L, null, z, Q);
              return nc(C(), [Ea], D());
            }, 0, null, d2, F, q, m(), R, "", null, null, Dj, f, R.length > 0);
            N.codecs = a.N.codecs;
            N.mimeType = a.N.mimeType;
            N.bandwidth = a.bandwidth;
            N.j = M;
            return N;
          }
          function l() {
            var L = [Math.max(n.Nb(), q), Math.min(n.Mc(), m())].map(function(M) {
              return M - q;
            });
            L = [Math.ceil(L[0] / w), Math.ceil(L[1] / w) - 1];
            a.N.zb && L[1]++;
            return L.map(function(M) {
              return M + v;
            });
          }
          function m() {
            var L = r2 != null && e.get(r2) || u;
            return L ? q + L : Infinity;
          }
          var n = a.presentationTimeline, q = a.ra.start, r2 = a.Aa.id, u = a.ra.duration, w = b.ob, v = b.Ge, y = b.hc, z = a.bandwidth || null, A = a.N.originalId, C = a.N.kb, D = a.Sb, F = q - b.Qb, B = l();
          c = a.Jb ? Math.max(B[0], B[1] - c + 1) : B[0];
          g = g || B[1];
          B = [];
          for (var E = c; E <= g; ++E) {
            var I = k2(E);
            B.push(I);
          }
          var J = new Zl(B);
          B = n.Mc() < m();
          E = n.U();
          if (B || E) {
            var K = Math.max(c, g + 1);
            c = w;
            a.N.zb && (c = 0.1);
            J.pg(c, function() {
              var L = n.Nb();
              J.ib(L);
              var M = t2(l());
              M.next();
              M = M.next().value;
              for (var N = []; K <= M; ) {
                var O = k2(K);
                N.push(O);
                K++;
              }
              return L > m() && !N.length ? null : N;
            });
          }
          return Promise.resolve(J);
        }
        function Qv(a, b) {
          var c = a.N.zf;
          c || (c = mv(a, Pv, "initialization"));
          if (!c) return null;
          c = dc(c);
          var d2 = a.N.originalId, e = a.bandwidth || null, f = a.N.kb, g = a.Sb;
          b = new Aj(function() {
            var h = kv(c, d2, null, null, e, null);
            return nc(f(), [h], g());
          }, 0, null, Cv(a), null, null, b, a.wa.encrypted);
          b.codecs = a.N.codecs;
          b.mimeType = a.N.mimeType;
          a.ra && !a.ra.Cf && (b.g = a.ra.start + a.ra.duration);
          return b;
        }
        function Vv(a, b, c, d2, e, f, g, h, k2, l, m, n) {
          Zl.call(this, []);
          this.F = a;
          this.h = b;
          this.H = c;
          this.D = d2;
          this.G = e;
          this.J = f;
          this.j = g;
          this.l = h;
          this.A = k2;
          this.C = l;
          this.I = m;
          this.K = n;
          Wv(this);
        }
        ma(Vv, Zl);
        p = Vv.prototype;
        p.getNumReferences = function() {
          return this.h ? this.h.timeline.length : 0;
        };
        p.release = function() {
          Zl.prototype.release.call(this);
          this.h = null;
        };
        p.ib = function(a) {
          if (this.h) {
            for (var b = 0, c = this.h.timeline, d2 = 0; d2 < c.length; d2 += 1) if (c[d2].end + this.j <= a) b += 1;
            else break;
            b > 0 && (this.h.timeline = c.slice(b), this.g.length >= b && (this.g = this.g.slice(b)), this.i += b, this.getNumReferences() === 0 && this.release());
          }
        };
        function Uv(a, b, c, d2, e, f) {
          Xv(a, e);
          a.F = f;
          if (a.h) {
            a.h.vd !== b.vd && (a.h.timeline = b.timeline, a.h.vd = b.vd, a.h.Qb = b.Qb);
            a.h.hc !== b.hc && (a.h.hc = b.hc);
            c = a.h.timeline;
            if (c.length) {
              var g = c[c.length - 1];
              b = b.timeline.filter(function(h) {
                return h.end > g.end;
              });
            } else b = b.timeline.slice();
            b.length > 0 && a.h.timeline.push.apply(a.h.timeline, x(b));
            a.l !== d2 && (a.l = d2);
          } else a.h = b, a.j = c, a.l = d2;
          Wv(a);
        }
        function Xv(a, b) {
          if (a.A !== b) {
            a.A = b;
            a = t2(a.g);
            for (var c = a.next(); !c.done; c = a.next()) (c = c.value) && Fj(c, b);
          }
        }
        function Wv(a) {
          if (a.h && !a.u) {
            for (var b = [], c = t2(a.h.timeline), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, d2.start >= a.l || d2.end <= 0 || b.push(d2);
            a.h.timeline = b;
            a.ib(a.j);
          }
        }
        p.find = function(a) {
          if (this.h && this.h.timeline && this.h.timeline.length && a < this.h.timeline[0].start + this.j) return this.i;
          if (!this.h) return null;
          var b = this.h.timeline;
          if (a < this.j || a >= this.l) return null;
          for (var c = b.length - 1, d2 = 0; d2 < b.length; d2++) {
            var e = b[d2], f = e.start + this.j;
            e = d2 < c ? b[d2 + 1].start + this.j : this.l === Infinity ? e.end + this.j : this.l;
            if (a >= f && a < e) return d2 + this.i;
          }
          return null;
        };
        p.get = function(a) {
          var b = this;
          a -= this.i;
          if (a < 0 || a >= this.getNumReferences() || !this.h) return null;
          var c = this.g[a];
          if (!c) {
            c = this.h.timeline[a];
            var d2 = c.nm, e = c.xi + this.h.vd, f = this.j - this.h.Qb, g = this.j + c.end, h = g;
            a === this.getNumReferences() - 1 && this.l !== Infinity && (h = this.F && Math.abs(h - this.l) > 0.1 ? Math.min(h, this.l) : this.l);
            var k2 = this.h.codecs, l = this.h.mimeType, m = this.h.bandwidth, n = [], q = false;
            c.Cc && this.h && this.h.hc && (q = this.h.hc.includes("$SubNumber$"));
            if (q) {
              q = (c.end - c.start) / c.Cc;
              for (var r2 = {}, u = 0; u < c.Cc; r2 = {
                rg: void 0,
                Uj: void 0
              }, u++) {
                var w = c.start + q * u, v = w + q;
                r2.Uj = u;
                r2.rg = null;
                r2 = new Cj(this.j + w, this.j + v, /* @__PURE__ */ function(y) {
                  return function() {
                    if (!b.h) return [];
                    y.rg == null && (y.rg = Yv(b.h.hc, b.H, d2, b.D, e, y.Uj, b.G, b.J));
                    return y.rg;
                  };
                }(r2), 0, null, this.A, f, this.j, this.l, [], "", null, null, Dj, this.C);
                r2.codecs = k2;
                r2.mimeType = l;
                r2.bandwidth = m;
                this.I == 0 ? u > 0 && r2.Jd() : u % this.I != 0 && r2.Jd();
                n.push(r2);
              }
            }
            c = new Cj(this.j + c.start, h, function() {
              return n.length > 0 || !b.h ? [] : Yv(b.h.hc, b.H, d2, b.D, e, null, b.G, b.J);
            }, 0, null, this.A, f, this.j, this.l, n, "", null, null, Dj, this.C, n.length > 0);
            c.codecs = k2;
            c.mimeType = l;
            c.j = g;
            c.bandwidth = m;
            this.g[a] = c;
          }
          return c;
        };
        p.Kb = function(a) {
          Wv(this);
          for (var b = 0; b < this.getNumReferences(); b++) {
            var c = this.get(b + this.i);
            c && a(c);
          }
        };
        function Yv(a, b, c, d2, e, f, g, h) {
          a = kv(a, b, c, f, d2 || null, e);
          return nc(g(), [a], h()).map(function(k2) {
            return k2.toString();
          });
        }
        p.mf = function() {
          return this.K;
        };
        function Zv(a) {
          this.u = null;
          this.C = a;
          this.H = new Ug();
          this.i = [];
          this.h = null;
          this.m = [];
          this.D = null;
          this.G = [];
          this.F = 300;
          this.l = /* @__PURE__ */ new Map();
          this.j = /* @__PURE__ */ new Map();
          this.g = null;
          this.A = "UNKNOWN";
        }
        Zv.prototype.configure = function(a) {
          this.u = a;
        };
        Zv.prototype.destroy = function() {
          this.C = this.u = null;
          this.i = [];
          this.h = null;
          this.m = [];
          this.G = [];
          this.l.clear();
          this.g != null && (this.g.stop(), this.g = null);
          return this.H.destroy();
        };
        Zv.prototype.setManifestType = function(a) {
          this.A = a;
        };
        function $v(a, b) {
          var c, d2, e, f, g, h, k2;
          return P(function(l) {
            if (l.g == 1) return c = nc(a.i, [aw(a, b)]), d2 = ah(c, a.u.retryParameters), e = a.C.networkingEngine.request(8, d2), Vg(a.H, e), sa(l, 2), G(l, e.promise, 4);
            if (l.g != 2) return f = l.h, g = Xb(f.data), h = JSON.parse(g), h.VERSION == 1 && bw(a, h, f.uri), ua(l, 0);
            if ((k2 = va(l)) && k2.code == 7001) return l.return();
            a.g != null && (a.g.stop(), a.g = null);
            a.g = new Cf(function() {
              $v(a, b);
            });
            a.g.Y(a.F);
            H(l);
          });
        }
        function aw(a, b) {
          if (!a.m.length) return b;
          b = new rb(b);
          var c = a.D || a.m[0], d2 = Math.round(a.C.getBandwidthEstimate()), e = b.g;
          a.A == "DASH" ? (e.add("_DASH_pathway", c), e.add("_DASH_throughput", String(d2))) : a.A == "HLS" && (e.add("_HLS_pathway", c), e.add("_HLS_throughput", String(d2)));
          Ib(e) && wb(b, e);
          return b.toString();
        }
        function bw(a, b, c) {
          a.g != null && (a.g.stop(), a.g = null);
          var d2 = b["RELOAD-URI"] || c;
          a.g = new Cf(function() {
            $v(a, d2);
          });
          if (c = b.TTL) a.F = c;
          a.g.Y(a.F);
          a.m = b["PATHWAY-PRIORITY"] || [];
          a.G = b["PATHWAY-CLONES"] || [];
        }
        function cw(a, b, c, d2) {
          var e = a.l.get(b);
          e || (e = /* @__PURE__ */ new Map());
          e.set(c, d2);
          a.l.set(b, e);
        }
        Zv.prototype.banLocation = function(a) {
          this.j.set(a, Date.now() + 6e4);
        };
        function dw(a, b, c) {
          c = c === void 0 ? false : c;
          b = a.l.get(b) || /* @__PURE__ */ new Map();
          for (var d2 = [], e = t2(a.m), f = e.next(), g = {}; !f.done; g = {
            Nd: void 0
          }, f = e.next()) if (g.Nd = f.value, f = b.get(g.Nd)) d2.push({
            Qh: g.Nd,
            location: f
          });
          else if (f = a.G.find(/* @__PURE__ */ function(k2) {
            return function(l) {
              return l.Zm == k2.Nd;
            };
          }(g))) {
            var h = b.get(f["BASE-ID"]);
            h && (f["URI-REPLACEMENT"].hk ? (h = new rb(h), tb(h, f["URI-REPLACEMENT"].hk), d2.push({
              Qh: g.Nd,
              location: h.toString()
            })) : d2.push({
              Qh: g.Nd,
              location: h
            }));
          }
          e = Date.now();
          g = t2(a.j.keys());
          for (f = g.next(); !f.done; f = g.next()) f = f.value, h = a.j.get(f), e > h && a.j.delete(f);
          d2 = d2.filter(function(k2) {
            for (var l = t2(a.j.keys()), m = l.next(); !m.done; m = l.next()) if (m.value.includes(new rb(k2.location).Ib)) return false;
            return true;
          });
          d2.length && (a.D = d2[0].Qh);
          d2 = d2.map(function(k2) {
            return k2.location;
          });
          if (!d2.length && a.h) {
            for (e = t2(a.h.split(",")), g = e.next(); !g.done; g = e.next()) if (g = b.get(g.value)) a.D = a.h, d2.push(g);
          }
          if (!d2.length) for (b = t2(b.values()), e = b.next(); !e.done; e = b.next()) d2.push(e.value);
          return c ? d2 : nc(a.i, d2);
        }
        ;
        function ew() {
          this.l = [];
          this.h = [];
          this.g = [];
          this.j = [];
          this.i = [];
          this.A = this.u = false;
          this.m = /* @__PURE__ */ new Set();
        }
        p = ew.prototype;
        p.release = function() {
          for (var a = t2(this.h.concat(this.g, this.j, this.i)), b = a.next(); !b.done; b = a.next()) b = b.value, b.segmentIndex && b.segmentIndex.release();
          this.h = [];
          this.g = [];
          this.j = [];
          this.i = [];
          this.l = [];
          this.A = this.u = false;
          this.m.clear();
        };
        p.vl = function() {
          return this.l;
        };
        p.wh = function() {
          return this.j.slice();
        };
        p.Ok = function() {
          return this.i;
        };
        p.Ri = function(a, b) {
          if (a) {
            if (a.type == "audio") for (var c = t2(this.h), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, d2.matchedStreams = d2.matchedStreams.filter(function(e) {
              return e !== a;
            });
            else if (a.type == "video") for (c = t2(this.g), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, d2.matchedStreams = d2.matchedStreams.filter(function(e) {
              return e !== a;
            }), d2.trickModeVideo && (d2.trickModeVideo.matchedStreams = d2.trickModeVideo.matchedStreams.filter(function(e) {
              return e !== a;
            })), d2.dependencyStream && (d2.dependencyStream.matchedStreams = d2.dependencyStream.matchedStreams.filter(function(e) {
              return e !== a;
            }));
            else if (a.type == tc) for (c = t2(this.j), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, d2.matchedStreams = d2.matchedStreams.filter(function(e) {
              return e !== a;
            });
            else if (a.type == "image") for (c = t2(this.i), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, d2.matchedStreams = d2.matchedStreams.filter(function(e) {
              return e !== a;
            });
            a.segmentIndex && a.closeSegmentIndex();
            this.m.delete(b);
          }
        };
        function fw(a, b) {
          var c = [], d2 = [], e = [], f = [];
          a = t2(a);
          for (var g = a.next(); !g.done; g = a.next()) {
            var h = g.value;
            g = new Map(h.audioStreams.map(function(n) {
              return [gw(n), n];
            }));
            var k2 = new Map(h.videoStreams.map(function(n) {
              return [hw(n), n];
            })), l = new Map(h.textStreams.map(function(n) {
              return [iw(n), n];
            }));
            h = new Map(h.imageStreams.map(function(n) {
              return [jw(n), n];
            }));
            if (b) {
              var m = kw(tc);
              l.set(iw(m), m);
              m = kw("image");
              h.set(jw(m), m);
            }
            c.push(g);
            d2.push(k2);
            e.push(l);
            f.push(h);
          }
          return {
            Hi: c,
            ek: d2,
            Zj: e,
            dj: f
          };
        }
        p.Og = function(a, b, c) {
          c = c === void 0 ? false : c;
          var d2 = this, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N, O, Q, R, V, Ba;
          return P(function(aa) {
            if (aa.g == 1) {
              e = vc;
              if (!b && a.length == 1) return f = fw(a, false), g = f.Hi, h = f.ek, k2 = f.Zj, l = f.dj, d2.h = Array.from(g[0].values()), d2.g = Array.from(h[0].values()), d2.j = Array.from(k2[0].values()), d2.i = Array.from(l[0].values()), aa.B(2);
              m = c ? d2.m.size : 0;
              n = -1;
              for (q = 0; q < a.length; q++) r2 = a[q], d2.m.has(r2.id) || (d2.m.add(r2.id), n == -1 && (n = q));
              if (n == -1) return aa.return();
              u = fw(a, true);
              w = u.Hi;
              v = u.ek;
              y = u.Zj;
              z = u.dj;
              return G(aa, Promise.all([lw(d2, d2.h, w, n, mw, nw, m), lw(d2, d2.g, v, n, mw, nw, m), lw(d2, d2.j, y, n, mw, nw, m), lw(d2, d2.i, z, n, mw, nw, m)]), 2);
            }
            A = 0;
            C = [];
            if (d2.g.length && d2.h.length) for (K = t2(d2.h), L = K.next(); !L.done; L = K.next()) for (M = L.value, N = t2(d2.g), O = N.next(); !O.done; O = N.next()) Q = O.value, R = Ag(M.drmInfos, Q.drmInfos), M.drmInfos.length && Q.drmInfos.length && !R.length || (V = (M.bandwidth || 0) + (Q.bandwidth || 0), M.dependencyStream && (V += M.dependencyStream.bandwidth || 0), Q.dependencyStream && (V += Q.dependencyStream.bandwidth || 0), Ba = A++, C.push({
              id: Ba,
              language: M.language,
              disabledUntilTime: 0,
              primary: M.primary,
              audio: M,
              video: Q,
              bandwidth: V,
              drmInfos: R,
              allowedByApplication: true,
              allowedByKeySystem: true,
              decodingInfos: []
            }));
            else for (D = d2.g.length ? d2.g : d2.h, F = t2(D), B = F.next(); !B.done; B = F.next()) E = B.value, I = A++, J = E.bandwidth || 0, E.dependencyStream && (J += E.dependencyStream.bandwidth || 0), C.push({
              id: I,
              language: E.language,
              disabledUntilTime: 0,
              primary: E.primary,
              audio: E.type == e.na ? E : null,
              video: E.type == e.Ja ? E : null,
              bandwidth: J,
              drmInfos: E.drmInfos,
              allowedByApplication: true,
              allowedByKeySystem: true,
              decodingInfos: []
            });
            d2.l = C;
            H(aa);
          });
        };
        function ow(a) {
          var b, c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N;
          return P(function(O) {
            switch (O.g) {
              case 1:
                b = vc;
                if (a.length == 1) return O.return(a[0]);
                c = a.map(function(Q) {
                  return new Map(Q.filter(function(R) {
                    return R.type === b.na;
                  }).map(function(R) {
                    return [gw(R), R];
                  }));
                });
                d2 = a.map(function(Q) {
                  return new Map(Q.filter(function(R) {
                    return R.type === b.Ja;
                  }).map(function(R) {
                    return [hw(R), R];
                  }));
                });
                e = a.map(function(Q) {
                  return new Map(Q.filter(function(R) {
                    return R.type === b.ab;
                  }).map(function(R) {
                    return [iw(R), R];
                  }));
                });
                f = a.map(function(Q) {
                  return new Map(Q.filter(function(R) {
                    return R.type === b.yg;
                  }).map(function(R) {
                    return [jw(R), R];
                  }));
                });
                g = t2(e);
                for (h = g.next(); !h.done; h = g.next()) k2 = h.value, l = pw(b.ab), k2.set(iw(l), l);
                m = t2(f);
                for (n = m.next(); !n.done; n = m.next()) q = n.value, r2 = pw(b.yg), q.set(jw(r2), r2);
                u = new ew();
                return G(O, lw(u, [], c, 0, qw, rw, 0), 2);
              case 2:
                return w = O.h, G(O, lw(u, [], d2, 0, qw, rw, 0), 3);
              case 3:
                return v = O.h, G(O, lw(u, [], e, 0, qw, rw, 0), 4);
              case 4:
                return y = O.h, G(O, lw(u, [], f, 0, qw, rw, 0), 5);
              case 5:
                z = O.h;
                A = 0;
                if (v.length && w.length) for (E = t2(w), I = E.next(); !I.done; I = E.next()) for (J = I.value, K = t2(v), L = K.next(); !L.done; L = K.next()) M = L.value, N = A++, M.variantIds.push(N), J.variantIds.push(N);
                else for (C = v.concat(w), D = t2(C), F = D.next(); !F.done; F = D.next()) B = F.value, B.variantIds = [A++];
                return O.return(v.concat(w).concat(y).concat(z));
            }
          });
        }
        function lw(a, b, c, d2, e, f, g) {
          var h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J;
          return P(function(K) {
            switch (K.g) {
              case 1:
                h = [];
                for (k2 = 0; k2 < c.length; k2++) k2 >= d2 ? h.push(new Set(c[k2].values())) : h.push(/* @__PURE__ */ new Set());
                l = t2(b);
                m = l.next();
              case 2:
                if (m.done) {
                  K.B(4);
                  break;
                }
                n = m.value;
                return G(K, sw(a, n, c, d2, f, h, g), 5);
              case 5:
                q = K.h;
                if (!q) throw new U(2, 4, 4037);
                m = l.next();
                K.B(2);
                break;
              case 4:
                r2 = t2(h);
                for (u = r2.next(); !u.done; u = r2.next()) for (w = u.value, v = t2(w), y = v.next(); !y.done; y = v.next()) z = y.value, (A = tw(a, z, c, e, f, h)) && b.push(A);
                C = t2(h);
                for (D = C.next(); !D.done; D = C.next()) for (F = D.value, B = t2(F), E = B.next(), I = {}; !E.done; I = {
                  li: void 0
                }, E = B.next()) if (I.li = E.value, !uw(I.li) && (J = b.some(/* @__PURE__ */ function(L) {
                  return function(M) {
                    return vw(a, L.li, M);
                  };
                }(I)))) throw new U(2, 4, 4037);
                return K.return(b);
            }
          });
        }
        function sw(a, b, c, d2, e, f, g) {
          return P(function(h) {
            if (h.g == 1) return ww(a, c, b, g > 0), b.matchedStreams ? b.segmentIndex ? G(h, xw(b, d2 + g), 2) : h.B(2) : h.return(false);
            yw(b, d2, e, f, g);
            return h.return(true);
          });
        }
        function xw(a, b) {
          var c, d2, e, f, g, h;
          return P(function(k2) {
            if (k2.g == 1) {
              c = [];
              d2 = a.matchedStreams;
              for (e = b; e < d2.length; e++) f = d2[e], c.push(f.createSegmentIndex()), f.trickModeVideo && !f.trickModeVideo.segmentIndex && c.push(f.trickModeVideo.createSegmentIndex()), f.dependencyStream && !f.dependencyStream.segmentIndex && c.push(f.dependencyStream.createSegmentIndex());
              return G(k2, Promise.all(c), 2);
            }
            if (a.segmentIndex instanceof bm) for (g = b; g < d2.length; g++) h = d2[g], h.segmentIndex && a.segmentIndex.h.push(h.segmentIndex);
            H(k2);
          });
        }
        function tw(a, b, c, d2, e, f) {
          if (uw(b)) return null;
          var g = d2(b);
          ww(a, c, g);
          g.createSegmentIndex && (g.createSegmentIndex = function() {
            return P(function(h) {
              if (g.segmentIndex) return h.B(0);
              g.segmentIndex = new bm();
              return G(h, xw(g, 0), 0);
            });
          });
          if (!g.matchedStreams || !g.matchedStreams.length) return null;
          yw(g, 0, e, f, 0);
          return g;
        }
        function yw(a, b, c, d2, e) {
          var f = a.matchedStreams;
          for (b += e; b < f.length; b++) {
            var g = f[b];
            c(a, g);
            var h = true;
            a.type == "audio" && Fc(a.language, g.language) == 0 && (h = false);
            if (h && (d2[b - e].delete(g), g.fullMimeTypes)) for (g = t2(g.fullMimeTypes.values()), h = g.next(); !h.done; h = g.next()) a.fullMimeTypes.add(h.value);
          }
        }
        function mw(a) {
          var b = Object.assign({}, a);
          b.originalId = null;
          b.createSegmentIndex = function() {
            return Promise.resolve();
          };
          b.closeSegmentIndex = function() {
            b.segmentIndex && (b.segmentIndex.release(), b.segmentIndex = null);
            if (b.matchedStreams) for (var c = t2(b.matchedStreams), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, d2.segmentIndex && (d2.segmentIndex.release(), d2.segmentIndex = null);
          };
          b.roles = b.roles.slice();
          b.segmentIndex = null;
          b.emsgSchemeIdUris = [];
          b.keyIds = new Set(a.keyIds);
          b.closedCaptions = a.closedCaptions ? new Map(a.closedCaptions) : null;
          b.trickModeVideo = null;
          b.dependencyStream = null;
          return b;
        }
        function qw(a) {
          var b = Object.assign({}, a);
          b.roles = b.roles.slice();
          b.keyIds = new Set(a.keyIds);
          b.segments = [];
          b.variantIds = [];
          b.closedCaptions = a.closedCaptions ? new Map(a.closedCaptions) : null;
          return b;
        }
        function nw(a, b) {
          function c(g, h) {
            g || (g = []);
            h = t2(h);
            for (var k2 = h.next(); !k2.done; k2 = h.next()) k2 = k2.value, g.includes(k2) || g.push(k2);
            return g;
          }
          a.roles = c(a.roles, b.roles);
          b.emsgSchemeIdUris && (a.emsgSchemeIdUris = c(a.emsgSchemeIdUris, b.emsgSchemeIdUris));
          for (var d2 = t2(b.keyIds), e = d2.next(); !e.done; e = d2.next()) a.keyIds.add(e.value);
          a.originalId == null ? a.originalId = b.originalId : (d2 = b.originalId || "") && !a.originalId.endsWith(d2) && (a.originalId += "," + d2);
          d2 = Ag(a.drmInfos, b.drmInfos);
          if (b.drmInfos.length && a.drmInfos.length && !d2.length) throw new U(2, 4, 4038);
          a.drmInfos = d2;
          a.encrypted = a.encrypted || b.encrypted;
          if (b.closedCaptions) for (a.closedCaptions || (a.closedCaptions = /* @__PURE__ */ new Map()), d2 = t2(b.closedCaptions), e = d2.next(); !e.done; e = d2.next()) {
            var f = t2(e.value);
            e = f.next().value;
            f = f.next().value;
            a.closedCaptions.set(e, f);
          }
          a.bandwidth && b.bandwidth && (a.bandwidth = Math.max(a.bandwidth, b.bandwidth));
          b.trickModeVideo ? (a.trickModeVideo || (a.trickModeVideo = mw(b.trickModeVideo), a.trickModeVideo.matchedStreams = [], a.trickModeVideo.createSegmentIndex = function() {
            if (a.trickModeVideo.segmentIndex) return Promise.resolve();
            for (var g = new bm(), h = t2(a.trickModeVideo.matchedStreams), k2 = h.next(); !k2.done; k2 = h.next()) g.h.push(k2.value.segmentIndex);
            a.trickModeVideo.segmentIndex = g;
            return Promise.resolve();
          }), a.trickModeVideo.matchedStreams.push(b.trickModeVideo), nw(a.trickModeVideo, b.trickModeVideo)) : a.trickModeVideo && (a.trickModeVideo.matchedStreams.push(b), nw(a.trickModeVideo, b));
          b.dependencyStream ? (a.dependencyStream || (a.dependencyStream = mw(b.dependencyStream), a.dependencyStream.matchedStreams = [], a.dependencyStream.createSegmentIndex = function() {
            if (a.dependencyStream.segmentIndex) return Promise.resolve();
            for (var g = new bm(), h = t2(a.dependencyStream.matchedStreams), k2 = h.next(); !k2.done; k2 = h.next()) g.h.push(k2.value.segmentIndex);
            a.dependencyStream.segmentIndex = g;
            return Promise.resolve();
          }), a.dependencyStream.matchedStreams.push(b.dependencyStream), nw(a.dependencyStream, b.dependencyStream)) : a.dependencyStream && (a.dependencyStream.matchedStreams.push(b), nw(a.dependencyStream, b));
        }
        function rw(a, b) {
          var c = a.roles;
          c || (c = []);
          for (var d2 = t2(b.roles), e = d2.next(); !e.done; e = d2.next()) e = e.value, c.includes(e) || c.push(e);
          a.roles = c;
          c = t2(b.keyIds);
          for (d2 = c.next(); !d2.done; d2 = c.next()) a.keyIds.add(d2.value);
          a.encrypted = a.encrypted && b.encrypted;
          a.segments.push.apply(a.segments, x(b.segments));
          if (b.closedCaptions) for (a.closedCaptions || (a.closedCaptions = /* @__PURE__ */ new Map()), b = t2(b.closedCaptions), c = b.next(); !c.done; c = b.next()) d2 = t2(c.value), c = d2.next().value, d2 = d2.next().value, a.closedCaptions.set(c, d2);
        }
        function ww(a, b, c, d2) {
          d2 = (d2 === void 0 ? 0 : d2) ? c.matchedStreams : [];
          b = t2(b);
          for (var e = b.next(); !e.done; e = b.next()) {
            e = zw(a, e.value, c);
            if (!e) return;
            d2.push(e);
          }
          c.matchedStreams = d2;
        }
        function zw(a, b, c) {
          var d2 = {
            audio: gw,
            video: hw,
            text: iw,
            image: jw
          }[c.type], e = null, f = d2(c);
          if (b.has(f)) e = b.get(f);
          else {
            f = {
              audio: function(l, m) {
                return vw(a, l, m);
              },
              video: function(l, m) {
                return vw(a, l, m);
              },
              text: Aw,
              image: Bw
            }[c.type];
            for (var g = {
              audio: Cw,
              video: Dw,
              text: Ew,
              image: Fw
            }[c.type], h = t2(b.values()), k2 = h.next(); !k2.done; k2 = h.next()) k2 = k2.value, !f(c, k2) || c.fastSwitching != k2.fastSwitching || e && !g(c, e, k2) || (e = k2);
          }
          a.A && !uw(e) && b.delete(d2(e));
          return e;
        }
        function Gw(a, b) {
          return a.mimeType != b.mimeType ? false : Hw(a.codecs) === Hw(b.codecs);
        }
        p.Ij = function(a) {
          this.u = a;
        };
        p.Oj = function(a) {
          this.A = a;
        };
        function vw(a, b, c) {
          return !Gw(b, c) && !a.u || b.drmInfos && !yg(b.drmInfos, c.drmInfos) ? false : true;
        }
        function Aw(a, b) {
          return b.language ? a.forced !== b.forced || Fc(a.language, b.language) == 0 || b.kind != a.kind ? false : true : true;
        }
        function Bw() {
          return true;
        }
        function Cw(a, b, c) {
          var d2 = Iw(a, b, c);
          if (d2 === Jw) return true;
          if (d2 === Kw) return false;
          d2 = Fc(a.language, b.language);
          var e = Fc(a.language, c.language);
          if (e > d2) return true;
          if (e < d2) return false;
          if (b.label !== c.label) {
            if (a.label === b.label) return false;
            if (a.label === c.label) return true;
          }
          if (a.roles.length) {
            d2 = b.roles.filter(function(f) {
              return a.roles.includes(f);
            });
            e = c.roles.filter(function(f) {
              return a.roles.includes(f);
            });
            if (e.length > d2.length) return true;
            if (e.length < d2.length) return false;
            if (c.roles.length !== b.roles.length) return c.roles.length < b.roles.length;
          } else {
            if (!c.roles.length && b.roles.length) return true;
            if (c.roles.length && !b.roles.length) return false;
          }
          if (!b.primary && c.primary) return true;
          if (b.primary && !c.primary) return false;
          d2 = Lw(a.channelsCount, b.channelsCount, c.channelsCount);
          if (d2 == Jw) return true;
          if (d2 == Kw) return false;
          d2 = Lw(a.audioSamplingRate, b.audioSamplingRate, c.audioSamplingRate);
          return d2 == Jw ? true : d2 == Kw ? false : a.bandwidth && Mw(a.bandwidth, b.bandwidth, c.bandwidth) == Jw ? true : false;
        }
        function Dw(a, b, c) {
          var d2 = Iw(a, b, c);
          if (d2 === Jw) return true;
          if (d2 === Kw) return false;
          d2 = Lw(a.width * a.height, b.width * b.height, c.width * c.height);
          if (d2 == Jw) return true;
          if (d2 == Kw) return false;
          if (a.frameRate) {
            d2 = Lw(a.frameRate, b.frameRate, c.frameRate);
            if (d2 == Jw) return true;
            if (d2 == Kw) return false;
          }
          return a.bandwidth && Mw(a.bandwidth, b.bandwidth, c.bandwidth) == Jw ? true : false;
        }
        function Ew(a, b, c) {
          var d2 = Fc(a.language, b.language), e = Fc(a.language, c.language);
          if (e > d2) return true;
          if (e < d2) return false;
          if (!b.primary && c.primary) return true;
          if (b.primary && !c.primary) return false;
          if (b.label !== c.label) {
            if (a.label === b.label) return false;
            if (a.label === c.label) return true;
          }
          if (a.roles.length) {
            d2 = b.roles.filter(function(f) {
              return a.roles.includes(f);
            });
            e = c.roles.filter(function(f) {
              return a.roles.includes(f);
            });
            if (e.length > d2.length) return true;
            if (e.length < d2.length) return false;
          } else {
            if (!c.roles.length && b.roles.length) return true;
            if (c.roles.length && !b.roles.length) return false;
          }
          return c.mimeType != a.mimeType || c.codecs != a.codecs || b.mimeType == a.mimeType && b.codecs == a.codecs ? false : true;
        }
        function Fw(a, b, c) {
          return Lw(a.width * a.height, b.width * b.height, c.width * c.height) == Jw ? true : false;
        }
        function pw(a) {
          return {
            id: 0,
            originalId: "",
            groupId: null,
            primary: false,
            type: a,
            mimeType: "",
            codecs: "",
            language: "",
            originalLanguage: null,
            label: null,
            width: null,
            height: null,
            encrypted: false,
            keyIds: /* @__PURE__ */ new Set(),
            segments: [],
            variantIds: [],
            roles: [],
            forced: false,
            channelsCount: null,
            audioSamplingRate: null,
            spatialAudio: false,
            closedCaptions: null,
            external: false,
            fastSwitching: false,
            isAudioMuxedInVideo: false,
            baseOriginalId: null
          };
        }
        function kw(a) {
          return {
            id: 0,
            originalId: "",
            groupId: null,
            createSegmentIndex: function() {
              return Promise.resolve();
            },
            segmentIndex: new Zl([]),
            mimeType: "",
            codecs: "",
            encrypted: false,
            drmInfos: [],
            keyIds: /* @__PURE__ */ new Set(),
            language: "",
            originalLanguage: null,
            label: null,
            type: a,
            primary: false,
            trickModeVideo: null,
            dependencyStream: null,
            emsgSchemeIdUris: null,
            roles: [],
            forced: false,
            channelsCount: null,
            audioSamplingRate: null,
            spatialAudio: false,
            closedCaptions: null,
            accessibilityPurpose: null,
            external: false,
            fastSwitching: false,
            fullMimeTypes: /* @__PURE__ */ new Set(),
            isAudioMuxedInVideo: false,
            baseOriginalId: null
          };
        }
        function Lw(a, b, c) {
          if (b == a && a != c) return Kw;
          if (c == a && a != b) return Jw;
          if (b > a) {
            if (c <= a || c - a < b - a) return Jw;
            if (c - a > b - a) return Kw;
          } else {
            if (c > a) return Kw;
            if (a - c < a - b) return Jw;
            if (a - c > a - b) return Kw;
          }
          return Nw;
        }
        function Iw(a, b, c) {
          var d2 = a.mimeType === b.mimeType && a.codecs === b.codecs, e = a.mimeType === c.mimeType && a.codecs === c.codecs;
          if (d2 && !e) return Kw;
          if (!d2 && e) return Jw;
          b = Gw(a, b);
          a = Gw(a, c);
          return b && !a ? Kw : !b && a ? Jw : Nw;
        }
        function Mw(a, b, c) {
          b = Math.abs(a - b);
          a = Math.abs(a - c);
          return a < b ? Jw : b < a ? Kw : Nw;
        }
        function uw(a) {
          switch (a.type) {
            case tc:
              return !a.language;
            case "image":
              return !a.tilesLayout;
            default:
              return false;
          }
        }
        function hw(a) {
          return Ow([a.fastSwitching, a.width, a.frameRate, a.codecs, a.mimeType, a.label, a.roles, a.closedCaptions ? Array.from(a.closedCaptions.entries()) : null, a.bandwidth, a.dependencyStream ? a.dependencyStream.baseOriginalId : null, Array.from(a.keyIds)]);
        }
        function gw(a) {
          return Ow([a.fastSwitching, a.channelsCount, a.language, a.bandwidth, a.label, a.codecs, a.mimeType, a.roles, a.audioSamplingRate, a.primary, a.dependencyStream ? a.dependencyStream.baseOriginalId : null, Array.from(a.keyIds)]);
        }
        function iw(a) {
          return Ow([a.language, a.label, a.codecs, a.mimeType, a.bandwidth, a.roles]);
        }
        function jw(a) {
          return Ow([a.width, a.codecs, a.mimeType]);
        }
        function Ow(a) {
          return JSON.stringify(a);
        }
        function Hw(a) {
          if (!Pw.has(a)) {
            var b = kf(a);
            Pw.set(a, b);
          }
          return Pw.get(a);
        }
        S("shaka.util.PeriodCombiner", ew);
        ew.prototype.setUseStreamOnce = ew.prototype.Oj;
        ew.prototype.setAllowMultiTypeVariants = ew.prototype.Ij;
        ew.prototype.combinePeriods = ew.prototype.Og;
        ew.prototype.deleteStream = ew.prototype.Ri;
        ew.prototype.getImageStreams = ew.prototype.Ok;
        ew.prototype.getTextStreams = ew.prototype.wh;
        ew.prototype.getVariants = ew.prototype.vl;
        var Jw = 1, Nw = 0, Kw = -1, Pw = /* @__PURE__ */ new Map();
        function Qw(a, b) {
          var c = new DOMParser(), d2 = Rw.value()(a);
          a = null;
          try {
            a = c.parseFromString(d2, "text/xml");
          } catch (e) {
            return null;
          }
          c = a.documentElement;
          if (!c || c.getElementsByTagName("parsererror").length || c.tagName != b) return null;
          if (!("createNodeIterator" in document)) return c;
          for (b = document.createNodeIterator(a, NodeFilter.SHOW_ALL); a = b.nextNode(); ) if (a instanceof HTMLElement || a instanceof SVGElement) return null;
          return c;
        }
        function Sw(a, b) {
          try {
            var c = $b(a);
            return Qw(c, b);
          } catch (d2) {
            return null;
          }
        }
        var Rw = new Rb(function() {
          if (typeof trustedTypes !== "undefined") {
            var a = trustedTypes.createPolicy("shaka-player#xml", {
              createHTML: function(b) {
                return b;
              }
            });
            return function(b) {
              return a.createHTML(b);
            };
          }
          return function(b) {
            return b;
          };
        });
        function Tw() {
          var a = this;
          this.j = this.g = null;
          this.C = [];
          this.h = null;
          this.va = 1;
          this.H = [];
          this.l = {
            Mf: "",
            type: "",
            profiles: [],
            Ac: null,
            zb: 0,
            kb: null,
            Ae: 0
          };
          this.A = /* @__PURE__ */ new Map();
          this.D = /* @__PURE__ */ new Map();
          this.u = /* @__PURE__ */ new Map();
          this.F = /* @__PURE__ */ new Map();
          this.sa = /* @__PURE__ */ new Map();
          this.m = new ew();
          this.K = 0;
          this.ua = new Nc(5);
          this.L = new Cf(function() {
            if (a.J && !a.g.continueLoadingWhenPaused && (a.I.Ea(a.J, "timeupdate"), a.J.paused)) {
              a.I.qa(a.J, "timeupdate", function() {
                return Uw(a);
              });
              return;
            }
            Uw(a);
          });
          this.P = new Ug();
          this.O = null;
          this.G = [];
          this.$ = Infinity;
          this.oa = false;
          this.i = null;
          this.M = 0;
          this.R = false;
          this.I = new Qc();
          this.J = null;
          this.S = false;
          this.Z = "";
          this.ea = function() {
            return false;
          };
          this.V = [];
          this.aa = /* @__PURE__ */ new Set();
        }
        p = Tw.prototype;
        p.configure = function(a, b) {
          var c = this.j && a.updatePeriod != this.g.updatePeriod && a.updatePeriod >= 0;
          this.g = a;
          b && (this.ea = b);
          c && this.h && this.h.presentationTimeline.U() && this.L.La();
          this.i && this.i.configure(this.g);
          this.m && (this.m.Ij(this.g.dash.multiTypeVariantsAllowed && fd()), this.m.Oj(this.g.dash.useStreamOnceInPeriodFlattening));
        };
        p.start = function(a, b) {
          var c = this, d2;
          return P(function(e) {
            if (e.g == 1) return c.oa = b.isLowLatencyMode(), c.C = [a], c.j = b, G(e, Vw(c), 2);
            d2 = e.h;
            c.j && Ww(c, d2);
            if (!c.j) throw new U(2, 7, 7001);
            return e.return(c.h);
          });
        };
        p.stop = function() {
          for (var a = t2(this.u.values()), b = a.next(); !b.done; b = a.next()) b = b.value, b.segmentIndex && b.segmentIndex.release();
          this.m && this.m.release();
          this.g = this.j = null;
          this.C = [];
          this.h = null;
          this.u.clear();
          this.F.clear();
          this.A.clear();
          this.D.clear();
          this.l = {
            Mf: "",
            type: "",
            profiles: [],
            Ac: null,
            zb: 0,
            kb: null,
            Ae: 0
          };
          this.m = null;
          this.L != null && (this.L.stop(), this.L = null);
          this.i && this.i.destroy();
          this.I && (this.I.release(), this.I = null);
          this.aa.clear();
          return this.P.destroy();
        };
        p.update = function() {
          var a = this, b;
          return P(function(c) {
            if (c.g == 1) return sa(c, 2), G(c, Vw(a), 4);
            if (c.g != 2) return ua(c, 0);
            b = va(c);
            if (!a.j || !b) return c.return();
            a.j.onError(b);
            H(c);
          });
        };
        p.onExpirationUpdated = function() {
        };
        p.onInitialVariantChosen = function(a) {
          if (this.h && this.h.presentationTimeline.U()) {
            var b = a.video || a.audio;
            if (b && b.segmentIndex) {
              a = this.h.presentationTimeline.Mc();
              var c = b.segmentIndex.find(a);
              c != null && (b = b.segmentIndex.get(c)) && (this.K = b.endTime - a, Ww(this, 0));
            }
          }
        };
        p.banLocation = function(a) {
          this.i && this.i.banLocation(a);
        };
        p.setMediaElement = function(a) {
          this.J = a;
        };
        function Vw(a) {
          var b, c, d2, e, f, g, h, k2, l, m, n;
          return P(function(q) {
            if (q.g == 1) return b = 4, c = "MPD", d2 = Xw(a), e = a.C, d2.length ? (e = d2, c = "Patch", b = 6) : a.C.length > 1 && a.i && (f = dw(a.i, "Location", true), f.length && (e = f)), g = ah(e, a.g.retryParameters), h = Date.now(), G(q, Yw(a, g, 0, {
              type: b
            }), 2);
            if (q.g != 3) {
              k2 = q.h;
              if (!a.j) return q.return(0);
              k2.uri && k2.uri != k2.originalUri && !a.C.includes(k2.uri) && a.C.unshift(k2.uri);
              l = new rb(k2.uri);
              a.Z = l.g.toString();
              return G(q, Zw(a, k2.data, k2.uri, c), 3);
            }
            m = Date.now();
            n = (m - h) / 1e3;
            a.ua.sample(1, n);
            a.aa.clear();
            return q.return(n);
          });
        }
        function Zw(a, b, c, d2) {
          var e, f, g, h, k2, l, m, n, q, r2, u;
          return P(function(w) {
            if (w.g == 1) {
              e = b;
              f = a.g.dash.manifestPreprocessor;
              g = Wn;
              if (f != g) {
                Wc("manifest.dash.manifestPreprocessor configuration", "Please Use manifest.dash.manifestPreprocessorTXml instead.");
                h = Sw(e, d2);
                if (!h) throw new U(2, 4, 4001, c);
                f(h);
                e = ac(h.outerHTML);
              }
              k2 = Kd(e, d2);
              if (!k2) throw new U(2, 4, 4001, c);
              l = a.g.dash.manifestPreprocessorTXml;
              m = Xn;
              l != m && l(k2);
              if (d2 === "Patch") return w.return($w(a, k2));
              if (n = a.g.dash.disableXlinkProcessing) return w.return(ax(a, k2, c));
              q = a.g.dash.xlinkFailGracefully;
              r2 = qv(k2, a.g.retryParameters, q, c, a.j.networkingEngine);
              Vg(a.P, r2);
              return G(w, r2.promise, 2);
            }
            u = w.h;
            return w.return(ax(a, u, c));
          });
        }
        function ax(a, b, c) {
          var d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N, O, Q, R, V, Ba, aa, Oa, La, Ja, Ea, ya, Fa, Da, za, Ca, fb, hb, ib, xb, vb, Va, Wd, Lc, Ee, Ad, xg, Dk, ai;
          return P(function(gd) {
            switch (gd.g) {
              case 1:
                a.i && a.i.l.clear();
                d2 = [c];
                e = [];
                f = /* @__PURE__ */ new Map();
                g = Sd(b, "Location");
                h = t2(g);
                for (k2 = h.next(); !k2.done; k2 = h.next()) if (l = k2.value, m = l.attributes.serviceLocation, n = Ud(l)) q = nc(d2, [n])[0], m && (a.i ? cw(a.i, "Location", m, q) : f.set(m, q)), e.push(q);
                a.i ? (r2 = dw(a.i, "Location", true), r2.length > 0 && (d2 = a.C = r2)) : e.length && (d2 = a.C = e);
                a.l.Mf = b.attributes.id || "";
                a.l.Ae = $d(b, "publishTime", ce) || 0;
                a.H = Sd(b, "PatchLocation");
                u = Promise.resolve();
                if ((w = Xd(b, "ContentSteering")) && a.j) {
                  v = w.attributes.defaultServiceLocation;
                  if (a.i) a.i.i = d2, a.i.h = v;
                  else if (a.i = new Zv(a.j), a.i.configure(a.g), a.i.setManifestType("DASH"), a.i.i = d2, a.i.h = v, y = Ud(w)) (z = $d(w, "queryBeforeStart", ke, false)) ? u = $v(a.i, y) : $v(a.i, y);
                  A = t2(f.keys());
                  for (C = A.next(); !C.done; C = A.next()) D = C.value, F = f.get(D), cw(a.i, "Location", D, F);
                }
                B = Sd(b, "BaseURL");
                E = false;
                if (a.i) for (I = t2(B), J = I.next(); !J.done; J = I.next()) K = J.value, L = K.attributes.serviceLocation, M = Ud(K), L && M && (cw(a.i, "BaseURL", L, M), E = true);
                a.V.splice(0);
                E && a.i || (N = B.map(Ud), a.V.push.apply(a.V, x(nc(d2, N))));
                O = a.i;
                Q = a.V;
                R = function() {
                  return O && E ? dw(O, "BaseURL") : Q.slice();
                };
                a.l.kb = R;
                V = 0;
                B && B.length && (V = $d(B[0], "availabilityTimeOffset", je) || 0);
                a.l.zb = V;
                a.K = $d(b, "minimumUpdatePeriod", de, -1);
                Ba = $d(b, "availabilityStartTime", ce);
                aa = $d(b, "timeShiftBufferDepth", de);
                Oa = a.g.dash.ignoreSuggestedPresentationDelay;
                La = null;
                Oa || (La = $d(b, "suggestedPresentationDelay", de));
                Ja = a.g.dash.ignoreMaxSegmentDuration;
                Ea = null;
                Ja || (Ea = $d(b, "maxSegmentDuration", de));
                ya = b.attributes.type || "static";
                a.h && a.h.presentationTimeline && (a.S = a.h.presentationTimeline.U() && ya == "static");
                a.l.type = ya;
                if (a.h) for (Fa = a.h.presentationTimeline, Da = Fa.Nb(), za = t2(a.u.values()), Ca = za.next(); !Ca.done; Ca = za.next()) fb = Ca.value, fb.segmentIndex && fb.segmentIndex.ib(Da);
                else hb = a.g.dash.ignoreMinBufferTime, ib = 0, hb || (ib = $d(b, "minBufferTime", de) || 0), xb = 0, xb = La != null ? Math.min(La, aa || Infinity) : a.g.defaultPresentationDelay > 0 ? a.g.defaultPresentationDelay : Math.min(ib * 1.5, aa || Infinity), Fa = new Al(Ba, xb, a.g.dash.autoCorrectDrift);
                Fa.rd(ya == "static");
                (vb = Fa.U()) && !isNaN(a.g.availabilityWindowOverride) && (aa = a.g.availabilityWindowOverride);
                aa == null && (aa = Infinity);
                Fa.hg(aa);
                Va = b.attributes.profiles || "";
                a.l.profiles = Va.split(",");
                Wd = {
                  Jb: ya != "static",
                  presentationTimeline: Fa,
                  Aa: null,
                  ra: null,
                  wa: null,
                  N: null,
                  bandwidth: 0,
                  Ch: false,
                  zb: V,
                  Ac: null,
                  profiles: Va.split(","),
                  roles: null,
                  Sb: function() {
                    return "";
                  }
                };
                return G(gd, u, 2);
              case 2:
                a.M = 0;
                Lc = bx(a, Wd, R, b, false);
                Ee = Lc.duration;
                Ad = Lc.periods;
                (ya != "static" || a.S) && Lc.Ti || Fa.yb(Ee || Infinity);
                a.R && a.oa && Fa.Jj(a.$);
                Fa.Lh(Ea || 1);
                a.R && a.oa && (xg = La != null ? La : a.g.defaultPresentationDelay, Fa.ci(xg));
                if (!a.h) return G(gd, a.m.Og(Ad, Wd.Jb), 6);
                a.h.periodCount = Ad.length;
                a.h.gapCount = a.M;
                return G(gd, cx(a, Ad, false), 4);
              case 6:
                a.h = {
                  presentationTimeline: Fa,
                  variants: a.m.l,
                  textStreams: a.m.wh(),
                  imageStreams: a.m.i,
                  offlineSessionIds: [],
                  sequenceMode: a.g.dash.sequenceMode,
                  ignoreManifestTimestampsInSegmentsMode: false,
                  type: "DASH",
                  serviceDescription: dx(b),
                  nextUrl: ex(b),
                  periodCount: Ad.length,
                  gapCount: a.M,
                  isLowLatency: a.R,
                  startTime: null
                };
                if (!Fa.ck()) {
                  gd.B(7);
                  break;
                }
                Dk = Sd(b, "UTCTiming");
                return G(gd, fx(a, R, Dk), 8);
              case 8:
                ai = gd.h;
                if (!a.j) return gd.return();
                Fa.Kj(ai);
              case 7:
                Fa.If(), a.m && !a.h.presentationTimeline.U() && a.m.release();
              case 4:
                a.j.makeTextStreamsForClosedCaptions(a.h), gx(a), hx(a, Ad), H(gd);
            }
          });
        }
        function cx(a, b, c) {
          var d2;
          return P(function(e) {
            if (e.g == 1) return G(e, a.m.Og(b, true, c), 2);
            a.h.variants = a.m.l;
            d2 = a.m.wh();
            d2.length > 0 && (a.h.textStreams = d2);
            a.h.imageStreams = a.m.i;
            a.j.filter(a.h);
            H(e);
          });
        }
        function $w(a, b) {
          var c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L;
          return P(function(M) {
            if (M.g == 1) {
              c = b.attributes.mpdId;
              d2 = $d(b, "originalPublishTime", ce);
              if (!c || c !== a.l.Mf || d2 !== a.l.Ae) throw a.H = [], new U(1, 4, 4052);
              e = [];
              f = [];
              g = /* @__PURE__ */ new Set();
              h = t2(Rd(b));
              for (k2 = h.next(); !k2.done; k2 = h.next()) if (l = k2.value, m = me(l.attributes.sel || ""), n = m[m.length - 1], q = Ud(l) || "", n.name === "MPD") {
                if (n.Ic === "mediaPresentationDuration") {
                  r2 = Ud(l) || "";
                  var N = de(r2);
                  if (N != null) {
                    a.l.Ac = N;
                    for (var O = t2(a.A.values()), Q = O.next(); !Q.done; Q = O.next()) Q.value.Ac = N;
                  }
                } else if (n.Ic === "type") {
                  a.h.presentationTimeline.rd(q == "static");
                  a.l.type = q;
                  N = t2(a.A.values());
                  for (O = N.next(); !O.done; O = N.next()) O.value.Jb = q == "dynamic";
                  q == "static" && (a.K = -1);
                } else n.Ic === "publishTime" ? a.l.Ae = ce(q) || 0 : n.Ic === null && l.tagName === "add" && f.push(l);
              } else if (n.name === "PatchLocation") ne(a.H, l);
              else if (n.name === "Period") l.tagName === "add" ? f.push(l) : l.tagName === "remove" && n.id && ix(a, n.id);
              else if (n.name === "SegmentTemplate") {
                O = me(l.attributes.sel || "");
                N = O[O.length - 1];
                if (N.Ic) {
                  O = jx(a, O);
                  Q = Ud(l) || "";
                  for (var R = t2(O), V = R.next(); !V.done; V = R.next()) V = a.A.get(V.value), pe(V.N.Tc, l.tagName, N.Ic, Q);
                  N = O;
                } else N = [];
                u = N;
                w = t2(u);
                for (v = w.next(); !v.done; v = w.next()) y = v.value, g.add(y);
              } else if (n.name === "SegmentTimeline" || n.name === "S") {
                N = me(l.attributes.sel || "");
                N = jx(a, N);
                O = t2(N);
                for (Q = O.next(); !Q.done; Q = O.next()) Q = a.A.get(Q.value), Q = nv(Q, Pv, "SegmentTimeline"), R = Sd(Q, "S"), ne(R, l), Q.children = R;
                z = N;
                A = t2(z);
                for (C = A.next(); !C.done; C = A.next()) D = C.value, g.add(D);
              }
              F = t2(g);
              for (B = F.next(); !B.done; B = F.next()) E = B.value, kx(a, E);
              I = t2(f);
              for (J = I.next(); !J.done; J = I.next()) K = J.value, e.push.apply(e, x(lx(a, K)));
              if (!e.length) return M.B(2);
              a.h.periodCount += e.length;
              a.h.gapCount = a.M;
              return G(M, cx(a, e, true), 2);
            }
            a.l.type == "static" && (L = a.l.Ac, a.h.presentationTimeline.yb(L || Infinity));
            H(M);
          });
        }
        function lx(a, b) {
          return bx(a, {
            Jb: a.l.type == "dynamic",
            presentationTimeline: a.h.presentationTimeline,
            Aa: null,
            ra: null,
            wa: null,
            N: null,
            bandwidth: 0,
            Ch: false,
            zb: a.l.zb,
            profiles: a.l.profiles,
            Ac: a.l.Ac,
            roles: null,
            Sb: function() {
              return "";
            }
          }, a.l.kb, b, true).periods;
        }
        function ix(a, b) {
          a.h.periodCount--;
          for (var c = t2(a.A.keys()), d2 = c.next(); !d2.done; d2 = c.next()) if (d2 = d2.value, d2.startsWith(b)) {
            var e = a.A.get(d2);
            nv(e, Pv, "SegmentTimeline").children = [];
            kx(a, d2);
            a.A.delete(d2);
          }
          a.G = a.G.filter(function(f) {
            return f !== b;
          });
        }
        function jx(a, b) {
          var c = "", d2 = "", e = -1, f = "";
          b = t2(b);
          for (var g = b.next(); !g.done; g = b.next()) g = g.value, g.name === "Period" ? c = g.id : g.name === "AdaptationSet" ? (d2 = g.id, g.position !== null && (e = g.position)) : g.name === "Representation" && (f = g.id);
          b = [];
          if (f) b.push(c + "," + f);
          else if (d2) for (e = t2(a.A.values()), a = e.next(); !a.done; a = e.next()) a = a.value, a.Aa.id === c && a.wa.id === d2 && a.N.id && b.push(c + "," + a.N.id);
          else if (e > -1) for (d2 = t2(a.A.values()), a = d2.next(); !a.done; a = d2.next()) a = a.value, a.Aa.id === c && a.wa.position === e && a.N.id && b.push(c + "," + a.N.id);
          return b;
        }
        function kx(a, b) {
          var c = a.A.get(b), d2 = a.u.get(b);
          d2.segmentIndex && d2.segmentIndex.ib(a.h.presentationTimeline.Nb());
          try {
            var e = Ov(c, function(f, g, h, k2) {
              return mx(a, f, g, h, k2);
            }, a.u, true, a.g.dash.initialSegmentLimit, a.sa, c.N.aesKey, null, true, a.D);
            d2.createSegmentIndex = function() {
              return P(function(f) {
                if (f.g == 1) return d2.segmentIndex ? f.B(0) : G(f, e.dd(), 3);
                d2.segmentIndex = f.h;
                H(f);
              });
            };
          } catch (f) {
            if (b = c.N.contentType, b != tc && b != "application" && b != "image" || f.code != 4002) throw f;
          }
        }
        function dx(a) {
          var b = Xd(a, "ServiceDescription");
          if (!b) return null;
          a = Xd(b, "Latency");
          b = Xd(b, "PlaybackRate");
          if (!a && !b) return null;
          var c = {};
          a && ("target" in a.attributes && (c.targetLatency = parseInt(a.attributes.target, 10) / 1e3), "max" in a.attributes && (c.maxLatency = parseInt(a.attributes.max, 10) / 1e3), "min" in a.attributes && (c.minLatency = parseInt(a.attributes.min, 10) / 1e3));
          b && ("max" in b.attributes && (c.maxPlaybackRate = parseFloat(b.attributes.max)), "min" in b.attributes && (c.minPlaybackRate = parseFloat(b.attributes.min)));
          return c;
        }
        function ex(a) {
          a = Sd(a, "SupplementalProperty");
          if (!a.length) return null;
          a = t2(a);
          for (var b = a.next(); !b.done; b = a.next()) if (b = b.value, b.attributes.schemeIdUri == "urn:mpeg:dash:chaining:2016") return b.attributes.value;
          return null;
        }
        function bx(a, b, c, d2, e) {
          var f = b.Ac;
          f || (f = $d(d2, "mediaPresentationDuration", de), a.l.Ac = f);
          var g = 0;
          a.h && a.h.presentationTimeline && a.S && (g = a.h.presentationTimeline.ec());
          var h = [], k2 = g;
          d2 = Sd(d2, "Period");
          for (var l = 0; l < d2.length; l++) {
            var m = d2[l], n = d2[l + 1], q = $d(m, "start", de, k2), r2 = m.attributes.id, u = $d(m, "duration", de);
            q = l == 0 && q == 0 && a.S ? g : q;
            var w = null;
            if (n) {
              var v = $d(n, "start", de);
              v != null && (w = v - q + g);
            } else f != null && (w = f - q + g);
            v = wc;
            w && u && Math.abs(w - u) > v && w > u && a.M++;
            w == null && (w = u);
            if (!(a.O !== null && r2 !== null && q !== null && q < a.O) || a.G.includes(r2) || l + 1 == d2.length) {
              q !== null && (a.O === null || q > a.O) && (a.O = q);
              k2 = nx(a, b, c, {
                start: q,
                duration: w,
                node: m,
                Cf: w == null || !n
              });
              h.push(k2);
              b.Aa.id && w && a.sa.set(b.Aa.id, w);
              if (w == null) {
                k2 = null;
                break;
              }
              k2 = q + w;
            }
          }
          if (e) for (b = t2(h), c = b.next(); !c.done; c = b.next()) c = c.value.id, a.G.includes(c) || a.G.push(c);
          else a.G = h.map(function(y) {
            return y.id;
          });
          return f != null ? {
            periods: h,
            duration: f + g,
            Ti: false
          } : {
            periods: h,
            duration: k2,
            Ti: true
          };
        }
        function gx(a) {
          var b = Array.from(a.F.keys()).filter(function(h) {
            return !a.G.includes(h);
          });
          b = t2(b);
          for (var c = b.next(); !c.done; c = b.next()) {
            c = c.value;
            for (var d2 = true, e = t2(a.F.get(c)), f = e.next(); !f.done; f = e.next()) {
              f = f.value;
              var g = a.u.get(f);
              g && (g.segmentIndex && g.segmentIndex.getNumReferences() != 0 ? d2 = false : (a.m && a.m.Ri(g, c), a.u.delete(f)));
            }
            d2 && a.F.delete(c);
          }
        }
        function hx(a, b) {
          b = new Set(b.map(function(e) {
            return e.id;
          }));
          for (var c = t2(a.D.keys()), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, b.has(d2) || a.D.delete(d2);
        }
        function nx(a, b, c, d2) {
          b.Aa = ox(a, d2.node, null, c);
          b.ra = d2;
          b.Aa.zb = b.zb;
          b.Aa.id || (b.Aa.id = "__shaka_period_" + d2.start);
          var e = Sd(d2.node, "EventStream");
          c = b.presentationTimeline.Nb();
          e = t2(e);
          for (var f = e.next(); !f.done; f = e.next()) px(a, d2.start, d2.duration, f.value, c);
          c = Sd(d2.node, "SupplementalProperty");
          c = t2(c);
          for (e = c.next(); !e.done; e = c.next()) if (e = e.value, e.attributes.schemeIdUri == "urn:mpeg:dash:urlparam:2014" && (e = qx(a, e))) b.Sb = e;
          c = Sd(d2.node, "AdaptationSet").map(function(r2, u) {
            return rx(a, b, u, r2);
          }).filter(Ff);
          if (b.Jb) {
            e = [];
            f = t2(c);
            for (var g = f.next(); !g.done; g = f.next()) {
              g = t2(g.value.gm);
              for (var h = g.next(); !h.done; h = g.next()) e.push(h.value);
            }
            if (e.length != new Set(e).size) throw new U(2, 4, 4018);
          }
          e = /* @__PURE__ */ new Map();
          f = t2(c);
          for (g = f.next(); !g.done; g = f.next()) for (g = t2(g.value.xk), h = g.next(); !h.done; h = g.next()) {
            var k2 = t2(h.value);
            h = k2.next().value;
            k2 = k2.next().value;
            e.set(h, k2);
          }
          if (e.size) for (f = null, g = t2(c), h = g.next(); !h.done; h = g.next()) {
            h = h.value;
            k2 = [];
            for (var l = t2(h.streams), m = l.next(), n = {}; !m.done; n = {
              mi: void 0
            }, m = l.next()) if (n.mi = m.value, e.has(n.mi.originalId)) {
              f || (f = Sd(d2.node, "AdaptationSet").map(function(r2, u) {
                return rx(a, b, u, r2);
              }).filter(Ff));
              m = t2(f);
              for (var q = m.next(); !q.done; q = m.next()) if (q = q.value.streams.find(/* @__PURE__ */ function(r2) {
                return function(u) {
                  return u.originalId == r2.mi.originalId;
                };
              }(n))) q.dependencyStream = e.get(q.originalId), q.originalId += q.dependencyStream.originalId, k2.push(q);
            }
            k2.length && h.streams.push.apply(h.streams, x(k2));
          }
          d2 = c.filter(function(r2) {
            return !r2.wi;
          });
          c = c.filter(function(r2) {
            return r2.wi;
          });
          if (!a.g.disableIFrames) {
            for (c = t2(c), e = c.next(); !e.done; e = c.next()) for (e = e.value, f = e.wi.split(" "), g = t2(d2), h = g.next(); !h.done; h = g.next()) if (h = h.value, f.includes(h.id)) for (h = t2(h.streams), k2 = h.next(); !k2.done; k2 = h.next()) pg(k2.value, e.streams);
          }
          c = sx(a.g.disableAudio, d2, "audio");
          e = sx(a.g.disableVideo, d2, "video");
          f = sx(a.g.disableText, d2, tc);
          d2 = sx(a.g.disableThumbnails, d2, "image");
          if (e.length === 0 && c.length === 0) throw new U(2, 4, 4004);
          return {
            id: b.Aa.id,
            audioStreams: c,
            videoStreams: e,
            textStreams: f,
            imageStreams: d2
          };
        }
        function sx(a, b, c) {
          return a || !b.length ? [] : b.reduce(function(d2, e) {
            if (e.contentType != c) return d2;
            d2.push.apply(d2, x(e.streams));
            return d2;
          }, []);
        }
        function rx(a, b, c, d2) {
          function e(L) {
            var M = L.attributes["dvb:fontFamily"];
            L = L.attributes["dvb:url"];
            M && L && (L = nc(b.wa.kb(), [L], b.Sb()), a.j.addFont(M, L[0]));
          }
          function f(L) {
            switch (L) {
              case 1:
              case 5:
              case 6:
              case 7:
                return "srgb";
              case 9:
                return "rec2020";
              case 11:
              case 12:
                return "p3";
            }
          }
          function g(L) {
            switch (L) {
              case 1:
              case 6:
              case 13:
              case 14:
              case 15:
                return "SDR";
              case 16:
                return "PQ";
              case 18:
                return "HLG";
            }
          }
          b.wa = ox(a, d2, b.Aa, null);
          b.wa.position = c;
          var h = false;
          c = Sd(d2, "Role");
          var k2 = c.map(function(L) {
            return L.attributes.value;
          }).filter(Ff), l = void 0, m = b.wa.contentType == tc;
          m && (l = "subtitle");
          c = t2(c);
          for (var n = c.next(); !n.done; n = c.next()) {
            n = n.value;
            var q = n.attributes.schemeIdUri;
            if (q == null || q == "urn:mpeg:dash:role:2011") switch (n = n.attributes.value, n) {
              case "main":
                h = true;
                break;
              case "caption":
              case "subtitle":
                l = n;
            }
          }
          var r2 = Sd(d2, "EssentialProperty");
          c = null;
          var u = false;
          n = null;
          q = false;
          r2 = t2(r2);
          for (var w = r2.next(); !w.done; w = r2.next()) {
            w = w.value;
            var v = w.attributes.schemeIdUri;
            if (v == "http://dashif.org/guidelines/trickmode") c = w.attributes.value;
            else if (v == "urn:mpeg:mpegB:cicp:TransferCharacteristics") var y = g(parseInt(w.attributes.value, 10));
            else if (v == "urn:mpeg:mpegB:cicp:ColourPrimaries") var z = f(parseInt(w.attributes.value, 10));
            else v != "urn:mpeg:mpegB:cicp:MatrixCoefficients" && (v == "urn:mpeg:dash:ssr:2023" && a.g.dash.enableFastSwitching ? u = true : v == "urn:dvb:dash:fontdownload:2014" ? e(w) : v == "urn:mpeg:dash:urlparam:2014" ? (n = qx(a, w)) || (q = true) : q = true);
          }
          if (q) return null;
          var A = null;
          q = Sd(d2, "SupplementalProperty");
          q = t2(q);
          for (r2 = q.next(); !r2.done; r2 = q.next()) r2 = r2.value, w = r2.attributes.schemeIdUri, w == "http://dashif.org/guidelines/last-segment-number" ? A = parseInt(r2.attributes.value, 10) - 1 : w == "urn:mpeg:mpegB:cicp:TransferCharacteristics" ? y = g(parseInt(r2.attributes.value, 10)) : w == "urn:mpeg:mpegB:cicp:ColourPrimaries" ? z = f(parseInt(r2.attributes.value, 10)) : w == "urn:dvb:dash:fontdownload:2014" ? e(r2) : w == "urn:mpeg:dash:urlparam:2014" && (n = qx(a, r2));
          n && (b.Sb = n);
          n = Sd(d2, "Accessibility");
          var C = /* @__PURE__ */ new Map(), D;
          n = t2(n);
          for (q = n.next(); !q.done; q = n.next()) if (r2 = q.value, q = r2.attributes.schemeIdUri, r2 = r2.attributes.value, q != "urn:scte:dash:cc:cea-608:2015" || a.g.disableText) {
            if (q != "urn:scte:dash:cc:cea-708:2015" || a.g.disableText) q == "urn:mpeg:dash:role:2011" ? r2 != null && (k2.push(r2), r2 == "captions" && (l = "caption")) : q == "urn:tva:metadata:cs:AudioPurposeCS:2007" && (r2 == "1" ? D = "visually impaired" : r2 == "2" ? D = "hard of hearing" : r2 == "9" && (D = "spoken subtitles"));
            else if (q = 1, r2 != null) for (r2 = t2(r2.split(";")), w = r2.next(); !w.done; w = r2.next()) {
              v = w.value;
              var F = w = void 0;
              v.includes("=") ? (v = v.split("="), w = "svc" + v[0], F = v[1].split(",")[0].split(":").pop()) : (w = "svc" + q, q++, F = v);
              C.set(w, zc(F));
            }
            else C.set("svc1", "und");
          } else if (q = 1, r2 != null) for (r2 = r2.split(";"), w = t2(r2), v = w.next(); !v.done; v = w.next()) {
            F = v.value;
            var B = v = void 0;
            F.includes("=") ? (F = F.split("="), v = F[0].startsWith("CC") ? F[0] : "CC" + F[0], B = F[1] || "und") : (v = "CC" + q, r2.length == 2 ? q += 2 : q++, B = F);
            C.set(v, zc(B));
          }
          else C.set("CC1", "und");
          n = Sd(d2, "ContentProtection");
          var E = cv(n, a.g.ignoreDrmInfo, a.g.dash.keySystemsByURI);
          b.wa.encrypted = n.length > 0;
          var I = zc(b.wa.language || "und"), J = b.wa.label, K = /* @__PURE__ */ new Map();
          d2 = Sd(d2, "Representation");
          if (!a.g.ignoreSupplementalCodecs) {
            n = [];
            q = t2(d2);
            for (r2 = q.next(); !r2.done; r2 = q.next()) if (w = r2.value, r2 = ae(w, "urn:scte:dash:scte214-extensions", "supplementalCodecs")) w = Hd(w), w.attributes.codecs = r2.split(" ").join(","), w.attributes.id && (w.attributes.supplementalId = w.attributes.id + "_supplementalCodecs"), n.push(w);
            d2.push.apply(d2, x(n));
          }
          n = d2.map(function(L) {
            var M = tx(a, b, E, l, I, J, h, k2, C, L, D, A);
            return M && (M.hdr = M.hdr || y, M.colorGamut = M.colorGamut || z, M.fastSwitching = u, L = L.attributes.dependencyId) ? (M.baseOriginalId = L, K.set(L, M), null) : M;
          }).filter(function(L) {
            return !!L;
          });
          if (n.length == 0 && K.size == 0) {
            c = b.wa.contentType == "image";
            if (a.g.dash.ignoreEmptyAdaptationSet || m || c) return null;
            throw new U(2, 4, 4003);
          }
          if (!b.wa.contentType || b.wa.contentType == "application") for (b.wa.contentType = ux(n[0].mimeType, n[0].codecs), m = t2(n), q = m.next(); !q.done; q = m.next()) q.value.type = b.wa.contentType;
          m = b.wa.id || "__fake__" + a.va++;
          q = t2(n);
          for (r2 = q.next(); !r2.done; r2 = q.next()) {
            r2 = r2.value;
            w = t2(E.drmInfos);
            for (v = w.next(); !v.done; v = w.next()) v = v.value, v.keyIds = v.keyIds && r2.keyIds ? new Set([].concat(x(v.keyIds), x(r2.keyIds))) : v.keyIds || r2.keyIds;
            r2.groupId = m;
          }
          d2 = d2.map(function(L) {
            return L.attributes.supplementalId || L.attributes.id;
          }).filter(Ff);
          return {
            id: m,
            contentType: b.wa.contentType,
            language: I,
            Rn: h,
            streams: n,
            drmInfos: E.drmInfos,
            wi: c,
            gm: d2,
            xk: K
          };
        }
        function qx(a, b) {
          if ((b = Yd(b, "urn:mpeg:dash:schema:urlparam:2014", "UrlQueryInfo")) && $d(b, "useMPDUrlQuery", ke, false)) {
            var c = b.attributes.queryTemplate;
            if (c) return function() {
              return c == "$querypart$" ? a.Z : c.split("&").map(function(d2) {
                if (d2 == "$querypart$") return a.Z;
                var e = /\$query:(.*?)\$/g.exec(d2);
                if (e && e.length == 2) {
                  e = e[1];
                  var f = new zb(a.Z).get(e);
                  if (f.length) return e + "=" + f[0];
                }
                return d2;
              }).join("&");
            };
          }
          return null;
        }
        function tx(a, b, c, d2, e, f, g, h, k2, l, m, n) {
          b.N = ox(a, l, b.wa, null);
          var q = b.N.id;
          a.$ = Math.min(a.$, b.N.zb);
          a.R = a.$ > 0;
          if (!vx(b.N)) return null;
          var r2 = b.ra.start;
          b.bandwidth = $d(l, "bandwidth", ge) || 0;
          b.roles = h;
          var u = Sd(l, "SupplementalProperty"), w = Sd(l, "EssentialProperty"), v = Sd(l, "ContentProtection");
          l = null;
          var y = w.find(function(O) {
            return O.attributes.schemeIdUri == "urn:mpeg:dash:urlparam:2014";
          });
          y ? l = qx(a, y) : (y = u.find(function(O) {
            return O.attributes.schemeIdUri == "urn:mpeg:dash:urlparam:2014";
          })) && (l = qx(a, y));
          l && (b.Sb = l);
          y = b.N.contentType;
          l = y == tc || y == "application";
          y = y == "image";
          v.length && (b.wa.encrypted = true);
          try {
            var z = void 0;
            if (c.Hg) {
              var A = b.N.kb, C = b.Sb, D = nc(A(), [c.Hg.Jl], C()), F = ah(D, a.g.retryParameters);
              z = {
                bitsKey: 128,
                blockCipherMode: "CBC",
                iv: c.Hg.iv,
                firstMediaSequenceNumber: 0,
                fetchKey: function() {
                  var O, Q, R;
                  return P(function(V) {
                    if (V.g == 1) return G(V, Yw(a, F, 6), 2);
                    if (V.g != 3) {
                      O = V.h;
                      if (!O.data || O.data.byteLength != 16) throw new U(2, 4, 4049);
                      Q = {
                        name: "AES-CBC"
                      };
                      R = z;
                      return G(V, window7.crypto.subtle.importKey("raw", O.data, Q, true, ["decrypt"]), 3);
                    }
                    R.cryptoKey = V.h;
                    z.fetchKey = void 0;
                    H(V);
                  });
                }
              };
            }
            b.N.aesKey = z;
            A = function(O, Q, R, V) {
              return mx(a, O, Q, R, V);
            };
            if (b.N.Ud) var B = Dv(b, A, z);
            else if (b.N.Fc) B = Jv(b, a.u, z);
            else if (b.N.Tc) B = Ov(b, A, a.u, !!a.h, a.g.dash.initialSegmentLimit, a.sa, z, n, false, a.D);
            else {
              var E = b.ra.duration || 0, I = b.N.kb, J = b.N.mimeType, K = b.N.codecs;
              B = {
                endTime: -1,
                timeline: -1,
                dd: function() {
                  var O = am(r2, E, I());
                  O.Kb(function(Q) {
                    Q.mimeType = J;
                    Q.codecs = K;
                  });
                  return Promise.resolve(O);
                },
                timescale: 1
              };
            }
          } catch (O) {
            if ((l || y) && O.code == 4002) return null;
            throw O;
          }
          n = gv(v, c, a.g.ignoreDrmInfo, a.g.dash.keySystemsByURI);
          n = new Set(n ? [n] : []);
          v = false;
          u.some(function(O) {
            return O.attributes.schemeIdUri == "tag:dolby.com,2018:dash:EC3_ExtensionType:2018" && O.attributes.value == "JOC";
          }) && (v = true);
          u = false;
          l && (u = h.includes("forced_subtitle") || h.includes("forced-subtitle"));
          var L;
          if (y && ((w = w.find(function(O) {
            return ["http://dashif.org/thumbnail_tile", "http://dashif.org/guidelines/thumbnail_tile"].includes(O.attributes.schemeIdUri);
          })) && (L = w.attributes.value), !L)) return null;
          var M;
          l = b.N.codecs;
          b.profiles.includes("http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10") && (l.includes("hvc1.2.4.L153.B0") || l.includes("hev1.2.4.L153.B0")) && (M = "PQ");
          w = b.N.id ? b.Aa.id + "," + b.N.id : "";
          a.H.length && q && a.A.set(b.Aa.id + "," + q, wx(b));
          b.N.Wf && xx(a, b.N.Wf, B, b.presentationTimeline);
          B.endTime != -1 && b.Aa.id != null && b.N.id != null && ((q = a.D.get(b.Aa.id)) ? (q.endTime = B.endTime, q.Uh.includes(b.N.id) || q.Uh.push(b.N.id), a.D.set(b.Aa.id, q)) : a.D.set(b.Aa.id, {
            endTime: B.endTime,
            timeline: B.timeline,
            Uh: [b.N.id]
          }));
          var N = w && a.u.has(w) ? a.u.get(w) : {
            id: a.va++,
            originalId: b.N.id,
            groupId: null,
            createSegmentIndex: function() {
              return Promise.resolve();
            },
            closeSegmentIndex: function() {
              N.segmentIndex && (N.segmentIndex.release(), N.segmentIndex = null);
            },
            segmentIndex: null,
            mimeType: b.N.mimeType,
            codecs: l,
            frameRate: b.N.frameRate,
            pixelAspectRatio: b.N.pixelAspectRatio,
            bandwidth: b.bandwidth,
            width: b.N.width,
            height: b.N.height,
            kind: d2,
            encrypted: c.drmInfos.length > 0,
            drmInfos: c.drmInfos,
            keyIds: n,
            language: e,
            originalLanguage: b.wa.language,
            label: f,
            type: b.wa.contentType,
            primary: g,
            trickModeVideo: null,
            dependencyStream: null,
            emsgSchemeIdUris: b.N.emsgSchemeIdUris,
            roles: h,
            forced: u,
            channelsCount: b.N.Pf,
            audioSamplingRate: b.N.audioSamplingRate,
            spatialAudio: v,
            closedCaptions: k2,
            hdr: M,
            colorGamut: void 0,
            videoLayout: void 0,
            tilesLayout: L,
            accessibilityPurpose: m,
            external: false,
            fastSwitching: false,
            fullMimeTypes: /* @__PURE__ */ new Set([ef(b.N.mimeType, b.N.codecs)]),
            isAudioMuxedInVideo: false,
            baseOriginalId: null
          };
          N.createSegmentIndex = function() {
            var O;
            return P(function(Q) {
              if (Q.g == 1) {
                if (N.segmentIndex) return Q.B(0);
                O = N;
                return G(Q, B.dd(), 3);
              }
              O.segmentIndex = Q.h;
              H(Q);
            });
          };
          w && b.Jb && !a.u.has(w) && (b = b.Aa.id || "", a.F.has(b) || a.F.set(b, []), a.u.set(w, N), a.F.get(b).push(w));
          return N;
        }
        function xx(a, b, c, d2) {
          if (!a.aa.has(b)) {
            a.aa.add(b);
            var e = $d(b, "presentationTime", he) || 0, f = Xd(b, "UTCTiming"), g;
            if (g = f && f.attributes.schemeIdUri) f = f.attributes.schemeIdUri, g = !(f === "urn:mpeg:dash:utc:http-ntp:2014" || f === "urn:mpeg:dash:utc:ntp:2014" || f === "urn:mpeg:dash:utc:sntp:2014");
            g ? b = ($d(b, "wallClockTime", ce) || 0) * 1e3 : (b = $d(b, "wallClockTime", he) || 0, b = dk(b));
            c = new Date(b - e / c.timescale * 1e3);
            e = c.getTime() / 1e3;
            isNaN(e) || (d2.u || d2.ei(e), d2 = (/* @__PURE__ */ new Map()).set("detail", {
              wallClockTime: b,
              programStartDate: c
            }), d2 = new T("prft", d2), a.j.onEvent(d2));
          }
        }
        function wx(a) {
          function b(c) {
            if (!c) return null;
            c = Id(c);
            c.Ud = null;
            c.Fc = null;
            c.Tc = re(c.Tc);
            c.Wf = null;
            return c;
          }
          a = Id(a);
          a.Aa = b(a.Aa);
          a.wa = b(a.wa);
          a.N = b(a.N);
          a.ra && (a.ra = Id(a.ra), a.ra.node = null);
          return a;
        }
        function Uw(a) {
          var b, c;
          return P(function(d2) {
            switch (d2.g) {
              case 1:
                return b = 0, sa(d2, 2), G(d2, Vw(a), 4);
              case 4:
                b = d2.h;
                ua(d2, 3);
                break;
              case 2:
                if (c = va(d2), a.j) {
                  if (a.g.raiseFatalErrorOnManifestUpdateRequestFailure) return a.j.onError(c), d2.return();
                  c.severity = 1;
                  a.j.onError(c);
                }
              case 3:
                if (!a.j) return d2.return();
                a.j.onManifestUpdated();
                Ww(a, b);
                H(d2);
            }
          });
        }
        function Ww(a, b) {
          if (!(a.K < 0)) {
            var c = a.K;
            a.g.updatePeriod >= 0 && (c = a.g.updatePeriod);
            a.L.Y(Math.max(c - b, Oc(a.ua)));
          }
        }
        function ox(a, b, c, d2) {
          c = c || {
            contentType: "",
            mimeType: "",
            codecs: "",
            emsgSchemeIdUris: [],
            frameRate: void 0,
            pixelAspectRatio: void 0,
            Pf: null,
            audioSamplingRate: null,
            zb: 0,
            eg: 1,
            encrypted: false
          };
          d2 = d2 || c.kb;
          var e = b.attributes.id, f = b.attributes.supplementalId, g = Sd(b, "BaseURL"), h, k2 = false;
          if (a.i) for (var l = t2(g), m = l.next(); !m.done; m = l.next()) {
            var n = m.value;
            m = n.attributes.serviceLocation;
            n = Ud(n);
            m && n && (cw(a.i, e, m, n), k2 = true);
          }
          k2 && a.i || (h = g.map(Ud));
          var q = a.i;
          a = b.attributes.contentType || c.contentType;
          l = b.attributes.mimeType || c.mimeType;
          m = Fm([b.attributes.codecs || c.codecs]).join(",");
          n = $d(b, "frameRate", le) || c.frameRate;
          var r2 = b.attributes.sar || c.pixelAspectRatio, u = yx(Sd(b, "InbandEventStream"), c.emsgSchemeIdUris), w = Sd(b, "AudioChannelConfiguration");
          w = zx(w) || c.Pf;
          var v = $d(b, "audioSamplingRate", he) || c.audioSamplingRate;
          a || (a = ux(l, m));
          var y = Xd(b, "SegmentBase"), z = Xd(b, "SegmentTemplate"), A = y ? $d(y, "availabilityTimeOffset", je) || 0 : 0, C = z ? $d(z, "availabilityTimeOffset", je) || 0 : 0, D = g && g.length ? $d(g[0], "availabilityTimeOffset", je) || 0 : 0;
          A = c.zb + D + A + C;
          C = null;
          (D = Xd(b, "SegmentSequenceProperties")) && (D = $d(D, "cadence", ge)) && (C = D);
          D = b.attributes.label;
          var F = Sd(b, "Label");
          F && F.length && (F = F[0], Td(F) && (D = Td(F)));
          return {
            kb: function() {
              return nc(d2(), g.length ? q && k2 ? dw(q, e) : h ? h : [] : []);
            },
            Ud: y || c.Ud,
            Fc: Xd(b, "SegmentList") || c.Fc,
            Tc: z || c.Tc,
            Wf: Xd(b, "ProducerReferenceTime") || c.Wf,
            width: $d(b, "width", he) || c.width,
            height: $d(b, "height", he) || c.height,
            contentType: a,
            mimeType: l,
            codecs: m,
            frameRate: n,
            pixelAspectRatio: r2,
            emsgSchemeIdUris: u,
            id: f || e,
            originalId: e,
            language: b.attributes.lang,
            Pf: w,
            audioSamplingRate: v,
            zb: A,
            zf: null,
            eg: C || c.eg,
            label: D || null,
            encrypted: false
          };
        }
        function yx(a, b) {
          b = b.slice();
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) c = c.value.attributes.schemeIdUri, b.includes(c) || b.push(c);
          return b;
        }
        function zx(a) {
          a = t2(a);
          for (var b = a.next(); !b.done; b = a.next()) {
            b = b.value;
            var c = b.attributes.schemeIdUri;
            if (c && (b = b.attributes.value)) switch (c) {
              case "urn:mpeg:dash:outputChannelPositionList:2012":
                return b.trim().split(/ +/).length;
              case "urn:mpeg:dash:23003:3:audio_channel_configuration:2011":
              case "urn:dts:dash:audio_channel_configuration:2012":
                b = parseInt(b, 10);
                if (!b) continue;
                return b;
              case "tag:dolby.com,2015:dash:audio_channel_configuration:2015":
                c = [2, 1, 2, 2, 2, 2, 1, 2, 2, 1, 1, 1, 1, 2, 1, 1, 2, 2];
                b = parseInt(b, 16);
                if (!b) continue;
                for (var d2 = 0, e = 0; e < c.length; e++) b & 1 << e && (d2 += c[e]);
                if (d2) return d2;
                continue;
              case "tag:dolby.com,2014:dash:audio_channel_configuration:2011":
              case "urn:dolby:dash:audio_channel_configuration:2011":
                c = [1, 1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2, 1, 2, 1, 1].reverse();
                b = parseInt(b, 16);
                if (!b) continue;
                for (e = d2 = 0; e < c.length; e++) b & 1 << e && (d2 += c[e]);
                if (d2) return d2;
                continue;
              case "urn:mpeg:mpegB:cicp:ChannelConfiguration":
                if (c = [0, 1, 2, 3, 4, 5, 6, 8, 2, 3, 4, 7, 8, 24, 8, 12, 10, 12, 14, 12, 14], (b = parseInt(b, 10)) && b > 0 && b < c.length) return c[b];
            }
          }
          return null;
        }
        function vx(a) {
          var b = a.Ud ? 1 : 0;
          b += a.Fc ? 1 : 0;
          b += a.Tc ? 1 : 0;
          if (b == 0) return a.contentType == tc || a.contentType == "application" ? true : false;
          b != 1 && (a.Ud && (a.Fc = null), a.Tc = null);
          return true;
        }
        function Ax(a, b, c, d2) {
          var e, f, g, h, k2, l, m;
          return P(function(n) {
            if (n.g == 1) return e = [dc(c)], f = nc(b(), e), g = ah(f, a.g.retryParameters), g.method = d2, h = a.j.networkingEngine.request(4, g, {
              isPreload: a.ea()
            }), Vg(a.P, h), G(n, h.promise, 2);
            k2 = n.h;
            if (d2 == "HEAD") {
              if (!k2.headers || !k2.headers.date) return n.return(0);
              l = k2.headers.date;
            } else l = Xb(k2.data);
            m = Date.parse(l);
            return isNaN(m) ? n.return(0) : n.return(m - Date.now());
          });
        }
        function fx(a, b, c) {
          var d2, e, f, g, h, k2, l, m;
          return P(function(n) {
            switch (n.g) {
              case 1:
                d2 = c.map(function(q) {
                  return {
                    scheme: q.attributes.schemeIdUri,
                    value: q.attributes.value
                  };
                }), e = a.g.dash.clockSyncUri, !d2.length && e && d2.push({
                  scheme: "urn:mpeg:dash:utc:http-head:2014",
                  value: e
                }), f = t2(d2), g = f.next();
              case 2:
                if (g.done) {
                  n.B(4);
                  break;
                }
                h = g.value;
                sa(n, 5);
                k2 = h.scheme;
                l = h.value;
                switch (k2) {
                  case "urn:mpeg:dash:utc:http-head:2014":
                  case "urn:mpeg:dash:utc:http-head:2012":
                    return n.B(7);
                  case "urn:mpeg:dash:utc:http-xsdate:2014":
                  case "urn:mpeg:dash:utc:http-iso:2014":
                  case "urn:mpeg:dash:utc:http-xsdate:2012":
                  case "urn:mpeg:dash:utc:http-iso:2012":
                    return n.B(8);
                  case "urn:mpeg:dash:utc:direct:2014":
                  case "urn:mpeg:dash:utc:direct:2012":
                    return m = Date.parse(l), n.return(isNaN(m) ? 0 : m - Date.now());
                  case "urn:mpeg:dash:utc:http-ntp:2014":
                  case "urn:mpeg:dash:utc:ntp:2014":
                  case "urn:mpeg:dash:utc:sntp:2014":
                    bb("NTP UTCTiming scheme is not supported");
                    break;
                  default:
                    bb("Unrecognized scheme in UTCTiming element", k2);
                }
                n.B(9);
                break;
              case 7:
                return G(n, Ax(a, b, l, "HEAD"), 10);
              case 10:
                return n.return(n.h);
              case 8:
                return G(n, Ax(a, b, l, "GET"), 11);
              case 11:
                return n.return(n.h);
              case 9:
                ua(n, 3);
                break;
              case 5:
                va(n);
              case 3:
                g = f.next();
                n.B(2);
                break;
              case 4:
                return bb("A UTCTiming element should always be given in live manifests! This content may not play on clients with bad clocks!"), n.return(0);
            }
          });
        }
        function px(a, b, c, d2, e) {
          var f = d2.attributes.schemeIdUri || "", g = d2.attributes.value || "", h = $d(d2, "timescale", he) || 1, k2 = $d(d2, "presentationTimeOffset", he) || 0;
          d2 = t2(Sd(d2, "Event"));
          for (var l = d2.next(); !l.done; l = d2.next()) {
            l = l.value;
            var m = $d(l, "presentationTime", he) || 0, n = $d(l, "duration", he) || 0;
            m = Math.max((m - k2) / h + b, b);
            n = m + n / h;
            c != null && (m = Math.min(m, b + c), n = Math.min(n, b + c));
            n < e || (l = {
              schemeIdUri: f,
              value: g,
              startTime: m,
              endTime: n,
              id: l.attributes.id || "",
              timescale: h,
              eventElement: qe(l),
              eventNode: re(l)
            }, a.j.onTimelineRegionAdded(l));
          }
        }
        function mx(a, b, c, d2, e) {
          var f, g, h, k2;
          return P(function(l) {
            if (l.g == 1) return f = gh, g = e ? 0 : 1, h = Jm(b, c, d2, a.g.retryParameters), G(l, Yw(a, h, f, {
              type: g
            }), 2);
            k2 = l.h;
            return l.return(k2.data);
          });
        }
        function ux(a, b) {
          b = ef(a, b);
          return vf(b) ? tc : a.split("/")[0];
        }
        function Yw(a, b, c, d2) {
          d2 || (d2 = {});
          d2.isPreload = a.ea();
          b = a.j.networkingEngine.request(c, b, d2);
          Vg(a.P, b);
          return b.promise;
        }
        function Xw(a) {
          var b = a.l.Ae;
          if (!a.l.Mf || !b || !a.H.length) return [];
          var c = Date.now() / 1e3, d2 = a.H.filter(function(e) {
            e = he(e.attributes.ttl);
            return !e || b + e > c;
          }).map(Ud).filter(Ff);
          return d2.length ? nc(a.C, d2) : [];
        }
        S("shaka.dash.DashParser", Tw);
        Gi("application/dash+xml", function() {
          return new Tw();
        });
        Gi("video/vnd.mpeg.dash.mpd", function() {
          return new Tw();
        });
        function Bx() {
        }
        S("shaka.dependencies", Bx);
        Bx.has = function(a) {
          return Cx.has(a);
        };
        Bx.add = function(a, b) {
          if (!Dx[a]) throw Error(a + " is not supported");
          a == Ex ? Wc("mux.js", "mux.js is no longer used in Shaka Player.") : Cx.set(a, function() {
            return b;
          });
        };
        var Ex = "muxjs", Dx = {
          Sn: Ex,
          ISOBoxer: "ISOBoxer"
        };
        Bx.Allowed = Dx;
        var Cx = /* @__PURE__ */ new Map([["ISOBoxer", function() {
          return window7.ISOBoxer;
        }]]);
        function Fx() {
          this.j = new Rb(function() {
            return ["Oculus", "Quest"].some(function(a) {
              return navigator.userAgent.includes(a.toLowerCase());
            }) ? "VR" : navigator.userAgent.match(/Smart( ?|_)TV/i) || navigator.userAgent.match(/Android ?TV/i) ? "TV" : navigator.userAgentData ? navigator.userAgentData.mobile ? "MOBILE" : "DESKTOP" : /(?:iPhone|iPad|iPod)/.test(navigator.userAgent) ? "MOBILE" : navigator.userAgentData && navigator.userAgentData.platform ? navigator.userAgentData.platform.toLowerCase() == "android" ? "MOBILE" : "DESKTOP" : navigator.userAgent.includes("Android") ? "MOBILE" : "DESKTOP";
          });
          this.l = new Rb(function() {
            return navigator.vendor.includes("Apple") && (navigator.userAgent.includes("Version/") || navigator.userAgent.includes("OS/")) ? "WEBKIT" : navigator.userAgent.includes("Edge/") ? "EDGE" : navigator.userAgent.includes("Chrome/") ? "CHROMIUM" : navigator.userAgent.includes("Firefox/") ? "GECKO" : "UNKNOWN";
          });
        }
        function Ji() {
          var a = window7.ManagedMediaSource || window7.MediaSource;
          return a && a.isTypeSupported ? true : false;
        }
        p = Fx.prototype;
        p.mc = function() {
          return !!navigator.mediaCapabilities;
        };
        p.Ka = function() {
          return this.j.value();
        };
        p.Ga = function() {
          return this.l.value();
        };
        p.Rd = function() {
          return false;
        };
        p.yj = function() {
          return false;
        };
        p.Af = function() {
          return false;
        };
        p.zj = function() {
          return false;
        };
        p.Ce = function() {
          return false;
        };
        p.td = function() {
          return true;
        };
        p.ud = function() {
          return true;
        };
        p.He = function() {
          return true;
        };
        p.Ej = function() {
          return 0;
        };
        p.tc = function() {
          return Promise.resolve({
            width: Infinity,
            height: Infinity
          });
        };
        p.Qj = function() {
          return false;
        };
        p.ki = function() {
          return false;
        };
        p.bb = function(a) {
          var b = this.Ka();
          if (b === "TV" || b === "CONSOLE" || b === "CAST") a.ads.customPlayheadTracker = true, a.ads.skipPlayDetection = true, a.ads.supportsMultipleMediaElements = false;
          return a;
        };
        p.oi = function() {
          return !!window7.indexedDB;
        };
        p.wj = function() {
          return [];
        };
        function Tn(a) {
          Sb();
          return window7.matchMedia !== void 0 && window7.matchMedia("(color-gamut: p3)").matches ? a ? "HLG" : "PQ" : "SDR";
        }
        p.kg = function() {
          return false;
        };
        p.mj = function() {
          return false;
        };
        p.Yh = function() {
          return false;
        };
        p.lg = function() {
          return true;
        };
        p.nj = function() {
          return false;
        };
        p.Yj = function() {
          return true;
        };
        p.sd = function() {
          return false;
        };
        p.Kh = function(a) {
          return a === "com.apple.fps";
        };
        p.toString = function() {
          return "Device: " + this.Ub() + " v" + this.Fa() + "; Type: " + this.Ka();
        };
        function Gx() {
          Fx.call(this);
          this.g = new Rb(function() {
            var a = navigator.userAgent.match(/Version\/(\d+)/);
            return a ? parseInt(a[1], 10) : (a = navigator.userAgent.match(/OS (\d+)(?:_\d+)?/)) ? parseInt(a[1], 10) : null;
          });
          this.h = new Rb(function() {
            return /(?:iPhone|iPad|iPod)/.test(navigator.userAgent) || navigator.maxTouchPoints > 1 ? "xr" in navigator ? "APPLE_VR" : "MOBILE" : "xr" in navigator ? "APPLE_VR" : "DESKTOP";
          });
        }
        ma(Gx, Fx);
        p = Gx.prototype;
        p.Fa = function() {
          return this.g.value();
        };
        p.Ub = function() {
          return "Apple Browser";
        };
        p.Ka = function() {
          return this.h.value();
        };
        p.Ga = function() {
          return "WEBKIT";
        };
        p.mc = function() {
          return false;
        };
        p.Rd = function(a, b) {
          return b === "audio";
        };
        p.Af = function() {
          return true;
        };
        p.zj = function(a) {
          return a === "audio";
        };
        p.bb = function(a) {
          Fx.prototype.bb.call(this, a);
          a.abr.minTimeToSwitch = 0.5;
          return a;
        };
        p.kg = function() {
          return true;
        };
        (navigator.vendor || "").includes("Apple") && (/(?:iPhone|iPad|iPod)/.test(navigator.userAgent) || navigator.maxTouchPoints > 1 || navigator.userAgentData && navigator.userAgentData.platform && navigator.userAgentData.platform.toLowerCase() == "macos" || navigator.platform && navigator.platform.toLowerCase().includes("mac")) && (Ub = function() {
          return new Gx();
        });
        function Hx() {
          if (!Ix()) throw Error("Not a Chromecast device!");
          Fx.call(this);
          this.h = new Rb(function() {
            var a = navigator.userAgent.match(/Chrome\/(\d+)/);
            return a ? parseInt(a[1], 10) : null;
          });
          this.g = new Rb(function() {
            var a = navigator.userAgentData && navigator.userAgentData.platform || navigator.userAgent;
            a = a.toLowerCase();
            return a.includes("android") ? Jx : a.includes("fuchsia") ? Kx : Lx;
          });
        }
        ma(Hx, Fx);
        p = Hx.prototype;
        p.Fa = function() {
          return this.h.value();
        };
        p.Ub = function() {
          return "Chromecast with " + this.g.value();
        };
        p.Ka = function() {
          return "CAST";
        };
        p.Ga = function() {
          return "CHROMIUM";
        };
        p.mc = function() {
          return Fx.prototype.mc.call(this) && this.g.value() !== Lx;
        };
        p.ud = function() {
          return this.g.value() !== Lx;
        };
        p.Ej = function() {
          switch (this.g.value()) {
            case Jx:
              return 0;
            case Kx:
              return 3;
            default:
              return 1;
          }
        };
        p.tc = function() {
          var a, b, c, d2, e;
          return P(function(f) {
            switch (f.g) {
              case 1:
                a = window7.cast && cast.__platform__ && cast.__platform__.canDisplayType;
                b = {
                  width: 1280,
                  height: 720
                };
                sa(f, 2);
                if (!(c = a)) {
                  f.B(4);
                  break;
                }
                return G(f, cast.__platform__.canDisplayType('video/mp4; codecs="avc1.640028"; width=3840; height=2160'), 5);
              case 5:
                c = f.h;
              case 4:
                if (c) {
                  b.width = 3840;
                  b.height = 2160;
                  f.B(6);
                  break;
                }
                if (!(d2 = a)) {
                  f.B(7);
                  break;
                }
                return G(f, cast.__platform__.canDisplayType('video/mp4; codecs="avc1.640028"; width=1920; height=1080'), 8);
              case 8:
                d2 = f.h;
              case 7:
                d2 && (b.width = 1920, b.height = 1080);
              case 6:
                ua(f, 3);
                break;
              case 2:
                e = va(f), ab("Failed to check canDisplayType:", e);
              case 3:
                return f.return(b);
            }
          });
        };
        p.bb = function(a) {
          Fx.prototype.bb.call(this, a);
          a.streaming.stallSkip = 0;
          return a;
        };
        p.oi = function() {
          return false;
        };
        p.sd = function() {
          return true;
        };
        function Ix() {
          return navigator.userAgent.includes("CrKey") && !navigator.userAgent.includes("VIZIO SmartCast");
        }
        var Jx = "Android", Kx = "Fuchsia", Lx = "Linux";
        Ix() && (Ub = function() {
          return new Hx();
        });
        function Mx() {
          Fx.call(this);
          var a = this;
          this.i = new Rb(function() {
            var b = navigator.userAgent.match(/(Chrome|Firefox)\/(\d+)/);
            return b ? parseInt(b[2], 10) : null;
          });
          this.g = new Rb(function() {
            return navigator.userAgent.match(/Edge?\//) ? "Edge" : navigator.userAgent.includes("Chrome") ? "Chrome" : navigator.userAgent.includes("Firefox") ? "Firefox" : "Unknown";
          });
          this.h = new Rb(function() {
            return navigator.userAgentData && navigator.userAgentData.platform ? navigator.userAgentData.platform.toLowerCase() == "windows" : navigator.platform ? navigator.platform.toLowerCase().includes("win32") : false;
          });
          this.A = new Rb(function() {
            return navigator.userAgent.match(/Edge?\//) ? !a.h.value() : true;
          });
          this.u = new Rb(function() {
            return navigator.userAgent.includes("sony.hbbtv.tv");
          });
          this.m = new Rb(function() {
            return navigator.userAgentData && navigator.userAgentData.platform ? navigator.userAgentData.platform.toLowerCase() == "android" : navigator.userAgent.includes("Android") ? true : false;
          });
        }
        ma(Mx, Fx);
        p = Mx.prototype;
        p.Fa = function() {
          return this.i.value();
        };
        p.Ub = function() {
          return this.g.value();
        };
        p.Rd = function(a) {
          return Bg(a) ? this.g.value() === "Edge" && this.h.value() : false;
        };
        p.yj = function() {
          return this.g.value() === "Edge" && this.h.value();
        };
        p.Af = function() {
          return this.g.value() === "Edge" && this.h.value();
        };
        p.ud = function() {
          return this.A.value();
        };
        p.bb = function(a) {
          Fx.prototype.bb.call(this, a);
          if (this.h.value()) switch (this.g.value()) {
            case "Firefox":
              a.drm.keySystemsMapping = {
                "com.microsoft.playready": "com.microsoft.playready.recommendation"
              };
              break;
            case "Chrome":
              a.drm.keySystemsMapping = {
                "com.microsoft.playready": "com.microsoft.playready.recommendation.3000",
                "com.microsoft.playready.recommendation": "com.microsoft.playready.recommendation.3000"
              };
          }
          this.m.value() && (a.drm.defaultAudioRobustnessForWidevine = "", a.drm.defaultVideoRobustnessForWidevine = "");
          return a;
        };
        p.Yh = function() {
          return this.g.value() === "Edge" || this.u.value();
        };
        p.sd = function() {
          if (this.Ga() === "GECKO") {
            var a = this.Fa();
            return a !== null ? a >= 100 : Fx.prototype.sd.call(this);
          }
          return Fx.prototype.sd.call(this);
        };
        p.Kh = function(a) {
          return this.Ga() === "GECKO" ? a.startsWith("com.microsoft.playready.recommendation") : Fx.prototype.Kh.call(this, a);
        };
        Vb = function() {
          return new Mx();
        };
        function Nx() {
          Fx.apply(this, arguments);
        }
        ma(Nx, Fx);
        p = Nx.prototype;
        p.Fa = function() {
          return null;
        };
        p.Ub = function() {
          return "Hisense";
        };
        p.Ka = function() {
          return "TV";
        };
        p.mc = function() {
          return false;
        };
        p.tc = function() {
          var a = {
            width: 1920,
            height: 1080
          }, b = null;
          if (window7.Hisense_Get4KSupportState) try {
            b = window7.Hisense_Get4KSupportState();
          } catch (c) {
          }
          b == null && (b = navigator.userAgent.includes("UHD"));
          b && (a.width = 3840, a.height = 2160);
          return Promise.resolve(a);
        };
        p.bb = function(a) {
          Fx.prototype.bb.call(this, a);
          a.streaming.stallSkip = 0;
          return a;
        };
        if (navigator.userAgent.includes("Hisense") || navigator.userAgent.includes("VIDAA")) Ub = function() {
          return new Nx();
        };
        function Ox() {
          Fx.call(this);
          this.g = new Rb(function() {
            var a = navigator.userAgent.match(/PlayStation (\d+)/);
            return a ? parseInt(a[1], 10) : null;
          });
        }
        ma(Ox, Fx);
        p = Ox.prototype;
        p.Ub = function() {
          return "PlayStation";
        };
        p.Ka = function() {
          return "CONSOLE";
        };
        p.Ga = function() {
          return "WEBKIT";
        };
        p.Fa = function() {
          return this.g.value();
        };
        p.mc = function() {
          return false;
        };
        p.td = function() {
          return false;
        };
        p.ud = function() {
          return false;
        };
        p.ki = function() {
          return this.Fa() === 4;
        };
        p.tc = function() {
          var a, b, c, d2, e;
          return P(function(f) {
            switch (f.g) {
              case 1:
                return a = {
                  width: 1920,
                  height: 1080
                }, b = false, sa(f, 2), G(f, window7.msdk.device.getDisplayInfo(), 4);
              case 4:
                c = f.h;
                b = c.resolution === "4K";
                ua(f, 3);
                break;
              case 2:
                return va(f), sa(f, 5), G(f, window7.msdk.device.getDisplayInfoImmediate(), 7);
              case 7:
                d2 = f.h;
                b = d2.resolution === "4K";
                ua(f, 3);
                break;
              case 5:
                e = va(f), bb("PlayStation: Failed to get the display info:", e);
              case 3:
                return b && (a.width = 3840, a.height = 2160), f.return(a);
            }
          });
        };
        p.bb = function(a) {
          Fx.prototype.bb.call(this, a);
          this.Fa() === 4 && a.drm.preferredKeySystems.push("com.microsoft.playready");
          a.streaming.clearDecodingCache = true;
          return a;
        };
        p.Yh = function() {
          return this.Fa() === 4;
        };
        p.lg = function() {
          return this.Fa() !== 4;
        };
        navigator.userAgent.includes("PlayStation") && (Ub = function() {
          return new Ox();
        });
        function Px() {
          Fx.call(this);
          var a = navigator.userAgent.match(/Tizen (\d+).(\d+)/);
          this.g = a ? parseInt(a[1], 10) : null;
          this.h = a ? parseInt(a[2], 10) : null;
        }
        ma(Px, Fx);
        p = Px.prototype;
        p.Fa = function() {
          return this.g;
        };
        p.Ub = function() {
          return "Tizen";
        };
        p.Ga = function() {
          return "CHROMIUM";
        };
        p.Ka = function() {
          return "TV";
        };
        p.Rd = function() {
          return true;
        };
        p.Ce = function() {
          return this.Fa() === 3;
        };
        p.mc = function() {
          return false;
        };
        p.td = function() {
          var a = this.Fa();
          return a !== null ? a >= 4 : Fx.prototype.td.call(this);
        };
        p.ud = function() {
          return false;
        };
        p.He = function() {
          return this.g && this.h ? this.g === 5 ? this.h >= 5 : this.g > 5 : Fx.prototype.He.call(this);
        };
        p.tc = function() {
          var a = window7.devicePixelRatio;
          a = {
            width: window7.screen.width * a > 1920 ? 3840 : 1920,
            height: window7.screen.height * a > 1080 ? 2160 : 1080
          };
          try {
            if (webapis.systeminfo && webapis.systeminfo.getMaxVideoResolution) {
              var b = webapis.systeminfo.getMaxVideoResolution();
              a.width = b.width;
              a.height = b.height;
            } else webapis.productinfo.is8KPanelSupported && webapis.productinfo.is8KPanelSupported() ? (a.width = 7680, a.height = 4320) : webapis.productinfo.isUdPanelSupported && webapis.productinfo.isUdPanelSupported() && (a.width = 3840, a.height = 2160);
          } catch (c) {
            bb("Tizen: Error detecting screen size, default screen size 1920x1080.");
          }
          return Promise.resolve(a);
        };
        p.bb = function(a) {
          Fx.prototype.bb.call(this, a);
          a.drm.ignoreDuplicateInitData = this.Fa() !== 2;
          this.Fa() === 3 && (a.streaming.crossBoundaryStrategy = "reset_to_encrypted");
          a.streaming.shouldFixTimestampOffset = true;
          a.streaming.stallSkip = 0;
          a.streaming.gapPadding = 2;
          return a;
        };
        p.wj = function() {
          var a = [];
          this.g !== null && this.g < 5 && a.push("opus");
          return a;
        };
        p.mj = function() {
          return true;
        };
        p.nj = function() {
          return this.Fa() === 3;
        };
        navigator.userAgent.includes("Tizen") && (Ub = function() {
          return new Px();
        });
        function Qx() {
          Fx.apply(this, arguments);
        }
        ma(Qx, Fx);
        Qx.prototype.Fa = function() {
          return null;
        };
        Qx.prototype.Ub = function() {
          return "Vizio";
        };
        Qx.prototype.Ka = function() {
          return "TV";
        };
        Qx.prototype.mc = function() {
          return false;
        };
        navigator.userAgent.includes("VIZIO SmartCast") && (Ub = function() {
          return new Qx();
        });
        function Rx() {
          Fx.call(this);
          this.i = new Rb(function() {
            return navigator.userAgent.includes("DT_STB_BCM") || navigator.userAgent.includes("Sky_STB");
          });
          this.h = new Rb(function() {
            return navigator.userAgent.includes("SOPOpenBrowser");
          });
          this.g = new Rb(function() {
            if (navigator.userAgent.includes("DT_STB_BCM")) return 11;
            var a = navigator.userAgent.match(/Version\/(\d+)/);
            return a ? parseInt(a[1], 10) : (a = navigator.userAgent.match(/OS (\d+)(?:_\d+)?/)) ? parseInt(a[1], 10) : null;
          });
        }
        ma(Rx, Fx);
        p = Rx.prototype;
        p.Fa = function() {
          return this.g.value();
        };
        p.Ub = function() {
          return "WebKit STB";
        };
        p.Ka = function() {
          return "TV";
        };
        p.Ga = function() {
          return "WEBKIT";
        };
        p.mc = function() {
          return false;
        };
        p.td = function() {
          var a = this.g.value();
          return a !== null ? a >= 15 : true;
        };
        p.Rd = function() {
          return this.h.value();
        };
        p.tc = function() {
          return Promise.resolve({
            width: window7.screen.width * window7.devicePixelRatio,
            height: window7.screen.height * window7.devicePixelRatio
          });
        };
        p.lg = function() {
          return !this.i.value();
        };
        if (navigator.userAgent.includes("SOPOpenBrowser") || navigator.userAgent.includes("DT_STB_BCM") || navigator.userAgent.includes("Sky_STB") || !(!(navigator.vendor || "").includes("Apple") || /(?:iPhone|iPad|iPod)/.test(navigator.userAgent) || navigator.maxTouchPoints > 1 || navigator.userAgentData && navigator.userAgentData.platform && navigator.userAgentData.platform.toLowerCase() == "macos" || navigator.platform && navigator.platform.toLowerCase().includes("mac"))) Ub = function() {
          return new Rx();
        };
        function Sx() {
          Fx.call(this);
          this.g = Tx();
        }
        ma(Sx, Fx);
        p = Sx.prototype;
        p.Fa = function() {
          return this.g;
        };
        p.Ub = function() {
          return "WebOS";
        };
        p.Ka = function() {
          return "TV";
        };
        p.Ga = function() {
          return "CHROMIUM";
        };
        p.mc = function() {
          return false;
        };
        p.td = function() {
          var a = this.Fa();
          return a !== null ? a > 3 : Fx.prototype.td.call(this);
        };
        p.ud = function() {
          var a = this.Fa();
          return a !== null ? a > 6 : Fx.prototype.ud.call(this);
        };
        p.He = function() {
          var a = this.Fa();
          return a !== null ? a > 3 : Fx.prototype.He.call(this);
        };
        p.tc = function() {
          var a = {
            width: 1920,
            height: 1080
          };
          try {
            var b = JSON.parse(window7.PalmSystem.deviceInfo);
            a.width = Math.max(1920, b.screenWidth);
            a.height = Math.max(1080, b.screenHeight);
          } catch (c) {
            bb("WebOS: Error detecting screen size, default screen size 1920x1080.");
          }
          return Promise.resolve(a);
        };
        p.bb = function(a) {
          Fx.prototype.bb.call(this, a);
          this.Fa() === 3 && (a.streaming.crossBoundaryStrategy = "reset");
          a.streaming.shouldFixTimestampOffset = true;
          a.streaming.stallSkip = 0;
          return a;
        };
        function Tx() {
          var a = null, b = navigator.userAgent.match(/Chrome\/(\d+)/);
          b && (a = parseInt(b[1], 10));
          switch (a) {
            case 38:
              return 3;
            case 53:
              return 4;
            case 68:
              return 5;
            case 79:
              return 6;
            case 87:
              return 22;
            case 94:
              return 23;
            case 108:
              return 24;
            case 120:
              return 25;
            default:
              return null;
          }
        }
        p.Yj = function() {
          return false;
        };
        p.sd = function() {
          var a = this.Fa();
          return a !== null ? a >= 6 : Fx.prototype.sd.call(this);
        };
        navigator.userAgent.includes("Web0S") && (Ub = function() {
          return new Sx();
        });
        function Ux() {
          Fx.call(this);
          this.g = navigator.userAgent.includes("Edge/");
          var a = navigator.userAgent.match(/Edge?\/(\d+)/);
          this.h = a ? parseInt(a[1], 10) : null;
        }
        ma(Ux, Fx);
        p = Ux.prototype;
        p.Fa = function() {
          return this.h;
        };
        p.Ub = function() {
          return "Xbox";
        };
        p.Ka = function() {
          return "CONSOLE";
        };
        p.Ga = function() {
          return this.g ? "EDGE" : "CHROMIUM";
        };
        p.Rd = function() {
          return true;
        };
        p.Af = function() {
          return true;
        };
        p.Qj = function() {
          return this.g;
        };
        p.tc = function() {
          var a = {
            width: 1920,
            height: 1080
          }, b = Vx();
          if (b) try {
            var c = new b.Media.Protection.ProtectionCapabilities(), d2 = b.Media.Protection.ProtectionCapabilityResult;
            b = null;
            do
              b = c.isTypeSupported('video/mp4;codecs="hvc1,mp4a";features="decode-res-x=3840,decode-res-y=2160,decode-bitrate=20000,decode-fps=30,decode-bpc=10,display-res-x=3840,display-res-y=2160,display-bpc=8"', "com.microsoft.playready.recommendation");
            while (b === d2.maybe);
            b === d2.probably && (a.width = 3840, a.height = 2160);
          } catch (e) {
            bb("Xbox: Error detecting screen size, default screen size 1920x1080.");
          }
          return Promise.resolve(a);
        };
        p.bb = function(a) {
          Fx.prototype.bb.call(this, a);
          a.drm.parseInbandPsshEnabled = this.g;
          a.drm.preferredKeySystems.push("com.microsoft.playready");
          this.g && (a.streaming.gapPadding = 0.01);
          return a;
        };
        p.oi = function() {
          return false;
        };
        function Vx() {
          var a = null;
          try {
            a = typeof Windows !== "undefined" ? Windows : chrome.webview.hostObjects.sync.Windows;
          } catch (b) {
          }
          return a;
        }
        if (navigator.userAgent.includes("Xbox One") || Vx() !== null) Ub = function() {
          return new Ux();
        };
        function Wx(a, b, c) {
          this.type = a;
          this.ma = b;
          this.segments = c || null;
        }
        function Xx(a, b, c, d2) {
          this.id = a;
          this.name = b;
          this.attributes = c;
          this.value = d2 === void 0 ? null : d2;
        }
        Xx.prototype.toString = function(a) {
          function b(e) {
            return e.name + "=" + (isNaN(Number(e.value)) ? '"' + e.value + '"' : e.value);
          }
          var c = "#" + this.name, d2 = this.attributes ? this.attributes.filter(function(e) {
            return a ? !a.has(e.name) : true;
          }).map(b) : [];
          this.value && d2.unshift(this.value);
          d2.length > 0 && (c += ":" + d2.join(","));
          return c;
        };
        function Yx(a, b) {
          if (b) return a.toString();
          b = (/* @__PURE__ */ new Set()).add("AUDIO").add("VIDEO").add("SUBTITLES").add("PATHWAY-ID").add("GROUP-ID").add("URI");
          return a.toString(b);
        }
        function Zx(a, b) {
          a = a.attributes.filter(function(c) {
            return c.name == b;
          });
          return a.length ? a[0] : null;
        }
        function $x(a, b, c) {
          return (a = Zx(a, b)) ? a.value : c || null;
        }
        function ay(a, b) {
          a = Zx(a, b);
          if (!a) throw new U(2, 4, 4023, b);
          return a.value;
        }
        function by(a, b, c) {
          c = c === void 0 ? [] : c;
          this.ma = b;
          this.g = a;
          this.Cc = c;
        }
        function cy(a, b) {
          this.name = a;
          this.value = b;
        }
        ;
        function dy(a, b) {
          return a.filter(function(c) {
            return c.name == b;
          });
        }
        function ey(a, b) {
          return a.filter(function(c) {
            return ay(c, "TYPE") == b;
          });
        }
        function fy(a, b) {
          a = t2(a);
          for (var c = a.next(); !c.done; c = a.next()) if (c = c.value, c.name === b) return c;
          return null;
        }
        function gy(a, b, c) {
          c = c === void 0 ? 0 : c;
          return (a = fy(a, b)) ? Number(a.value) : c;
        }
        function hy(a, b, c) {
          return b ? iy(a, [b], c) : [];
        }
        function iy(a, b, c) {
          if (!b.length) return [];
          var d2 = b;
          c && c.size && (d2 = b.map(function(e) {
            return jy(e, c);
          }));
          return nc(a, d2);
        }
        function jy(a, b) {
          if (!b || !b.size) return a;
          a = String(a).replace(/%7B/g, "{").replace(/%7D/g, "}");
          var c = a.match(/{\$\w*}/g);
          if (c) {
            c = t2(c);
            for (var d2 = c.next(); !d2.done; d2 = c.next()) {
              d2 = d2.value;
              var e = d2.slice(2, d2.length - 1), f = b.get(e);
              if (f) a = a.replace(d2, f);
              else throw new U(2, 4, 4039, e);
            }
          }
          return a;
        }
        ;
        function ky() {
          this.g = 0;
        }
        function ly(a, b) {
          b = Xb(b);
          b = b.replace(/\r\n|\r(?=[^\n]|$)/gm, "\n").trim();
          var c = b.split(/\n+/m);
          if (!/^#EXTM3U($|[ \t\n])/m.test(c[0])) throw new U(2, 4, 4015);
          b = 0;
          for (var d2 = true, e = t2(c), f = e.next(); !f.done; f = e.next()) if (f = f.value, /^#(?!EXT)/m.test(f) || d2) d2 = false;
          else if (f = my(a, f), --a.g, ny.includes(f.name)) {
            b = 1;
            break;
          } else f.name == "EXT-X-STREAM-INF" && (d2 = true);
          e = [];
          d2 = true;
          for (f = 0; f < c.length; f++) {
            var g = c[f], h = c[f + 1];
            if (/^#(?!EXT)/m.test(g) || d2) d2 = false;
            else {
              g = my(a, g);
              if (oy.includes(g.name)) {
                if (b != 1) throw new U(2, 4, 4017);
                g = c.splice(f, c.length - f);
                c = [];
                d2 = [];
                f = [];
                h = null;
                g = t2(g);
                for (var k2 = g.next(); !k2.done; k2 = g.next()) k2 = k2.value, /^(#EXT)/.test(k2) ? (k2 = my(a, k2), ny.includes(k2.name) ? e.push(k2) : k2.name == "EXT-X-MAP" ? h = k2 : k2.name == "EXT-X-PART" ? f.push(k2) : k2.name == "EXT-X-PRELOAD-HINT" ? $x(k2, "TYPE") == "PART" ? f.push(k2) : $x(k2, "TYPE") == "MAP" && (k2.name = "EXT-X-MAP", h = k2) : d2.push(k2)) : /^#(?!EXT)/m.test(k2) || (k2 = k2.trim(), h && d2.push(h), c.push(new by(k2, d2, f)), d2 = [], f = []);
                f.length && (h && d2.push(h), c.push(new by("", d2, f)));
                return new Wx(b, e, c);
              }
              e.push(g);
              g.name == "EXT-X-STREAM-INF" && (g.attributes.push(new cy("URI", h)), d2 = true);
            }
          }
          return new Wx(b, e);
        }
        function my(a, b) {
          a = a.g++;
          var c = b.match(/^#(EXT[^:]*)(?::(.*))?$/);
          if (!c) throw new U(2, 4, 4016, b);
          b = c[1];
          var d2 = c[2];
          c = [];
          var e;
          if (d2) {
            d2 = new xd(d2);
            var f;
            (f = zd(d2, /^([^,=]+)(?:,|$)/g)) && (e = f[1]);
            for (var g = /([^=]+)=(?:"([^"]*)"|([^",]*))(?:,|$)/g; f = zd(d2, g); ) c.push(new cy(f[1], f[2] || f[3])), yd(d2);
          }
          return new Xx(a, b, c, e);
        }
        var ny = "EXT-X-TARGETDURATION EXT-X-MEDIA-SEQUENCE EXT-X-DISCONTINUITY-SEQUENCE EXT-X-PLAYLIST-TYPE EXT-X-I-FRAMES-ONLY EXT-X-ENDLIST EXT-X-SERVER-CONTROL EXT-X-SKIP EXT-X-PART-INF EXT-X-DATERANGE".split(" "), oy = "EXTINF EXT-X-BYTERANGE EXT-X-DISCONTINUITY EXT-X-PROGRAM-DATE-TIME EXT-X-KEY EXT-X-DATERANGE EXT-X-MAP EXT-X-GAP EXT-X-TILES".split(" ");
        function py() {
        }
        function qy(a, b) {
          try {
            var c = ry(a);
            return Qg({
              uri: a,
              originalUri: a,
              data: c.data,
              headers: {
                "content-type": c.contentType
              },
              originalRequest: b
            });
          } catch (d2) {
            return Og(d2);
          }
        }
        function ry(a) {
          var b = a.split(":");
          if (b.length < 2 || b[0] != "data") throw new U(2, 1, 1004, a);
          b = b.slice(1).join(":").split(",");
          if (b.length < 2) throw new U(2, 1, 1004, a);
          var c = b[0];
          a = window7.decodeURIComponent(b.slice(1).join(","));
          b = c.split(";");
          c = b[0];
          var d2 = false;
          b.length > 1 && b[b.length - 1] == "base64" && (d2 = true, b.pop());
          var e;
          d2 ? e = jc(a) : e = ac(a);
          return {
            data: e,
            contentType: c
          };
        }
        S("shaka.net.DataUriPlugin", py);
        py.parse = qy;
        Xg("data", qy);
        function sy() {
          var a = this;
          this.g = this.h = null;
          this.H = 1;
          this.C = /* @__PURE__ */ new Map();
          this.K = /* @__PURE__ */ new Map();
          this.D = /* @__PURE__ */ new Map();
          this.D.set("video", /* @__PURE__ */ new Map());
          this.D.set("audio", /* @__PURE__ */ new Map());
          this.D.set(tc, /* @__PURE__ */ new Map());
          this.D.set("image", /* @__PURE__ */ new Map());
          this.jc = (/* @__PURE__ */ new Map()).set("com.apple.streamingkeydelivery", function(b, c, d2) {
            return ty(a, b, c, d2);
          }).set("urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed", function(b) {
            var c = ay(b, "METHOD");
            if (["SAMPLE-AES", "SAMPLE-AES-CTR"].includes(c)) {
              var d2 = "cenc";
              c == "SAMPLE-AES" && (d2 = "cbcs");
              c = ay(b, "URI");
              c = ry(c.split("?")[0]);
              c = Lb(c.data);
              d2 = oc("com.widevine.alpha", d2, [{
                initDataType: "cenc",
                initData: c
              }]);
              (b = $x(b, "KEYID")) && d2.keyIds.add(b.toLowerCase().substr(2));
              b = Promise.resolve(d2);
            } else b = Promise.resolve(null);
            return b;
          }).set("com.microsoft.playready", function(b) {
            var c = ay(b, "METHOD");
            if (["SAMPLE-AES", "SAMPLE-AES-CTR"].includes(c)) {
              var d2 = "cenc";
              c == "SAMPLE-AES" && (d2 = "cbcs");
              b = ay(b, "URI");
              b = ry(b.split("?")[0]);
              b = Lb(b.data);
              c = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]);
              c = Bh(b, c, /* @__PURE__ */ new Set(), 0);
              d2 = oc("com.microsoft.playready", d2, [{
                initDataType: "cenc",
                initData: c
              }]);
              if (b = Ld(["<PLAYREADY>", ic(b), "</PLAYREADY>"].join("\n"))) d2.licenseServerUri = bv(b);
              d2 = Promise.resolve(d2);
            } else d2 = Promise.resolve(null);
            return d2;
          }).set("urn:uuid:3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c", function(b) {
            var c = ay(b, "METHOD");
            if (["SAMPLE-AES", "SAMPLE-AES-CTR"].includes(c)) {
              var d2 = "cenc";
              c == "SAMPLE-AES" && (d2 = "cbcs");
              c = ay(b, "URI");
              c = ry(c.split("?")[0]);
              c = Lb(c.data);
              d2 = oc("com.huawei.wiseplay", d2, [{
                initDataType: "cenc",
                initData: c
              }]);
              (b = $x(b, "KEYID")) && d2.keyIds.add(b.toLowerCase().substr(2));
              b = Promise.resolve(d2);
            } else b = Promise.resolve(null);
            return b;
          });
          this.Za = /* @__PURE__ */ new Set();
          this.i = /* @__PURE__ */ new Map();
          this.l = null;
          this.G = "";
          this.hb = new ky();
          this.L = -1;
          this.$ = Infinity;
          this.Z = this.Ec = this.Va = false;
          this.F = new Cf(function() {
            if (a.S && !a.g.continueLoadingWhenPaused && (a.R.Ea(a.S, "timeupdate"), a.S.paused)) {
              a.R.qa(a.S, "timeupdate", function() {
                return uy(a);
              });
              return;
            }
            uy(a);
          });
          this.va = vy;
          this.m = null;
          this.Oa = 0;
          this.u = Infinity;
          this.Ma = this.Ia = this.P = 0;
          this.V = new Ug();
          this.I = /* @__PURE__ */ new Map();
          this.J = /* @__PURE__ */ new Map();
          this.ua = /* @__PURE__ */ new Map();
          this.ea = /* @__PURE__ */ new Map();
          this.M = /* @__PURE__ */ new Map();
          this.oa = /* @__PURE__ */ new Map();
          this.sa = /* @__PURE__ */ new Map();
          this.kc = this.aa = false;
          this.fb = new Nc(5);
          this.j = null;
          this.O = true;
          this.R = new Qc();
          this.A = this.S = null;
          this.Ob = function() {
            return false;
          };
        }
        p = sy.prototype;
        p.configure = function(a, b) {
          var c = this.h && a.updatePeriod != this.g.updatePeriod && a.updatePeriod >= 0;
          this.g = a;
          b && (this.Ob = b);
          this.j && this.j.configure(this.g);
          c && this.m && this.m.presentationTimeline.U() && this.F.La();
        };
        p.start = function(a, b) {
          var c = this, d2;
          return P(function(e) {
            return e.g == 1 ? (c.h = b, c.aa = b.isLowLatencyMode(), G(e, wy(c, [a]).promise, 2)) : e.g != 3 ? (d2 = e.h, c.G = d2.uri, G(e, xy(c, d2.data), 3)) : e.return(c.m);
          });
        };
        p.stop = function() {
          this.F && (this.F.stop(), this.F = null);
          var a = [];
          this.V && (a.push(this.V.destroy()), this.V = null);
          this.g = this.h = null;
          this.Za.clear();
          this.m = null;
          this.i.clear();
          this.K.clear();
          this.J.clear();
          this.C.clear();
          this.ua.clear();
          this.ea.clear();
          this.M.clear();
          this.oa.clear();
          this.sa.clear();
          this.j && this.j.destroy();
          this.R && (this.R.release(), this.R = null);
          return Promise.all(a);
        };
        p.update = function() {
          var a = this, b, c, d2, e, f, g, h, k2, l, m, n, q;
          return P(function(r2) {
            if (r2.g == 1) {
              if (!yy(a)) return r2.return();
              b = [];
              c = Array.from(a.i.values());
              a.u = Infinity;
              a.m.gapCount = 0;
              d2 = c.filter(function(u) {
                return u.stream.segmentIndex;
              });
              e = t2(d2);
              for (f = e.next(); !f.done; f = e.next()) g = f.value, b.push(zy(a, g));
              return G(r2, Promise.all(b), 2);
            }
            Ay(a, d2.map(function(u) {
              return u.stream;
            }));
            h = d2.some(function(u) {
              return u.me == 0;
            });
            d2.length && !h && (k2 = By, Cy(a, k2.ik), l = d2.map(function(u) {
              return u.zc;
            }), a.l.yb(Math.min.apply(Math, x(l))), a.h.updateDuration());
            h && Dy(a);
            m = t2(d2);
            for (n = m.next(); !n.done; n = m.next()) q = n.value, q.stream.isAudioMuxedInVideo || !q.stream.segmentIndex || fg(q.stream.segmentIndex) || a.h.disableStream(q.stream);
            H(r2);
          });
        };
        function Ey(a, b) {
          return yy(a) ? a.D.get(b.type) : b.Jf;
        }
        function zy(a, b) {
          var c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N, O, Q, R, V, Ba, aa, Oa, La;
          return P(function(Ja) {
            switch (Ja.g) {
              case 1:
                if (b.stream.isAudioMuxedInVideo) return Ja.return();
                c = [];
                d2 = t2(b.T());
                for (e = d2.next(); !e.done; e = d2.next()) f = e.value, g = new rb(f), h = g.g, b.jf && (b.Yb >= 0 && h.add("_HLS_msn", String(b.Yb)), b.Zb >= 0 && h.add("_HLS_part", String(b.Zb))), b.kf && h.add("_HLS_skip", "YES"), Ib(h) && wb(g, yb(h.toString())), c.push(g.toString());
                sa(Ja, 2);
                return G(Ja, wy(a, c, true).promise, 4);
              case 4:
                k2 = Ja.h;
                ua(Ja, 3);
                break;
              case 2:
                throw l = va(Ja), a.h && a.h.disableStream(b.stream), l;
              case 3:
                if (!b.stream.segmentIndex) return Ja.return();
                m = ly(a.hb, k2.data);
                if (m.type != 1) throw new U(2, 4, 4017);
                n = k2.uri;
                n == k2.originalUri || b.T().includes(n) || b.Zf.push(n);
                q = dy(m.ma, "EXT-X-DEFINE");
                r2 = Fy(a, q, n);
                u = b.stream;
                w = Ey(a, b);
                return G(Ja, Gy(a, m, u.mimeType, b.T, r2), 5);
              case 5:
                v = Ja.h;
                y = v.keyIds;
                z = v.drmInfos;
                A = v.encrypted;
                C = v.Fi;
                u.encrypted || !A || C || (u.encrypted = true);
                D = function(Ea, ya) {
                  return Ea.size === ya.size && [].concat(x(Ea)).every(function(Fa) {
                    return ya.has(Fa);
                  });
                };
                D(u.keyIds, y) || (u.keyIds = y, u.drmInfos = z, a.h.newDrmInfo(u));
                F = Hy(a, m, w, r2, b.T, b.type);
                B = F.segments;
                if (E = F.bandwidth) u.bandwidth = E;
                I = nm(u);
                J = t2(B);
                for (K = J.next(); !K.done; K = J.next()) L = K.value, L.ha && (L.ha.Kd = I);
                u.segmentIndex.we(B, a.l.Nb());
                B.length && (M = gy(m.ma, "EXT-X-MEDIA-SEQUENCE", 0), O = (N = fy(m.ma, "EXT-X-SKIP")) ? Number($x(N, "SKIPPED-SEGMENTS")) : 0, Q = Iy(M, B), R = Q.Yb, V = Q.Zb, b.Yb = R + O, b.Zb = V, Ba = w.get(M), u.segmentIndex.ib(Ba));
                if (aa = fg(u.segmentIndex)) b.md = aa.startTime, Oa = B[B.length - 1], b.zc = Oa.endTime;
                if (La = fy(m.ma, "EXT-X-ENDLIST")) b.me = true;
                Jy(a, m);
                Ky(a, m.ma, u.type, r2, b.T);
                H(Ja);
            }
          });
        }
        p.onExpirationUpdated = function() {
        };
        p.onInitialVariantChosen = function() {
        };
        p.banLocation = function(a) {
          this.j && this.j.banLocation(a);
        };
        p.setMediaElement = function(a) {
          this.S = a;
        };
        function Ly(a, b, c) {
          c = c === void 0 ? false : c;
          for (var d2 = a.L == -1, e = t2(b), f = e.next(); !f.done; f = e.next()) {
            f = f.value;
            var g = f.stream.segmentIndex, h = Ey(a, f);
            if (g = fg(g)) {
              h = t2(h);
              for (var k2 = h.next(); !k2.done; k2 = h.next()) {
                k2 = t2(k2.value);
                var l = k2.next().value;
                if (k2.next().value == g.startTime) {
                  d2 && (a.L = Math.max(a.L, l));
                  f.Wg = l;
                  break;
                }
              }
            }
          }
          if (!(a.L < 0)) {
            for (b = t2(b), d2 = b.next(); !d2.done; d2 = b.next()) if (d2 = d2.value, My(a, d2.type) || c) {
              if (e = d2.stream.segmentIndex) {
                if (f = a.L - d2.Wg, f > 0 && (e.g.splice(0, f), e = fg(e))) e = -e.startTime, d2.stream.segmentIndex.offset(e), Ny(a, d2, e);
              }
            }
          }
        }
        function Oy(a, b) {
          if (a.$ == Infinity) {
            b = t2(b);
            for (var c = b.next(); !c.done; c = b.next()) c = fg(c.value.stream.segmentIndex), c != null && c.h != null && (a.$ = Math.min(a.$, c.h));
          }
          b = a.$;
          if (b != Infinity) {
            c = t2(a.i.values());
            for (var d2 = c.next(); !d2.done; d2 = c.next()) if (d2 = d2.value, !My(a, d2.type)) {
              var e = d2.stream.segmentIndex;
              if (e != null) {
                var f = fg(e);
                if (f) if (f.h == null) ab("Missing EXT-X-PROGRAM-DATE-TIME for stream", d2.T(), "Expect AV sync issues!");
                else for (Ny(a, d2, f.h - b - f.startTime), d2 = t2(e), e = d2.next(); !e.done; e = d2.next()) e.value.pi(b);
              }
            }
          }
        }
        function Ny(a, b, c) {
          if (!(Math.abs(c) < 1e-3)) {
            b.md += c;
            b.zc += c;
            a = Ey(a, b);
            for (var d2 = t2(a), e = d2.next(); !e.done; e = d2.next()) {
              var f = t2(e.value);
              e = f.next().value;
              f = f.next().value;
              a.set(e, f + c);
            }
            b.T();
          }
        }
        function xy(a, b) {
          var c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N, O, Q, R, V, Ba, aa, Oa, La, Ja, Ea, ya, Fa, Da, za;
          return P(function(Ca) {
            switch (Ca.g) {
              case 1:
                c = vc;
                d2 = ly(a.hb, b);
                e = dy(d2.ma, "EXT-X-DEFINE");
                f = [];
                g = [];
                h = [];
                a.l = new Al(null, 0);
                a.l.rd(true);
                k2 = function() {
                  return [a.G];
                };
                l = null;
                m = /* @__PURE__ */ new Map();
                if (d2.type == 1) return a.O = false, R = dy(d2.ma, "EXT-X-DEFINE"), m = Fy(a, R, a.G), l = c.Ja, V = "", Ba = /* @__PURE__ */ new Map(), G(Ca, Py(a, a.H++, m, d2, k2, "", l, V, true, "Media Playlist", null, Ba, null, false, null, false), 7);
                Qy(a, e);
                n = dy(d2.ma, "EXT-X-MEDIA");
                q = dy(d2.ma, "EXT-X-STREAM-INF");
                r2 = dy(d2.ma, "EXT-X-IMAGE-STREAM-INF");
                u = dy(d2.ma, "EXT-X-I-FRAME-STREAM-INF");
                w = dy(d2.ma, "EXT-X-SESSION-KEY");
                v = dy(d2.ma, "EXT-X-SESSION-DATA");
                y = dy(d2.ma, "EXT-X-CONTENT-STEERING");
                Ry(a, v);
                return G(Ca, Sy(a, y), 4);
              case 4:
                if (!a.g.ignoreSupplementalCodecs) {
                  z = [];
                  A = t2(q);
                  C = A.next();
                  for (D = {}; !C.done; D = {
                    Wj: void 0
                  }, C = A.next()) if (F = C.value, B = $x(F, "SUPPLEMENTAL-CODECS")) D.Wj = B.split(/\s*,\s*/).map(function(fb) {
                    return fb.split("/")[0];
                  }), E = F.attributes.map(/* @__PURE__ */ function(fb) {
                    return function(hb) {
                      var ib = hb.name, xb = hb.value;
                      ib == "CODECS" && (xb = fb.Wj.join(","), hb = hb.value.split(","), hb.length > 1 && (hb = rc("audio", hb)) && (xb += "," + hb));
                      return new cy(ib, xb);
                    };
                  }(D)), z.push(new Xx(F.id, F.name, E, null));
                  q.push.apply(q, x(z));
                  I = [];
                  J = t2(u);
                  K = J.next();
                  for (L = {}; !K.done; L = {
                    Xj: void 0
                  }, K = J.next()) if (M = K.value, N = $x(M, "SUPPLEMENTAL-CODECS")) L.Xj = N.split(/\s*,\s*/).map(function(fb) {
                    return fb.split("/")[0];
                  }), O = M.attributes.map(/* @__PURE__ */ function(fb) {
                    return function(hb) {
                      var ib = hb.name;
                      hb = hb.value;
                      ib == "CODECS" && (hb = fb.Xj.join(","));
                      return new cy(ib, hb);
                    };
                  }(L)), I.push(new Xx(M.id, M.name, O, null));
                  u.push.apply(u, x(I));
                }
                Ty(a, q);
                Uy(a, n);
                Q = Vy(a, u);
                return G(Ca, Wy(a, q, w, n, k2, a.C, Q), 5);
              case 5:
                return f = Ca.h, g = Xy(a, n), G(Ca, Yy(a, r2, u), 6);
              case 6:
                h = Ca.h;
                Ca.B(3);
                break;
              case 7:
                aa = Ca.h, a.i.set(a.G, aa), aa.stream && (Oa = nm(aa.stream), aa.stream.segmentIndex.Kb(function(fb) {
                  fb.ha && (fb.ha.Kd = Oa);
                })), l = aa.stream.type, La = true, a.g.disableAudio && aa.type == "audio" ? La = false : a.g.disableVideo && aa.type == "video" && !aa.stream.codecs.includes(",") && (La = false), La && f.push({
                  id: 0,
                  language: zc(V || "und"),
                  disabledUntilTime: 0,
                  primary: true,
                  audio: aa.type == "audio" ? aa.stream : null,
                  video: aa.type == "video" ? aa.stream : null,
                  bandwidth: aa.stream.bandwidth || 0,
                  allowedByApplication: true,
                  allowedByKeySystem: true,
                  decodingInfos: []
                });
              case 3:
                if (!a.h) throw new U(2, 7, 7001);
                Zy(a, d2);
                d2.type == 1 && (yy(a) && ($y(a, d2), Ja = a.u, a.F.Y(Ja)), Ea = Array.from(a.i.values()), az(a, Ea), Dy(a), Ky(a, d2.ma, l, m, k2));
                a.m = {
                  presentationTimeline: a.l,
                  variants: f,
                  textStreams: g,
                  imageStreams: h,
                  offlineSessionIds: [],
                  sequenceMode: a.g.hls.sequenceMode,
                  ignoreManifestTimestampsInSegmentsMode: a.g.hls.ignoreManifestTimestampsInSegmentsMode,
                  type: "HLS",
                  serviceDescription: null,
                  nextUrl: null,
                  periodCount: 1,
                  gapCount: 0,
                  isLowLatency: false,
                  startTime: a.A
                };
                if (a.Z || !a.g.hls.disableCodecGuessing) {
                  Ca.B(8);
                  break;
                }
                ya = [];
                Fa = t2(a.m.variants);
                for (Da = Fa.next(); !Da.done; Da = Fa.next()) za = Da.value, za.audio && za.audio.codecs === "" && ya.push(za.audio.createSegmentIndex()), za.video && za.video.codecs === "" && ya.push(za.video.createSegmentIndex());
                return G(Ca, Promise.all(ya), 8);
              case 8:
                a.h.makeTextStreamsForClosedCaptions(a.m), H(Ca);
            }
          });
        }
        function bz(a, b) {
          var c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A;
          return P(function(C) {
            if (C.g == 1) {
              c = Dm(a.g.hls.mediaPlaylistFullMimeType);
              if (!b.length) return C.return(c);
              d2 = cz(a, b);
              e = d2.segment;
              f = d2.segmentIndex;
              g = e.T();
              h = g[0];
              k2 = new rb(h);
              l = k2.xb.split(".").pop();
              return (m = dz.get(l)) ? C.return(Dm(m)) : G(C, Promise.all([ez(a, e.ha, 0), ez(a, e, f)]), 2);
            }
            n = C.h;
            q = n[1].mimeType;
            r2 = n[0].data;
            u = n[1].data;
            w = "mp4 mp4a m4s m4i m4a m4f cmfa mp4v m4v cmfv fmp4".split(" ");
            v = ["audio/mp4", "video/mp4", "video/iso.segment"];
            y = e.ha || v.includes(q);
            if (!y && xk(Lb(u))) {
              var D = u, F = a.g.disableAudio, B = a.g.disableVideo, E = a.g.disableText;
              var I = Lb(D);
              var J = new pk().parse(I), K = J.je();
              I = J.xh();
              var L = [], M = false, N = false;
              if (!F) switch (K.audio) {
                case "aac":
                case "aac-loas":
                  J.Bb().length && (L.push("mp4a.40.2"), M = true);
                  break;
                case "mp3":
                  J.Bb().length && (L.push("mp4a.40.34"), M = true);
                  break;
                case "ac3":
                  J.Bb().length && (L.push("ac-3"), M = true);
                  break;
                case "ec3":
                  J.Bb().length && (L.push("ec-3"), M = true);
                  break;
                case "opus":
                  J.Bb().length && (L.push("opus"), M = true);
              }
              if (!B) switch (K.video) {
                case "avc":
                  I.codec ? L.push(I.codec) : L.push("avc1.42E01E");
                  N = true;
                  break;
                case "hvc":
                  I.codec ? L.push(I.codec) : L.push("hvc1.1.6.L93.90");
                  N = true;
                  break;
                case "av1":
                  L.push("av01.0.01M.08"), N = true;
              }
              if (L.length) {
                F = M && !N;
                B = /* @__PURE__ */ new Map();
                if (N && !E) {
                  E = new ld("video/mp2t");
                  E.Tf(D);
                  D = t2(E.zg());
                  for (N = D.next(); !N.done; N = D.next()) N = N.value, B.set(N, N);
                  E.$d();
                }
                I = {
                  type: F ? "audio" : "video",
                  mimeType: "video/mp2t",
                  codecs: L.join(", "),
                  language: null,
                  height: I.height,
                  width: I.width,
                  channelCount: null,
                  sampleRate: null,
                  closedCaptions: B,
                  Ke: null,
                  colorGamut: null,
                  frameRate: I.frameRate
                };
              } else I = null;
              if (z = I) return C.return(z);
            } else if (y || w.includes(l)) {
              if (A = Em(r2, u, a.g.disableText)) return C.return(A);
            }
            return q ? C.return(Dm(q)) : C.return(c);
          });
        }
        function ez(a, b, c) {
          var d2, e, f, g, h, k2;
          return P(function(l) {
            switch (l.g) {
              case 1:
                if (!b) return l.return({
                  mimeType: null,
                  data: null
                });
                d2 = gh;
                e = Jm(b.T(), b.Nc(), b.Lc(), a.g.retryParameters);
                f = b instanceof Cj ? 1 : 0;
                return G(l, fz(a, e, d2, {
                  type: f
                }).promise, 2);
              case 2:
                g = l.h;
                h = g.data;
                if (!b.aesKey) {
                  l.B(3);
                  break;
                }
                return G(l, Im(h, b.aesKey, c), 4);
              case 4:
                h = l.h;
              case 3:
                return b instanceof Cj ? b.Ee(h, true) : b.Ee(h), (k2 = g.headers["content-type"]) && (k2 = k2.split(";")[0].toLowerCase()), l.return({
                  mimeType: k2,
                  data: h
                });
            }
          });
        }
        function Dy(a) {
          if (yy(a)) {
            if (a.va == gz) {
              for (var b = Infinity, c = Infinity, d2 = t2(a.i.values()), e = d2.next(); !e.done; e = d2.next()) e = e.value, e.stream.segmentIndex && e.stream.type != "text" && !e.stream.isAudioMuxedInVideo && (b = Math.min(b, e.zc), c = Math.min(c, e.md));
              b = b - c || 0;
              isNaN(a.g.availabilityWindowOverride) || (b = a.g.availabilityWindowOverride);
              a.l.hg(b);
            }
          } else a.l.yb(hz(a));
          if (!a.l.u) for (b = t2(a.i.values()), c = b.next(); !c.done; c = b.next()) c = c.value, !c.stream.segmentIndex || c.type != "audio" && c.type != "video" || (c = fg(c.stream.segmentIndex)) && c.h && a.l.ei(c.h);
          a.l.If();
        }
        function Qy(a, b) {
          var c = new rb(a.G).g;
          b = t2(b);
          for (var d2 = b.next(); !d2.done; d2 = b.next()) {
            var e = d2.value;
            d2 = $x(e, "NAME");
            var f = $x(e, "VALUE");
            e = $x(e, "QUERYPARAM");
            d2 && f && (a.C.has(d2) || a.C.set(d2, f));
            e && (d2 = c.get(e)[0]) && !a.C.has(d2) && a.C.set(e, d2);
          }
        }
        function Fy(a, b, c) {
          c = new rb(c).g;
          var d2 = /* @__PURE__ */ new Map();
          b = t2(b);
          for (var e = b.next(); !e.done; e = b.next()) {
            var f = e.value, g = $x(f, "NAME"), h = $x(f, "VALUE");
            e = $x(f, "QUERYPARAM");
            f = $x(f, "IMPORT");
            g && h && (d2.has(g) || d2.set(g, h));
            e && (g = c.get(e)[0]) && !d2.has(g) && d2.set(e, g);
            f && (e = a.C.get(f)) && d2.set(f, e);
          }
          return d2;
        }
        function Ty(a, b) {
          b = t2(b);
          for (var c = b.next(); !c.done; c = b.next()) {
            var d2 = c.value, e = $x(d2, "AUDIO");
            c = $x(d2, "VIDEO");
            var f = $x(d2, "SUBTITLES");
            d2 = iz(a, d2);
            if (f) {
              var g = rc(tc, d2);
              a.J.set(f, g);
              ud(d2, g);
            }
            e && (f = rc("audio", d2), f || (f = a.g.hls.defaultAudioCodec), a.J.set(e, f));
            c && (e = rc("video", d2), e || (e = a.g.hls.defaultVideoCodec), a.J.set(c, e));
          }
        }
        function Ry(a, b) {
          b = t2(b);
          for (var c = b.next(); !c.done; c = b.next()) {
            var d2 = c.value, e = $x(d2, "DATA-ID");
            c = $x(d2, "URI");
            var f = $x(d2, "LANGUAGE");
            d2 = $x(d2, "VALUE");
            e = (/* @__PURE__ */ new Map()).set("id", e);
            c && e.set("uri", hy([a.G], c, a.C)[0]);
            f && e.set("language", f);
            d2 && e.set("value", d2);
            c = new T("sessiondata", e);
            if (a.h) a.h.onEvent(c);
          }
        }
        function Sy(a, b) {
          var c, d2, e, f, g, h;
          return P(function(k2) {
            if (!a.h || !a.g) return k2.return();
            d2 = t2(b);
            for (e = d2.next(); !e.done; e = d2.next()) if (f = e.value, g = $x(f, "PATHWAY-ID"), h = $x(f, "SERVER-URI"), g && h) {
              a.j = new Zv(a.h);
              a.j.configure(a.g);
              a.j.i = [a.G];
              a.j.setManifestType("HLS");
              a.j.h = g;
              c = $v(a.j, h);
              break;
            }
            return G(k2, c, 0);
          });
        }
        function Xy(a, b) {
          var c = ey(b, "SUBTITLES");
          b = c.map(function(g) {
            if (a.g.disableText) return null;
            try {
              return jz(a, [g], /* @__PURE__ */ new Map()).stream;
            } catch (h) {
              if (a.g.hls.ignoreTextStreamFailures) return null;
              throw h;
            }
          });
          c = t2(c);
          for (var d2 = c.next(); !d2.done; d2 = c.next()) {
            var e = ay(d2.value, "GROUP-ID");
            if (d2 = a.J.get(e)) {
              if (e = a.K.get(e)) {
                e = t2(e);
                for (var f = e.next(); !f.done; f = e.next()) f = f.value, f.stream.codecs = d2, f.stream.mimeType = kz(tc, d2) || lz(tc), mz(f.stream);
              }
            }
          }
          return b.filter(function(g) {
            return g;
          });
        }
        function mz(a) {
          var b = /* @__PURE__ */ new Set([ef(a.mimeType, a.codecs)]);
          a.segmentIndex && a.segmentIndex.Kb(function(c) {
            c.mimeType && b.add(ef(c.mimeType, a.codecs));
          });
          a.fullMimeTypes = b;
        }
        function Yy(a, b, c) {
          var d2, e;
          return P(function(f) {
            if (f.g == 1) return d2 = b.map(function(g) {
              var h, k2, l;
              return P(function(m) {
                if (m.g == 1) {
                  if (h = a.g.disableThumbnails) return m.return(null);
                  sa(m, 2);
                  return G(m, nz(a, g), 4);
                }
                if (m.g != 2) return k2 = m.h, m.return(k2.stream);
                l = va(m);
                if (a.g.hls.ignoreImageStreamFailures) return m.return(null);
                throw l;
              });
            }).concat(c.map(function(g) {
              if (a.g.disableThumbnails) return null;
              try {
                var h = oz(a, g);
                return h.stream.type !== "image" ? null : h.stream;
              } catch (k2) {
                if (a.g.hls.ignoreImageStreamFailures) return null;
                throw k2;
              }
            })), G(f, Promise.all(d2), 2);
            e = f.h;
            return f.return(e.filter(function(g) {
              return g;
            }));
          });
        }
        function pz(a, b, c) {
          b = b.filter(function(h) {
            var k2 = $x(h, "URI") || "";
            h = $x(h, "TYPE");
            return h != "SUBTITLES" && (k2 != "" || h == "AUDIO");
          });
          var d2 = {};
          b = t2(b);
          for (var e = b.next(); !e.done; e = b.next()) {
            e = e.value;
            var f = Yx(e, !a.j);
            d2[f] ? d2[f].push(e) : d2[f] = [e];
          }
          for (var g in d2) jz(a, d2[g], c, false);
        }
        function Vy(a, b) {
          return b.map(function(c) {
            c = oz(a, c);
            return c.stream.type !== "video" ? null : c.stream;
          }).filter(function(c) {
            return c;
          });
        }
        function Wy(a, b, c, d2, e, f, g) {
          var h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N, O, Q, R, V, Ba, aa, Oa, La, Ja, Ea, ya, Fa;
          return P(function(Da) {
            switch (Da.g) {
              case 1:
                h = [];
                k2 = /* @__PURE__ */ new Set();
                if (a.g.ignoreDrmInfo || !(c.length > 0)) {
                  Da.B(2);
                  break;
                }
                l = t2(c);
                m = l.next();
              case 3:
                if (m.done) {
                  Da.B(2);
                  break;
                }
                n = m.value;
                q = ay(n, "METHOD");
                r2 = $x(n, "KEYFORMAT") || "identity";
                u = null;
                if (q == "NONE") {
                  Da.B(4);
                  break;
                }
                if (qz(q)) {
                  w = hy(e(), ay(n, "URI"), f);
                  v = w.sort().join("");
                  a.M.has(v) || (y = ah(w, a.g.retryParameters), z = fz(a, y, 6).promise, a.M.set(v, z));
                  Da.B(4);
                  break;
                }
                if (r2 == "identity") return G(Da, rz(a, n, "", e, null, f), 12);
                A = a.jc.get(r2);
                if (!A) {
                  C = null;
                  Da.B(10);
                  break;
                }
                return G(Da, A(n, "", null), 11);
              case 11:
                C = Da.h;
              case 10:
                u = C;
                Da.B(6);
                break;
              case 12:
                u = Da.h;
              case 6:
                if (u) {
                  if (u.keyIds) for (D = t2(u.keyIds), F = D.next(); !F.done; F = D.next()) B = F.value, k2.add(B);
                  h.push(u);
                }
              case 4:
                m = l.next();
                Da.B(3);
                break;
              case 2:
                E = {};
                I = t2(b);
                for (J = I.next(); !J.done; J = I.next()) K = J.value, L = Yx(K, !a.j), E[L] ? E[L].push(K) : E[L] = [K];
                M = [];
                for (N in E) O = E[N], Q = O[0], R = $x(Q, "FRAME-RATE"), V = Number($x(Q, "AVERAGE-BANDWIDTH")) || Number(ay(Q, "BANDWIDTH")), Ba = $x(Q, "RESOLUTION"), aa = t2(Ba ? Ba.split("x") : [null, null]), Oa = aa.next().value, La = aa.next().value, Ja = $x(Q, "VIDEO-RANGE"), (Ea = $x(Q, "REQ-VIDEO-LAYOUT")) && Ea.includes(",") && (ya = Ea.split(",").filter(function(za) {
                  return za == "CH-STEREO" || za == "CH-MONO";
                }), Ea = ya[0]), Ea = Ea || "CH-MONO", Fa = sz(a, O, d2), M.push.apply(M, x(tz(a, Fa.audio, Fa.video, V, Oa, La, R, Ja, Ea, h, k2, g)));
                return Da.return(M.filter(function(za) {
                  return za != null;
                }));
            }
          });
        }
        function sz(a, b, c) {
          for (var d2 = {
            audio: [],
            video: []
          }, e = /* @__PURE__ */ new Map(), f = [], g = false, h = false, k2 = t2(b), l = k2.next(); !l.done; l = k2.next()) {
            var m = l.value;
            l = $x(m, "AUDIO");
            var n = $x(m, "VIDEO"), q = l || n;
            q && (f.includes(q) || f.push(q), (m = $x(m, "PATHWAY-ID")) && e.set(q, m), l ? g = true : n && (h = true));
          }
          f.length && c.length && (c = c.filter(function(u) {
            return f.includes(ay(u, "GROUP-ID"));
          }), pz(a, c, e));
          c = (e = f.sort().join(",")) && a.K.has(e) ? a.K.get(e) : [];
          g ? d2.audio.push.apply(d2.audio, x(c)) : h && d2.video.push.apply(d2.video, x(c));
          g = false;
          var r2 = b.map(function(u) {
            return ay(u, "URI");
          });
          l = d2.audio.find(function(u) {
            return u && u.T().find(function(w) {
              return r2.includes(w);
            });
          });
          h = iz(a, b[0]);
          c = rc("video", h);
          (k2 = rc("audio", h)) && !c ? (l = "audio", g = d2.audio.length > 0) : !d2.audio.length && !d2.video.length && k2 && c ? (l = "video", h = [[c, k2].join()]) : d2.audio.length && l ? (l = "audio", g = true) : l = d2.video.length && !d2.audio.length ? "audio" : "video";
          g || (a = uz(a, b, h, l), e && (a.stream.groupId = e), d2[a.stream.type] = [a]);
          return d2;
        }
        function iz(a, b) {
          b = $x(b, "CODECS") || "";
          a.Z = b.length > 0;
          a.Z || a.g.hls.disableCodecGuessing || (b = [], a.g.disableVideo || b.push(a.g.hls.defaultVideoCodec), a.g.disableAudio || b.push(a.g.hls.defaultAudioCodec), b = b.join(","));
          return Fm(b.split(/\s*,\s*/));
        }
        function tz(a, b, c, d2, e, f, g, h, k2, l, m, n) {
          for (var q = t2(c), r2 = q.next(); !r2.done; r2 = q.next()) vz(r2.value.stream, e, f, g, h, k2, null);
          e = a.g.disableVideo;
          if (!c.length || e) c = [null];
          e && (b = b.filter(function(y) {
            return !y.stream.isAudioMuxedInVideo;
          }));
          e = a.g.disableAudio;
          if (!b.length || e) b = [null];
          e = [];
          b = t2(b);
          for (f = b.next(); !f.done; f = b.next()) for (f = f.value, g = t2(c), h = g.next(); !h.done; h = g.next()) {
            var u = h.value;
            if (h = f ? f.stream : null) h.drmInfos = l, h.keyIds = m;
            if (k2 = u ? u.stream : null) k2.drmInfos = l, k2.keyIds = m, a.g.disableIFrames || pg(k2, n);
            k2 && !h && (k2.bandwidth = d2);
            !k2 && h && (h.bandwidth = d2);
            q = f ? f.stream.drmInfos : null;
            r2 = u ? u.stream.drmInfos : null;
            u = u ? u.T().sort().join(",") : "";
            var w = f ? f.T().sort().join(",") : "", v = [];
            h && h.codecs && v.push(h.codecs);
            k2 && k2.codecs && v.push(k2.codecs);
            u = [u, w, v.sort()].join("-");
            h && k2 && !yg(q, r2) || a.Za.has(u) || (h = {
              id: a.H++,
              language: h ? h.language : "und",
              disabledUntilTime: 0,
              primary: !!h && h.primary || !!k2 && k2.primary,
              audio: h,
              video: k2,
              bandwidth: d2,
              allowedByApplication: true,
              allowedByKeySystem: true,
              decodingInfos: []
            }, e.push(h), a.Za.add(u));
          }
          return e;
        }
        function Uy(a, b) {
          b = ey(b, "CLOSED-CAPTIONS");
          a.O = b.length == 0;
          b = t2(b);
          for (var c = b.next(); !c.done; c = b.next()) {
            var d2 = c.value, e = $x(d2, "LANGUAGE");
            c = zc(e || "und");
            e || (e = $x(d2, "NAME")) && (c = e);
            e = ay(d2, "GROUP-ID");
            d2 = ay(d2, "INSTREAM-ID").replace("SERVICE", "svc");
            a.I.get(e) || a.I.set(e, /* @__PURE__ */ new Map());
            a.I.get(e).set(d2, c);
          }
        }
        function jz(a, b, c, d2) {
          d2 = d2 === void 0 ? true : d2;
          for (var e = [], f = [], g = /* @__PURE__ */ new Map(), h = t2(b), k2 = h.next(); !k2.done; k2 = h.next()) {
            var l = k2.value;
            k2 = d2 ? ay(l, "URI") : $x(l, "URI") || "shaka://hls-muxed";
            l = ay(l, "GROUP-ID");
            e.push(k2);
            f.push(l);
            g.set(l, k2);
          }
          d2 = f.sort().join(",");
          k2 = b[0];
          b = "";
          h = ay(k2, "TYPE").toLowerCase();
          h == "subtitles" && (h = tc);
          if (h == tc) b = $x(k2, "CODECS") || "";
          else for (f = t2(f), l = f.next(); !l.done; l = f.next()) if (l = l.value, a.J.has(l)) {
            b = a.J.get(l);
            break;
          }
          f = e.sort().join(",");
          if (a.i.has(f)) return a.i.get(f);
          l = a.H++;
          if (a.j) {
            g = t2(g);
            for (var m = g.next(); !m.done; m = g.next()) {
              var n = t2(m.value);
              m = n.next().value;
              n = n.next().value;
              (m = c.get(m)) && cw(a.j, l, m, n);
            }
          }
          c = $x(k2, "LANGUAGE");
          g = $x(k2, "NAME");
          m = $x(k2, "DEFAULT") == "YES";
          h == "audio" ? n = (n = $x(k2, "CHANNELS")) ? parseInt(n.split("/")[0], 10) : null : n = null;
          var q;
          h == "audio" ? (q = $x(k2, "CHANNELS")) ? (q = q.split("/"), q = q.length != 2 ? false : q[1] === "JOC" || q[1].includes("ATMOS")) : q = false : q = false;
          var r2 = $x(k2, "CHARACTERISTICS"), u = $x(k2, "FORCED") == "YES";
          h == "audio" ? k2 = (k2 = $x(k2, "SAMPLE-RATE")) ? parseInt(k2, 10) : null : k2 = null;
          e = wz(a, l, e, b, h, c, m, g, n, null, r2, u, k2, q);
          e.stream && (e.stream.groupId = d2);
          a.K.has(d2) ? a.K.get(d2).push(e) : a.K.set(d2, [e]);
          a.i.set(f, e);
          return e;
        }
        function nz(a, b) {
          var c, d2, e, f, g, h, k2, l, m, n;
          return P(function(q) {
            if (q.g == 1) {
              c = ay(b, "URI");
              d2 = $x(b, "CODECS", "jpeg") || "";
              if (a.i.has(c)) return q.return(a.i.get(c));
              e = $x(b, "LANGUAGE");
              f = $x(b, "NAME");
              g = $x(b, "CHARACTERISTICS");
              h = wz(a, a.H++, [c], d2, "image", e, false, f, null, null, g, false, null, false);
              return (k2 = $x(b, "RESOLUTION")) ? G(q, h.stream.createSegmentIndex(), 3) : q.B(2);
            }
            q.g != 2 && (l = fg(h.stream.segmentIndex), m = l.tilesLayout) && (h.stream.width = Number(k2.split("x")[0]) * Number(m.split("x")[0]), h.stream.height = Number(k2.split("x")[1]) * Number(m.split("x")[1]));
            if (n = $x(b, "BANDWIDTH")) h.stream.bandwidth = Number(n);
            a.i.set(c, h);
            return q.return(h);
          });
        }
        function oz(a, b) {
          var c = "video", d2 = ay(b, "URI"), e = $x(b, "CODECS") || "";
          e == "mjpg" && (c = "image");
          if (a.i.has(d2)) return a.i.get(d2);
          var f = $x(b, "LANGUAGE"), g = $x(b, "NAME"), h = $x(b, "CHARACTERISTICS");
          c = wz(a, a.H++, [d2], e, c, f, false, g, null, null, h, false, null, false);
          e = $x(b, "RESOLUTION");
          f = t2(e ? e.split("x") : [null, null]);
          e = f.next().value;
          f = f.next().value;
          c.stream.width = Number(e) || void 0;
          c.stream.height = Number(f) || void 0;
          if (b = $x(b, "BANDWIDTH")) c.stream.bandwidth = Number(b);
          a.i.set(d2, c);
          return c;
        }
        function uz(a, b, c, d2) {
          for (var e = a.H++, f = [], g = t2(b), h = g.next(); !h.done; h = g.next()) {
            var k2 = h.value;
            h = ay(k2, "URI");
            k2 = $x(k2, "PATHWAY-ID");
            a.j && k2 && cw(a.j, e, k2, h);
            f.push(h);
          }
          g = f.sort().join(",") + c.sort().join(",");
          if (a.i.has(g)) return a.i.get(g);
          h = f.join(",");
          a: {
            b = $x(b[0], "CLOSED-CAPTIONS");
            if (d2 == "video") {
              if (a.g.disableText) {
                a.O = false;
                b = null;
                break a;
              }
              if (b) {
                if (b != "NONE") {
                  b = a.I.get(b);
                  break a;
                }
                a.O = false;
              } else if (!b && a.I.size) for (b = t2(a.I.keys()), b = b.next(); !b.done; b = b.next()) {
                b = a.I.get(b.value);
                break a;
              }
            }
            b = null;
          }
          c = qc(d2, c);
          d2 = wz(a, e, f, c, d2, null, false, h, null, b, null, false, null, false);
          a.i.set(g, d2);
          return d2;
        }
        function wz(a, b, c, d2, e, f, g, h, k2, l, m, n, q, r2) {
          function u(C) {
            var D, F, B, E, I, J, K, L, M, N, O, Q, R, V, Ba, aa, Oa, La, Ja, Ea;
            return P(function(ya) {
              switch (ya.g) {
                case 1:
                  return D = vc, sa(ya, 2), G(ya, C.promise, 4);
                case 4:
                  F = ya.h;
                  if (C.aborted) return ya.return();
                  B = F.uri;
                  B != F.originalUri && (E = y.T(), E.includes(B) || y.Zf.push(B));
                  I = ly(a.hb, F.data);
                  if (I.type != 1) throw new U(2, 4, 4017);
                  J = dy(I.ma, "EXT-X-DEFINE");
                  K = Fy(a, J, B);
                  L = false;
                  (!a.Z && a.g.hls.disableCodecGuessing || a.O && e == D.Ja && !a.g.hls.disableClosedCaptionsDetection) && I.segments.length > 0 && (a.O = false, L = true);
                  M = !a.Z && a.g.hls.disableCodecGuessing;
                  N = yy(a);
                  return G(ya, Py(a, 0, K, I, w, d2, e, f, g, h, k2, l, m, n, q, r2, void 0, L, M), 5);
                case 5:
                  O = ya.h;
                  if (C.aborted) return ya.return();
                  Q = O.stream;
                  Zy(a, I);
                  yy(a) && !N && $y(a, I);
                  y.md = O.md;
                  y.zc = O.zc;
                  y.kf = O.kf;
                  y.jf = O.jf;
                  y.me = O.me;
                  y.Jf = O.Jf;
                  y.Yb = O.Yb;
                  y.Zb = O.Zb;
                  v.segmentIndex = Q.segmentIndex;
                  v.encrypted = Q.encrypted;
                  v.drmInfos = Q.drmInfos;
                  v.keyIds = Q.keyIds;
                  v.mimeType = Q.mimeType;
                  v.bandwidth = v.bandwidth || Q.bandwidth;
                  v.codecs = v.codecs || Q.codecs;
                  v.closedCaptions = v.closedCaptions || Q.closedCaptions;
                  v.width = v.width || Q.width;
                  v.height = v.height || Q.height;
                  v.hdr = v.hdr || Q.hdr;
                  v.colorGamut = v.colorGamut || Q.colorGamut;
                  v.frameRate = v.frameRate || Q.frameRate;
                  v.language == "und" && Q.language != "und" && (v.language = Q.language);
                  v.language = v.language || Q.language;
                  v.channelsCount = v.channelsCount || Q.channelsCount;
                  v.audioSamplingRate = v.audioSamplingRate || Q.audioSamplingRate;
                  mz(v);
                  v.drmInfos.length && a.h.newDrmInfo(v);
                  R = false;
                  if (!l && v.closedCaptions || l && v.closedCaptions && l.size != v.closedCaptions.size) R = true;
                  a.m && R && a.h.makeTextStreamsForClosedCaptions(a.m);
                  e == D.ab && (V = fg(Q.segmentIndex)) && V.ha && (v.mimeType = "application/mp4", mz(v));
                  Ba = nm(v);
                  v.segmentIndex.Kb(function(Fa) {
                    Fa.ha && (Fa.ha.Kd = Ba);
                  });
                  xz(a) && (a.Ec ? az(a, [y]) : (a.Ec = true, aa = Array.from(a.i.values()), Oa = aa.filter(function(Fa) {
                    return Fa.stream.segmentIndex;
                  }), az(a, Oa), Dy(a), La = a.u, La > 0 && a.F.Y(La)));
                  Ky(a, I.ma, v.type, K, w);
                  a.m && (a.m.startTime = a.A);
                  ua(ya, 0);
                  break;
                case 2:
                  Ja = va(ya);
                  v.closeSegmentIndex();
                  if (Ja.code === 7001) return ya.return();
                  Ea = a.h.disableStream(v);
                  if (!Ea) throw Ja;
                  H(ya);
              }
            });
          }
          function w() {
            return a.j && c.length > 1 ? dw(a.j, b) : y.Zf.concat(iy([a.G], c, a.C));
          }
          var v = Mz(a, d2, e, f, g, h, k2, l, m, n, q, r2);
          c.includes("shaka://hls-muxed") && (v.isAudioMuxedInVideo = true, v.mimeType = "video/mp2t", mz(v));
          var y = {
            stream: v,
            type: e,
            Zf: [],
            md: 0,
            zc: 0,
            Jf: /* @__PURE__ */ new Map(),
            kf: false,
            jf: false,
            me: false,
            Wg: -1,
            Yb: -1,
            Zb: -1,
            T: w
          }, z = null, A;
          v.createSegmentIndex = function() {
            if (z) return z;
            if (v.isAudioMuxedInVideo) return v.segmentIndex = new Zl([]), Promise.resolve();
            A = wy(a, y.T(), true);
            return z = new Promise(function(C) {
              C(u(A));
            });
          };
          v.closeSegmentIndex = function() {
            z && !v.segmentIndex && A.abort();
            v.segmentIndex && (v.segmentIndex.release(), v.segmentIndex = null);
            z = null;
          };
          return y;
        }
        function hz(a) {
          var b = Infinity;
          a = t2(a.i.values());
          for (var c = a.next(); !c.done; c = a.next()) c = c.value, c.stream.segmentIndex && c.stream.type != "text" && !c.stream.isAudioMuxedInVideo && (b = Math.min(b, c.zc));
          return b;
        }
        function Ay(a, b) {
          var c = [];
          b = t2(b);
          for (var d2 = b.next(); !d2.done; d2 = b.next()) d2 = d2.value, d2.segmentIndex && d2.segmentIndex.Kb(function(e) {
            c.push(e);
          });
          a.l.ye(c);
        }
        function az(a, b) {
          if (!yy(a)) for (var c = hz(a), d2 = t2(b), e = d2.next(); !e.done; e = d2.next()) e.value.stream.segmentIndex.Ed(0, c);
          Ay(a, b.map(function(f) {
            return f.stream;
          }));
          d2 = Array.from(a.i.values()).filter(function(f) {
            return f.stream.segmentIndex;
          });
          c = d2.some(function(f) {
            return f.stream.type == "audio";
          });
          e = d2.some(function(f) {
            return f.stream.type == "video";
          });
          d2 = yy(a) && !a.Va;
          c = !yy(a) && a.Va && !(c && e);
          a.g.hls.ignoreManifestProgramDateTime || d2 || c ? Ly(a, b, d2) : (Oy(a, b), a.g.hls.ignoreManifestProgramDateTimeForTypes.length > 0 && Ly(a, b));
        }
        function My(a, b) {
          return a.g.hls.ignoreManifestProgramDateTime ? true : a.g.hls.ignoreManifestProgramDateTimeForTypes.includes(b);
        }
        function xz(a) {
          if (!a.m) return false;
          var b = [], c = [];
          a = t2(a.m.variants);
          for (var d2 = a.next(); !d2.done; d2 = a.next()) d2 = d2.value, d2.video && b.push(d2.video), d2.audio && c.push(d2.audio);
          return b.length > 0 && !b.some(function(e) {
            return e.segmentIndex;
          }) || c.length > 0 && !c.some(function(e) {
            return e.segmentIndex;
          }) ? false : true;
        }
        function Py(a, b, c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z) {
          y = y === void 0 ? true : y;
          z = z === void 0 ? true : z;
          var A, C, D, F, B, E, I, J, K, L, M, N, O, Q, R, V, Ba, aa, Oa, La, Ja, Ea, ya, Fa, Da, za, Ca, fb, hb;
          return P(function(ib) {
            switch (ib.g) {
              case 1:
                A = d2.segments || [];
                C = A.every(function(xb) {
                  return fy(xb.ma, "EXT-X-GAP") ? true : false;
                });
                if (!A.length || C) throw new U(2, 4, 4053);
                Nz(a, d2);
                yy(a) && Jy(a, d2);
                D = yy(a) ? a.D.get(g) : /* @__PURE__ */ new Map();
                F = Hy(a, d2, D, c, e, g);
                B = F.segments;
                E = F.bandwidth;
                M = L = K = J = I = null;
                if (!(B.length > 0 && y)) {
                  ib.B(2);
                  break;
                }
                return G(ib, bz(a, B), 3);
              case 3:
                N = ib.h, g != N.type && yy(a) && (a.D.set(N.type, a.D.get(g)), a.D.set(g, /* @__PURE__ */ new Map())), g = N.type, h = N.language, m = N.channelCount, u = N.sampleRate, a.g.disableText || (n = N.closedCaptions), J = N.height, I = N.width, K = N.Ke, L = N.colorGamut, M = N.frameRate, z && (v = N.mimeType, f = N.codecs);
              case 2:
                if (v) {
                  ib.B(4);
                  break;
                }
                return G(ib, Oz(a, g, f, B), 5);
              case 5:
                v = ib.h, g != tc || f || v != "application/mp4" || !B[0] || B[0].ha || (v = "text/vtt");
              case 4:
                return G(ib, Gy(a, d2, v, e, c), 6);
              case 6:
                O = ib.h;
                Q = O.drmInfos;
                R = O.keyIds;
                V = O.encrypted;
                Ba = O.Fi;
                if (V && !Q.length && !Ba) throw new U(2, 4, 4026);
                aa = Mz(a, f, g, h, k2, l, m, n, q, r2, u, w);
                aa.encrypted = V && !Ba;
                aa.drmInfos = Q;
                aa.keyIds = R;
                aa.mimeType = v;
                E && (aa.bandwidth = E);
                mz(aa);
                g == "video" && (I || J || K || L) && vz(aa, I, J, M, K, null, L);
                yy(a) && Jy(a, d2);
                Oa = B[0].startTime;
                La = B[B.length - 1];
                Ja = La.endTime;
                Ea = new Zl(B);
                aa.segmentIndex = Ea;
                Fa = (ya = fy(d2.ma, "EXT-X-SERVER-CONTROL")) ? Zx(ya, "CAN-SKIP-UNTIL") != null : false;
                Da = ya ? Zx(ya, "CAN-BLOCK-RELOAD") != null : false;
                za = gy(d2.ma, "EXT-X-MEDIA-SEQUENCE", 0);
                Ca = Iy(za, B);
                fb = Ca.Yb;
                hb = Ca.Zb;
                return ib.return({
                  stream: aa,
                  type: g,
                  Zf: [],
                  T: e,
                  md: Oa,
                  zc: Ja,
                  kf: Fa,
                  jf: Da,
                  me: false,
                  Wg: -1,
                  Yb: fb,
                  Zb: hb,
                  Jf: D
                });
            }
          });
        }
        function Iy(a, b) {
          a = a + b.length - 1;
          var c = -1;
          if (!b.length) return a++, {
            Yb: a,
            Zb: c
          };
          b = b[b.length - 1];
          var d2 = b.g;
          if (!b.g.length) return a++, b.m && (c = 0), {
            Yb: a,
            Zb: c
          };
          c = d2.length - 1;
          d2[d2.length - 1].isPreload() || (a++, c = 0);
          return {
            Yb: a,
            Zb: c
          };
        }
        function Mz(a, b, c, d2, e, f, g, h, k2, l, m, n) {
          var q = kz(c, b) || lz(c), r2 = [];
          if (k2) {
            k2 = t2(k2.split(","));
            for (var u = k2.next(); !u.done; u = k2.next()) r2.push(u.value);
          }
          k2 = void 0;
          u = null;
          c == tc ? k2 = r2.includes("public.accessibility.transcribes-spoken-dialog") && r2.includes("public.accessibility.describes-music-and-sound") ? "caption" : "subtitle" : r2.includes("public.accessibility.describes-video") && (u = "visually impaired");
          r2.length || k2 !== "subtitle" || r2.push("subtitle");
          a = {
            id: a.H++,
            originalId: f,
            groupId: null,
            createSegmentIndex: function() {
              return Promise.resolve();
            },
            segmentIndex: null,
            mimeType: q,
            codecs: b,
            kind: c == tc ? "subtitle" : void 0,
            encrypted: false,
            drmInfos: [],
            keyIds: /* @__PURE__ */ new Set(),
            language: zc(d2 || "und"),
            originalLanguage: d2,
            label: f,
            type: c,
            primary: e,
            trickModeVideo: null,
            dependencyStream: null,
            emsgSchemeIdUris: null,
            frameRate: void 0,
            pixelAspectRatio: void 0,
            width: void 0,
            height: void 0,
            bandwidth: void 0,
            roles: r2,
            forced: l,
            channelsCount: g,
            audioSamplingRate: m,
            spatialAudio: n,
            closedCaptions: h,
            hdr: void 0,
            colorGamut: void 0,
            videoLayout: void 0,
            tilesLayout: void 0,
            accessibilityPurpose: u,
            external: false,
            fastSwitching: false,
            fullMimeTypes: /* @__PURE__ */ new Set(),
            isAudioMuxedInVideo: false,
            baseOriginalId: null
          };
          mz(a);
          return a;
        }
        function Gy(a, b, c, d2, e) {
          var f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N, O, Q, R;
          return P(function(V) {
            switch (V.g) {
              case 1:
                f = /* @__PURE__ */ new Map();
                if (!a.g.ignoreDrmInfo && b.segments) {
                  for (g = t2(b.segments), h = g.next(); !h.done; h = g.next()) if (k2 = h.value, l = dy(k2.ma, "EXT-X-KEY"), m = null, l.length) for (m = Pz(a, b, k2.ma, d2, e), n = t2(l), q = n.next(); !q.done; q = n.next()) r2 = q.value, f.set(r2, m);
                }
                w = u = false;
                v = [];
                y = /* @__PURE__ */ new Set();
                z = t2(f);
                A = z.next();
              case 2:
                if (A.done) {
                  V.B(4);
                  break;
                }
                C = A.value;
                D = t2(C);
                F = D.next().value;
                B = D.next().value;
                E = F;
                I = B;
                J = ay(E, "METHOD");
                if (J == "NONE") {
                  V.B(3);
                  break;
                }
                u = true;
                K = $x(E, "KEYFORMAT") || "identity";
                L = null;
                if (qz(J)) {
                  w = true;
                  V.B(3);
                  break;
                }
                if (K == "identity") return G(V, rz(a, E, c, d2, I, e), 11);
                M = a.jc.get(K);
                if (!M) {
                  N = null;
                  V.B(9);
                  break;
                }
                return G(V, M(E, c, I), 10);
              case 10:
                N = V.h;
              case 9:
                L = N;
                V.B(6);
                break;
              case 11:
                L = V.h;
              case 6:
                if (L) {
                  if (L.keyIds) for (O = t2(L.keyIds), Q = O.next(); !Q.done; Q = O.next()) R = Q.value, y.add(R);
                  v.push(L);
                }
              case 3:
                A = z.next();
                V.B(2);
                break;
              case 4:
                return V.return({
                  drmInfos: v,
                  keyIds: y,
                  encrypted: u,
                  Fi: w
                });
            }
          });
        }
        function Qz(a, b, c, d2, e) {
          if (!window7.crypto || !window7.crypto.subtle) throw bb("Web Crypto API is not available to decrypt AES. (Web Crypto only exists in secure origins like https)"), new U(2, 4, 4042);
          var f = 0, g = $x(b, "IV", "");
          if (g) {
            var h = kc(g.substr(2));
            if (h.byteLength != 16) throw new U(2, 4, 4048);
          } else f = gy(c.ma, "EXT-X-MEDIA-SEQUENCE", 0);
          var k2 = hy(d2(), ay(b, "URI"), e), l = k2.sort().join("");
          c = b.toString() + "-" + f + "-" + l;
          if (!a.ea.has(c)) {
            var m = {
              bitsKey: 128,
              blockCipherMode: "CBC",
              iv: h,
              firstMediaSequenceNumber: f
            };
            switch (ay(b, "METHOD")) {
              case "AES-256":
                m.bitsKey = 256;
                break;
              case "AES-256-CTR":
                m.bitsKey = 256, m.blockCipherMode = "CTR";
            }
            m.fetchKey = function() {
              var n, q, r2, u;
              return P(function(w) {
                if (w.g == 1) return a.M.has(l) || (n = ah(k2, a.g.retryParameters), q = fz(a, n, 6).promise, a.M.set(l, q)), G(w, a.M.get(l), 2);
                if (w.g != 3) {
                  r2 = w.h;
                  if (!r2.data || r2.data.byteLength != m.bitsKey / 8) throw new U(2, 4, 4049);
                  u = {
                    name: m.blockCipherMode == "CTR" ? "AES-CTR" : "AES-CBC",
                    length: m.bitsKey
                  };
                  return G(w, window7.crypto.subtle.importKey("raw", r2.data, u, true, ["decrypt"]), 3);
                }
                m.cryptoKey = w.h;
                m.fetchKey = void 0;
                H(w);
              });
            };
            a.ea.set(c, m);
          }
          return a.ea.get(c);
        }
        function Zy(a, b) {
          a.A == null && (b = fy(b.ma, "EXT-X-START")) && (a.A = Number(ay(b, "TIME-OFFSET")));
        }
        function Nz(a, b) {
          var c = fy(b.ma, "EXT-X-PLAYLIST-TYPE");
          b = fy(b.ma, "EXT-X-ENDLIST");
          b = c && c.value == "VOD" || b;
          c = c && c.value == "EVENT" && !b;
          c = !b && !c;
          b ? Cy(a, vy) : c ? Cy(a, gz) : Cy(a, Rz);
        }
        function Jy(a, b) {
          var c = Infinity, d2 = b.segments;
          if (d2.length) for (var e = d2.length - 1; e >= 0; ) {
            var f = fy(d2[e].ma, "EXTINF");
            if (f) {
              c = Number(f.value.split(",")[0]);
              break;
            }
            e--;
          }
          d2 = fy(b.ma, "EXT-X-TARGETDURATION");
          if (!d2) throw new U(2, 4, 4024, "EXT-X-TARGETDURATION");
          d2 = Number(d2.value);
          if (e = fy(b.ma, "EXT-X-PART-INF")) a.P = Number(ay(e, "PART-TARGET"));
          b = fy(b.ma, "EXT-X-SERVER-CONTROL");
          a.aa && a.P ? (a.u = a.kc ? a.P * 5 <= c ? Math.min(a.P, a.u) : Math.min(c, a.u) : Math.min(a.P, a.u), a.Ma = b ? Number(ay(b, "PART-HOLD-BACK")) : 0) : (a.u = Math.min(c, a.u), c = b ? Zx(b, "HOLD-BACK") : null, a.Ia = c ? Number(c.value) : 0);
          a.Oa = Math.max(d2, a.Oa);
        }
        function $y(a, b) {
          var c = 0;
          if (a.g.defaultPresentationDelay) c = a.g.defaultPresentationDelay;
          else if (a.Ma) c = a.Ma;
          else if (a.Ia) c = a.Ia;
          else for (var d2 = b.segments.length, e = d2 - Math.min(d2, a.g.hls.liveSegmentsDelay); e < d2; e++) {
            var f = fy(b.segments[e].ma, "EXTINF");
            c = f ? c + Number(f.value.split(",")[0]) : c + a.Oa;
          }
          a.A && a.A < 0 && (c = Math.min(-a.A, c), a.A += c);
          a.l.Nj(0);
          a.l.ci(c);
          a.l.rd(false);
        }
        function Pz(a, b, c, d2, e) {
          var f = fy(c, "EXT-X-MAP");
          if (!f) return null;
          var g = ay(f, "URI"), h = hy(d2(), g, e);
          g = [h.toString(), $x(f, "BYTERANGE", "")].join("-");
          if (!a.ua.has(g)) {
            var k2 = void 0, l = null, m = false;
            c = t2(c);
            for (var n = c.next(); !n.done; n = c.next()) n = n.value, n.name == "EXT-X-KEY" ? (m = ay(n, "METHOD"), qz(m) && n.id < f.id ? (m = false, k2 = Qz(a, n, b, d2, e)) : m = m != "NONE") : n.name == "EXT-X-BYTERANGE" && n.id < f.id && (l = n);
            b = Sz(h, f, l, k2, m);
            a.ua.set(g, b);
          }
          return a.ua.get(g);
        }
        function Sz(a, b, c, d2, e) {
          var f = 0, g = null;
          b = $x(b, "BYTERANGE");
          !b && c && (b = c.value);
          b && (f = b.split("@"), g = Number(f[0]), f = Number(f[1]), g = f + g - 1, d2 && (c = g + 1 - f, c % 16 && (g += 16 - c % 16)));
          return new Aj(function() {
            return a;
          }, f, g, null, null, null, d2, e);
        }
        function Tz(a, b, c, d2, e, f, g, h, k2) {
          function l(V) {
            V = new rb(V).xb.split(".").pop();
            var Ba = Uz.get(g).get(V);
            Ba || (Ba = dz.get(V));
            return Ba;
          }
          var m = d2.ma, n = fy(m, "EXTINF"), q = 0, r2 = 0, u = null;
          d2.Cc.length && (a.m.isLowLatency = true);
          var w = null;
          if (!a.g.hls.ignoreManifestProgramDateTime) {
            var v = fy(m, "EXT-X-PROGRAM-DATE-TIME");
            v && v.value && (w = ce(v.value), a.Va = true);
          }
          var y = Dj;
          fy(m, "EXT-X-GAP") && (a.m.gapCount++, y = 2);
          if (!n) {
            if (d2.Cc.length == 0) throw new U(2, 4, 4024, "EXTINF");
            if (!a.aa) return null;
          }
          var z = [];
          v = false;
          var A = null, C = false, D = false;
          if (a.aa && d2.Cc.length) {
            q = b && window7.ReadableStream && a.g.hls.allowLowLatencyByteRangeOptimization;
            for (var F = w, B = {}, E = 0; E < d2.Cc.length; B = {
              sg: void 0,
              Sf: void 0
            }, E++) {
              var I = d2.Cc[E], J = E == 0 ? c : z[z.length - 1], K = E == 0 ? e : J.endTime, L = Number($x(I, "DURATION")) || a.P;
              if (L) {
                var M = K + L, N = 0, O = null;
                I.name == "EXT-X-PRELOAD-HINT" ? (N = (N = $x(I, "BYTERANGE-START")) ? Number(N) : 0, (J = $x(I, "BYTERANGE-LENGTH")) ? O = N + Number(J) - 1 : N && (O = Number.MAX_SAFE_INTEGER)) : (N = $x(I, "BYTERANGE"), O = t2(Vz(J, N)), N = O.next().value, O = O.next().value);
                B.Sf = $x(I, "URI");
                if (B.Sf) {
                  J = Dj;
                  $x(I, "GAP") == "YES" && (a.m.gapCount++, J = 2, C = true);
                  B.sg = null;
                  var Q = /* @__PURE__ */ function(V) {
                    return function() {
                      V.sg == null && (V.sg = hy(h(), V.Sf, f));
                      return V.sg;
                    };
                  }(B);
                  q && N >= 0 && O != null && (A = Q, v = true);
                  K = new Cj(K, M, Q, N, O, b, 0, 0, Infinity, [], "", null, F, J, k2);
                  I.name == "EXT-X-PRELOAD-HINT" && (K.Jh(), D = true);
                  $x(I, "INDEPENDENT") != "YES" && E > 0 && K.Jd();
                  if (B = l(B.Sf)) K.mimeType = B, Wz.has(B) && (K.ha = null);
                  z.push(K);
                  F && (F += L);
                }
              }
            }
          }
          if (n) {
            n = Number(n.value.split(",")[0]);
            if (n == 0) return null;
            q = e + n;
          } else if (z.length) q = z[z.length - 1].endTime;
          else return null;
          v && (C || z[0].startByte != 0 ? (v = false, A = null) : z = []);
          (n = fy(m, "EXT-X-BYTERANGE")) ? (u = t2(Vz(c, n.value)), r2 = u.next().value, u = u.next().value) : z.length && (r2 = z[0].startByte, u = z[z.length - 1].endByte);
          c = "";
          n = null;
          g == "image" && (c = "1x1", m = fy(m, "EXT-X-TILES")) && (c = ay(m, "LAYOUT"), (m = $x(m, "DURATION")) && (n = Number(m)));
          var R = null;
          b = new Cj(e, q, function() {
            if (A) return A();
            R == null && (R = hy(h(), d2.g, f));
            return R || [];
          }, r2, u, b, 0, 0, Infinity, z, c, n, w, y, k2, z.length > 0 && !!d2.g);
          if (e = l(d2.g)) b.mimeType = e, Wz.has(e) && (b.ha = null);
          v && (a.kc = true, b.jj(), D && b.Jh());
          return b;
        }
        function Vz(a, b) {
          var c = 0, d2 = null;
          b && (c = b.split("@"), b = Number(c[0]), c = c[1] ? Number(c[1]) : a.endByte + 1, d2 = c + b - 1);
          return [c, d2];
        }
        function Ky(a, b, c, d2, e) {
          if (c == "video" || c == "audio") {
            var f = a.l.m;
            if (f && !My(a, c)) for (b = dy(b, "EXT-X-DATERANGE"), b = b.filter(function(J) {
              return Zx(J, "START-DATE") != null;
            }).sort(function(J, K) {
              J = ay(J, "START-DATE");
              K = ay(K, "START-DATE");
              return J < K ? -1 : J > K ? 1 : 0;
            }), c = 0; c < b.length; c++) {
              var g = b[c];
              try {
                var h = ay(g, "START-DATE"), k2 = ce(h);
                if (!isNaN(k2)) {
                  var l = Math.max(0, k2 - f), m = null, n = $x(g, "END-DATE");
                  if (n) {
                    var q = ce(n);
                    if (!isNaN(q) && (m = q - f, m < 0)) continue;
                  }
                  if (m == null) {
                    var r2 = $x(g, "DURATION") || $x(g, "PLANNED-DURATION");
                    if (r2) {
                      var u = parseFloat(r2);
                      isNaN(u) || (m = l + u);
                      if (k2 - f + u < 0) continue;
                    }
                  }
                  var w = $x(g, "CLASS") || "com.apple.quicktime.HLS", v = $x(g, "END-ON-NEXT") == "YES";
                  if (m == null && v) {
                    for (var y = c + 1; y < b.length; y++) {
                      var z = $x(b[y], "CLASS") || "com.apple.quicktime.HLS";
                      if (w == z) {
                        var A = ay(b[y], "START-DATE"), C = ce(A);
                        if (!isNaN(C) && C && C > k2) {
                          m = Math.max(0, C - f);
                          break;
                        }
                      }
                    }
                    if (m == null) continue;
                  }
                  y = ["CLASS", "START-DATE", "END-DATE", "DURATION", "END-ON-NEXT"];
                  for (var D = [], F = t2(g.attributes), B = F.next(); !B.done; B = F.next()) {
                    var E = B.value;
                    if (!y.includes(E.name)) {
                      var I = jy(E.value, d2);
                      if (E.name == "X-ASSET-URI" || E.name == "X-ASSET-LIST") I = hy(e(), E.value, d2)[0];
                      D.push({
                        key: E.name,
                        description: "",
                        data: I,
                        mimeType: null,
                        pictureType: null
                      });
                    }
                  }
                  if (D.length > 1) a.h.onMetadata(w, l, m, D);
                }
              } catch (J) {
              }
            }
          }
        }
        function Hy(a, b, c, d2, e, f) {
          var g = b.segments, h = void 0, k2 = gy(b.ma, "EXT-X-DISCONTINUITY-SEQUENCE", -1), l = gy(b.ma, "EXT-X-MEDIA-SEQUENCE", 0), m = fy(b.ma, "EXT-X-SKIP"), n = m ? Number($x(m, "SKIPPED-SEGMENTS")) : 0, q = l + n, r2 = 0;
          yy(a) && c.has(q) && (r2 = c.get(q));
          r2 === 0 && a.va == gz && c.size > 0 && !c.has(q) && a.l.i != null && (r2 = a.l.Nb());
          var u = [], w = null;
          m = [];
          for (var v = 0; v < g.length; v++) {
            var y = g[v], z = v == 0 ? r2 : w.endTime;
            q = l + n + v;
            fy(y.ma, "EXT-X-DISCONTINUITY") && (k2++, w && w.ha && (w.ha.g = z));
            var A = t2(y.ma);
            for (var C = A.next(); !C.done; C = A.next()) C = C.value, C.name == "EXT-X-KEY" && (qz(ay(C, "METHOD")) ? h = Qz(a, C, b, e, d2) : h = void 0);
            c.set(q, z);
            A = Pz(a, b, y.ma, e, d2);
            if (z = Tz(a, A, w, y, z, d2, f, e, h)) (w = gy(y.ma, "EXT-X-BITRATE")) ? m.push({
              bitrate: w,
              duration: z.endTime - z.startTime
            }) : m.length && (w = m.pop(), w.duration += z.endTime - z.startTime, m.push(w)), w = z, z.i = k2, My(a, f) && a.L != null && q < a.L || u.push(z);
          }
          b = void 0;
          m.length && (b = m.reduce(function(D, F) {
            return D + F.duration;
          }, 0), b = Math.round(m.reduce(function(D, F) {
            return D + F.bitrate * F.duration;
          }, 0) / b * 1e3));
          if (m = u.some(function(D) {
            return D.h != null;
          })) {
            for (c = {}, d2 = 0; d2 < u.length; c = {
              qf: void 0,
              pf: void 0,
              ef: void 0,
              od: void 0,
              df: void 0
            }, d2++) if (c.od = u[d2], c.od.h == null) for (c.pf = 0, c.qf = d2, e = /* @__PURE__ */ function(D) {
              return function() {
                var F = u[D.qf];
                if (F) {
                  if (F.h != null) return F.h + D.pf;
                  D.pf -= F.endTime - F.startTime;
                  D.qf += 1;
                }
                return null;
              };
            }(c), c.df = 0, c.ef = d2, g = /* @__PURE__ */ function(D) {
              return function() {
                var F = u[D.ef];
                if (F) {
                  F != D.od && (D.df += F.endTime - F.startTime);
                  if (F.h != null) return F.h + D.df;
                  --D.ef;
                }
                return null;
              };
            }(c); c.od.h == null; ) c.od.h = g(), c.od.h == null && (c.od.h = e());
          }
          if (m) for (c = t2(u), d2 = c.next(); !d2.done; d2 = c.next()) for (e = d2.value, d2 = e.h, e = t2(e.g), g = e.next(); !g.done; g = e.next()) g = g.value, g.h = d2, d2 += g.endTime - g.startTime;
          c = a.$;
          if (m && c != Infinity && !My(a, f)) for (a = t2(u), f = a.next(); !f.done; f = a.next()) f.value.pi(c);
          return {
            segments: u,
            bandwidth: b
          };
        }
        function kz(a, b) {
          if (a == tc) {
            if (b == "vtt" || b == "wvtt") return "text/vtt";
            if (b && b !== "") return "application/mp4";
          }
          return a != "image" || b && b != "jpeg" ? a == "audio" && b == "mp4a.40.34" ? "audio/mpeg" : b == "mjpg" ? "application/mp4" : null : "image/jpeg";
        }
        function lz(a) {
          return a == tc ? "text/vtt" : Uz.get(a).get("mp4");
        }
        function cz(a, b) {
          a = yy(a) ? Math.trunc((b.length - 1) / 2) : 0;
          for (var c = b[a]; c.Oc() == 2 && a + 1 < b.length; ) a++, c = b[a];
          return {
            segment: c,
            segmentIndex: a
          };
        }
        function Oz(a, b, c, d2) {
          var e, f, g, h, k2, l, m, n, q, r2, u, w, v;
          return P(function(y) {
            switch (y.g) {
              case 1:
                e = gh;
                f = cz(a, d2);
                g = f.segment;
                if (g.status == 2) return y.return(lz(b));
                h = g.T();
                k2 = new rb(h[0]);
                l = k2.xb.split(".").pop();
                m = Uz.get(b);
                if ((n = m.get(l)) || (n = dz.get(l)) || (n = kz(b, c))) return y.return(n);
                r2 = 1;
                u = ah(h, a.g.retryParameters);
                sa(y, 2);
                u.method = "HEAD";
                return G(y, fz(a, u, e, {
                  type: r2
                }).promise, 4);
              case 4:
                w = y.h;
                q = w.headers["content-type"];
                ua(y, 3);
                break;
              case 2:
                v = va(y);
                if (!v || v.code != 1002 && v.code != 1001) {
                  y.B(3);
                  break;
                }
                u.method = "GET";
                a.g.hls.allowRangeRequestsToGuessMimeType && (u.headers.Range = "bytes=0-0");
                return G(y, fz(a, u, e, {
                  type: r2
                }).promise, 6);
              case 6:
                w = y.h, q = w.headers["content-type"];
              case 3:
                if (!q) {
                  y.B(7);
                  break;
                }
                n = q.toLowerCase().split(";")[0];
                if (n != "application/octet-stream") {
                  y.B(8);
                  break;
                }
                if (w.data.byteLength) {
                  y.B(9);
                  break;
                }
                u.method = "GET";
                return G(y, fz(a, u, e, {
                  type: r2
                }).promise, 10);
              case 10:
                w = y.h;
              case 9:
                xk(Lb(w.data)) && (n = "video/mp2t");
              case 8:
                if (n != "application/octet-stream") return y.return(n);
              case 7:
                return y.return(lz(b));
            }
          });
        }
        function vz(a, b, c, d2, e, f, g) {
          a && (a.width = Number(b) || void 0, a.height = Number(c) || void 0, a.frameRate = Number(d2) || void 0, a.hdr = e || void 0, a.videoLayout = f || void 0, a.colorGamut = g || void 0);
        }
        function wy(a, b, c) {
          return fz(a, ah(b, a.g.retryParameters), 0, {
            type: c ? 2 : 3
          });
        }
        function uy(a) {
          var b, c, d2, e, f, g;
          return P(function(h) {
            switch (h.g) {
              case 1:
                if (!a.h) return h.return();
                sa(h, 2);
                b = Date.now();
                return G(h, a.update(), 4);
              case 4:
                c = Date.now();
                yy(a) && (d2 = (c - b) / 1e3, a.fb.sample(1, d2), e = a.g.updatePeriod > 0 ? a.g.updatePeriod : a.u, f = Math.max(0, e - Oc(a.fb)), a.F.Y(f));
                ua(h, 3);
                break;
              case 2:
                g = va(h);
                if (!a.h) return h.return();
                if (a.g.raiseFatalErrorOnManifestUpdateRequestFailure) return a.h.onError(g), h.return();
                g.severity = 1;
                a.h.onError(g);
                a.F.Y(0.1);
              case 3:
                if (!a.h) return h.return();
                a.h.onManifestUpdated();
                H(h);
            }
          });
        }
        function yy(a) {
          return a.va != vy;
        }
        function Cy(a, b) {
          a.va = b;
          a.l && a.l.rd(!yy(a));
          yy(a) || a.F.stop();
        }
        function fz(a, b, c, d2) {
          if (!a.V) throw new U(2, 7, 7001);
          d2 || (d2 = {});
          d2.isPreload = a.Ob();
          b = a.h.networkingEngine.request(c, b, d2);
          Vg(a.V, b);
          return b;
        }
        function qz(a) {
          return a == "AES-128" || a == "AES-256" || a == "AES-256-CTR";
        }
        function ty(a, b, c, d2) {
          var e, f, g, h, k2, l;
          return P(function(m) {
            if (m.g == 1) {
              if (c == "video/mp2t") throw new U(2, 4, 4040);
              if ("apple" === window7.shakaMediaKeysPolyfill) throw new U(2, 4, 4041);
              e = ay(b, "METHOD");
              f = ["SAMPLE-AES", "SAMPLE-AES-CTR"];
              if (!f.includes(e)) return m.return(null);
              g = "cenc";
              e == "SAMPLE-AES" && (g = "cbcs");
              h = ay(b, "URI");
              k2 = oc("com.apple.fps", g, [{
                initDataType: "sinf",
                initData: new Uint8Array(0),
                keyId: null
              }], h);
              var n = new rb(h).Ib.replace(/-/g, "").toLowerCase();
              return (l = n.length === 32 && /^[0-9a-f]+$/.test(n) ? n : null) || !d2 ? m.B(2) : G(m, Xz(a, d2), 3);
            }
            m.g != 2 && (l = m.h);
            l && k2.keyIds.add(l);
            return m.return(k2);
          });
        }
        function rz(a, b, c, d2, e, f) {
          var g, h, k2, l, m, n, q, r2, u, w, v, y;
          return P(function(z) {
            switch (z.g) {
              case 1:
                if (c == "video/mp2t") throw new U(2, 4, 4040);
                if ("apple" === window7.shakaMediaKeysPolyfill) throw new U(2, 4, 4041);
                g = ay(b, "METHOD");
                h = ["SAMPLE-AES", "SAMPLE-AES-CTR"];
                if (!h.includes(g)) return z.return(null);
                k2 = hy(d2(), ay(b, "URI"), f);
                if (k2[0].startsWith("data:text/plain;base64,")) {
                  l = lc(jc(k2[0].split("data:text/plain;base64,").pop()));
                  z.B(2);
                  break;
                }
                m = k2.sort().join("");
                a.oa.has(m) || (n = ah(k2, a.g.retryParameters), q = fz(a, n, 6).promise, a.oa.set(m, q));
                return G(z, a.oa.get(m), 3);
              case 3:
                r2 = z.h, l = lc(r2.data);
              case 2:
                u = "00000000000000000000000000000000";
                if (!e) {
                  z.B(4);
                  break;
                }
                return G(z, Xz(a, e), 5);
              case 5:
                (w = z.h) && (u = w);
              case 4:
                return v = /* @__PURE__ */ new Map(), v.set(u, l), y = "cenc", g == "SAMPLE-AES" && (y = "cbcs"), z.return(pc(v, y));
            }
          });
        }
        function Xz(a, b) {
          var c, d2, e, f;
          return P(function(g) {
            if (g.g == 1) {
              c = null;
              if (a.sa.has(b)) return c = a.sa.get(b), g.B(2);
              d2 = Jm(b.T(), b.Nc(), b.Lc(), a.g.retryParameters);
              e = gh;
              return G(g, fz(a, d2, e, {
                type: 0
              }).promise, 3);
            }
            g.g != 2 && (f = g.h, b.Ee(f.data), c = Hm(f.data), a.sa.set(b, c));
            return g.return(c);
          });
        }
        S("shaka.hls.HlsParser", sy);
        var dz = (/* @__PURE__ */ new Map()).set("aac", "audio/aac").set("ac3", "audio/ac3").set("ec3", "audio/ec3").set("mp3", "audio/mpeg"), Yz = (/* @__PURE__ */ new Map()).set("mp4", "audio/mp4").set("mp4a", "audio/mp4").set("m4s", "audio/mp4").set("m4i", "audio/mp4").set("m4a", "audio/mp4").set("m4f", "audio/mp4").set("cmfa", "audio/mp4").set("ts", "video/mp2t").set("tsa", "video/mp2t"), Zz = (/* @__PURE__ */ new Map()).set("mp4", "video/mp4").set("mp4v", "video/mp4").set("m4s", "video/mp4").set("m4i", "video/mp4").set("m4v", "video/mp4").set("m4f", "video/mp4").set("cmfv", "video/mp4").set("ts", "video/mp2t").set("tsv", "video/mp2t"), $z = (/* @__PURE__ */ new Map()).set("mp4", "application/mp4").set("m4s", "application/mp4").set("m4i", "application/mp4").set("m4f", "application/mp4").set("cmft", "application/mp4").set("vtt", "text/vtt").set("webvtt", "text/vtt").set("ttml", "application/ttml+xml"), aA = (/* @__PURE__ */ new Map()).set("jpg", "image/jpeg").set("png", "image/png").set("svg", "image/svg+xml").set("webp", "image/webp").set("avif", "image/avif"), Uz = (/* @__PURE__ */ new Map()).set("audio", Yz).set("video", Zz).set("text", $z).set("image", aA), Wz = new Set(["video/mp2t"].concat(x(ff))), vy = "VOD", Rz = "EVENT", gz = "LIVE", By = {
          ik: vy,
          Tm: Rz,
          dn: gz
        };
        Gi("application/x-mpegurl", function() {
          return new sy();
        });
        Gi("application/vnd.apple.mpegurl", function() {
          return new sy();
        });
        function bA(a) {
          return bv(a);
        }
        var cA = (/* @__PURE__ */ new Map()).set("com.microsoft.playready", bA).set("com.microsoft.playready.recommendation", bA).set("com.microsoft.playready.software", bA).set("com.microsoft.playready.hardware", bA);
        function dA() {
          var a = this;
          this.h = this.g = null;
          this.l = [];
          this.j = null;
          this.A = 1;
          this.i = null;
          this.F = new Nc(5);
          this.u = new Cf(function() {
            eA(a);
          });
          this.D = new Ug();
          this.m = /* @__PURE__ */ new Map();
          this.C = function() {
            return false;
          };
        }
        p = dA.prototype;
        p.configure = function(a, b) {
          this.g = a;
          b && (this.C = b);
        };
        p.start = function(a, b) {
          var c = this;
          return P(function(d2) {
            if (d2.g == 1) return c.l = [a], c.h = b, G(d2, fA(c), 2);
            if (!c.h) throw new U(2, 7, 7001);
            return d2.return(c.j);
          });
        };
        function eA(a) {
          var b;
          P(function(c) {
            switch (c.g) {
              case 1:
                return sa(c, 2), G(c, fA(a), 4);
              case 4:
                ua(c, 3);
                break;
              case 2:
                b = va(c), a.h && (b.severity = 1, a.h.onError(b));
              case 3:
                if (!a.h) return c.return();
                H(c);
            }
          });
        }
        p.stop = function() {
          this.g = this.h = null;
          this.l = [];
          this.j = null;
          this.u != null && (this.u.stop(), this.u = null);
          this.m.clear();
          return this.D.destroy();
        };
        p.update = function() {
          var a = this, b;
          return P(function(c) {
            if (c.g == 1) return sa(c, 2), G(c, fA(a), 4);
            if (c.g != 2) return ua(c, 0);
            b = va(c);
            if (!a.h || !b) return c.return();
            a.h.onError(b);
            H(c);
          });
        };
        p.onExpirationUpdated = function() {
        };
        p.onInitialVariantChosen = function() {
        };
        p.banLocation = function() {
        };
        p.setMediaElement = function() {
        };
        function fA(a) {
          var b, c, d2, e, f, g, h;
          return P(function(k2) {
            if (k2.g == 1) return b = ah(a.l, a.g.retryParameters), c = a.h.networkingEngine, d2 = Date.now(), e = c.request(0, b, {
              type: 5,
              isPreload: a.C()
            }), Vg(a.D, e), G(k2, e.promise, 2);
            f = k2.h;
            if (!a.h) return k2.return();
            f.uri && !a.l.includes(f.uri) && a.l.unshift(f.uri);
            var l = f.uri, m = f.data, n = a.g.mss.manifestPreprocessor;
            if (n != Wn) {
              Wc("manifest.mss.manifestPreprocessor configuration", "Please Use manifest.mss.manifestPreprocessorTXml instead.");
              m = Sw(m, "SmoothStreamingMedia");
              if (!m) throw new U(2, 4, 4046, l);
              n(m);
              m = ac(m.outerHTML);
            }
            var q = Kd(m, "SmoothStreamingMedia");
            if (!q) throw new U(2, 4, 4046, l);
            l = a.g.mss.manifestPreprocessorTXml;
            l != Xn && l(q);
            a.i || (a.i = new Al(null, 0));
            if (l = $d(q, "IsLive", ke, false)) throw new U(2, 4, 4047);
            a.i.rd(!l);
            n = $d(q, "TimeScale", he, 1e7);
            m = $d(q, "DVRWindowLength", he);
            l && (m === 0 || isNaN(m)) && (m = Infinity);
            var r2 = $d(q, "CanSeek", ke, false);
            m === 0 && r2 && (m = Infinity);
            r2 = null;
            m && m > 0 && (r2 = m / n);
            l && !isNaN(a.g.availabilityWindowOverride) && (r2 = a.g.availabilityWindowOverride);
            r2 == null && (r2 = Infinity);
            a.i.hg(r2);
            m = $d(q, "Duration", he, Infinity);
            l || a.i.yb(m / n);
            l = {
              variants: [],
              textStreams: [],
              timescale: n,
              duration: m / n
            };
            var u;
            r2 = Sd(q, "Protection");
            n = a.g.mss.keySystemsBySystemId;
            m = [];
            r2 = t2(r2);
            for (u = r2.next(); !u.done; u = r2.next()) m = m.concat(Sd(u.value, "ProtectionHeader"));
            if (m.length) {
              r2 = [];
              for (u = 0; u < m.length; u++) {
                var w = m[u], v = w.attributes.SystemID.toLowerCase(), y = n[v];
                if (y) {
                  var z;
                  a: {
                    if (z = $u(w)) {
                      z = t2(Vd(z, "DATA"));
                      for (var A = z.next(); !A.done; A = z.next()) if (A = Xd(A.value, "KID")) {
                        z = jc(Td(A));
                        z = new Uint8Array([z[3], z[2], z[1], z[0], z[5], z[4], z[7], z[6]].concat(x(z.slice(8))));
                        z = lc(z);
                        break a;
                      }
                    }
                    z = null;
                  }
                  A = jc(Td(w));
                  v = kc(v.replace(/-/g, ""));
                  v = [{
                    initData: Bh(A, v, /* @__PURE__ */ new Set(), 0),
                    initDataType: "cenc",
                    keyId: z
                  }];
                  v = oc(y, "cenc", v);
                  z && v.keyIds.add(z);
                  if (y = cA.get(y)) v.licenseServerUri = y(w);
                  r2.push(v);
                }
              }
              n = r2;
            } else n = [];
            u = n;
            r2 = [];
            n = [];
            m = [];
            q = Sd(q, "StreamIndex");
            q = t2(q);
            for (w = q.next(); !w.done; w = q.next()) {
              w = w.value;
              y = Sd(w, "QualityLevel");
              v = l.timescale;
              z = l.duration;
              A = Sd(w, "c");
              for (var C = [], D = 0, F = 0; F < A.length; ++F) {
                var B = A[F], E = A[F + 1], I = $d(B, "t", he), J = $d(B, "d", he);
                B = $d(B, "r", fe);
                if (!J) break;
                I = I != null ? I : D;
                (B = B || 0) && B--;
                if (B < 0) if (E) {
                  E = $d(E, "t", he);
                  if (E == null) break;
                  else if (I >= E) break;
                  B = Math.ceil((E - I) / J) - 1;
                } else {
                  if (z == Infinity) break;
                  else if (I / v >= z) break;
                  B = Math.ceil((z * v - I) / J) - 1;
                }
                for (E = 0; E <= B; ++E) D = I + J, C.push({
                  start: I / v,
                  end: D / v,
                  xi: I
                }), I = D;
              }
              v = C;
              y = t2(y);
              for (z = y.next(); !z.done; z = y.next()) (z = gA(a, w, z.value, v, u, l)) && (z.type != "audio" || a.g.disableAudio ? z.type != "video" || a.g.disableVideo ? z.type != tc || a.g.disableText || m.push(z) : n.push(z) : r2.push(z));
            }
            q = [];
            r2 = t2(r2.length > 0 ? r2 : [null]);
            for (u = r2.next(); !u.done; u = r2.next()) for (u = u.value, w = t2(n.length > 0 ? n : [null]), C = w.next(); !C.done; C = w.next()) y = q, v = y.push, z = a, A = u, C = C.value, F = 0, A && A.bandwidth && A.bandwidth > 0 && (F += A.bandwidth), C && C.bandwidth && C.bandwidth > 0 && (F += C.bandwidth), z = {
              id: z.A++,
              language: A ? A.language : "und",
              disabledUntilTime: 0,
              primary: !!A && A.primary || !!C && C.primary,
              audio: A,
              video: C,
              bandwidth: F,
              allowedByApplication: true,
              allowedByKeySystem: true,
              decodingInfos: []
            }, v.call(y, z);
            l.variants = q;
            l.textStreams = m;
            a.j ? (a.j.variants = l.variants, a.j.textStreams = l.textStreams, a.h.filter(a.j)) : (a.j = {
              presentationTimeline: a.i,
              variants: l.variants,
              textStreams: l.textStreams,
              imageStreams: [],
              offlineSessionIds: [],
              sequenceMode: a.g.mss.sequenceMode,
              ignoreManifestTimestampsInSegmentsMode: false,
              type: "MSS",
              serviceDescription: null,
              nextUrl: null,
              periodCount: 1,
              gapCount: 0,
              isLowLatency: false,
              startTime: null
            }, a.i.If());
            Promise.resolve();
            g = Date.now();
            h = (g - d2) / 1e3;
            a.F.sample(1, h);
            H(k2);
          });
        }
        function gA(a, b, c, d2, e, f) {
          var g = b.attributes.Type;
          if (g !== "audio" && g !== "video" && g !== "text") return bb("Ignoring unrecognized type:", g), null;
          var h = b.attributes.Language, k2 = a.A++, l = $d(c, "Bitrate", ge), m = $d(c, "MaxWidth", ge), n = $d(c, "MaxHeight", ge), q = $d(c, "Channels", ge), r2 = $d(c, "SamplingRate", ge), u = f.duration;
          d2.length && (u = d2[d2.length - 1].end - d2[0].start);
          var w = a.i.getDuration();
          a.i.yb(Math.min(u, w));
          var v = {
            id: k2,
            originalId: b.attributes.Name || String(k2),
            groupId: null,
            createSegmentIndex: function() {
              return Promise.resolve();
            },
            closeSegmentIndex: function() {
              return Promise.resolve();
            },
            segmentIndex: null,
            mimeType: "",
            codecs: "",
            frameRate: void 0,
            pixelAspectRatio: void 0,
            bandwidth: l || 0,
            width: m || void 0,
            height: n || void 0,
            kind: "",
            encrypted: e.length > 0,
            drmInfos: e,
            keyIds: /* @__PURE__ */ new Set(),
            language: zc(h || "und"),
            originalLanguage: h,
            label: "",
            type: "",
            primary: false,
            trickModeVideo: null,
            dependencyStream: null,
            emsgSchemeIdUris: [],
            roles: [],
            forced: false,
            channelsCount: q,
            audioSamplingRate: r2,
            spatialAudio: false,
            closedCaptions: null,
            hdr: void 0,
            colorGamut: void 0,
            videoLayout: void 0,
            tilesLayout: void 0,
            matchedStreams: [],
            mssPrivateData: {
              duration: u,
              timescale: f.timescale,
              codecPrivateData: null
            },
            accessibilityPurpose: null,
            external: false,
            fastSwitching: false,
            fullMimeTypes: /* @__PURE__ */ new Set(),
            isAudioMuxedInVideo: false,
            baseOriginalId: null
          };
          if (e = b.attributes.Subtype) (e = hA.get(e)) && v.roles.push(e), e === "main" && (v.primary = true);
          e = c.attributes.FourCC;
          if (e === null || e === "") e = b.attributes.FourCC;
          if (!e) {
            if (g === "audio") e = "AAC";
            else if (g === "video") return bb('FourCC is not defined whereas it is required for a QualityLevel element for a StreamIndex of type "video"'), null;
          }
          if (!iA.includes(e.toUpperCase())) return bb("Codec not supported:", e), null;
          c = jA(c, g, e, v);
          v.mssPrivateData.codecPrivateData = c;
          switch (g) {
            case "audio":
              if (!c) return bb("Quality unsupported without CodecPrivateData", g), null;
              v.type = "audio";
              v.mimeType = "mss/audio/mp4";
              v.codecs = kA(e, c);
              break;
            case "video":
              if (!c) return bb("Quality unsupported without CodecPrivateData", g), null;
              v.type = "video";
              v.mimeType = "mss/video/mp4";
              v.codecs = lA(c);
              break;
            case "text":
              if (v.type = tc, v.mimeType = "application/mp4", e === "TTML" || e === "DFXP") v.codecs = "stpp";
          }
          v.fullMimeTypes.add(ef(v.mimeType, v.codecs));
          v.createSegmentIndex = function() {
            if (v.segmentIndex) return Promise.resolve();
            if (a.m.has(v.id)) var y = a.m.get(v.id);
            else y = [], v.type == "video" && (y = v.mssPrivateData.codecPrivateData.split("00000001").slice(1)), y = {
              id: v.id,
              type: v.type,
              codecs: v.codecs,
              encrypted: v.encrypted,
              timescale: v.mssPrivateData.timescale,
              duration: v.mssPrivateData.duration,
              Gb: y,
              Na: new Uint8Array([]),
              Xa: new Uint8Array([]),
              eb: 0,
              gb: 0,
              data: null,
              stream: v
            }, y = Wi(new Vi([y])), a.m.set(v.id, y);
            y = mA(a, new Aj(function() {
              return [];
            }, 0, null, nm(v), v.mssPrivateData.timescale, y, null, v.encrypted), v, b, d2);
            v.segmentIndex = new Zl(y);
            return Promise.resolve();
          };
          v.closeSegmentIndex = function() {
            v.segmentIndex && (v.segmentIndex.release(), v.segmentIndex = null);
          };
          return v;
        }
        function jA(a, b, c, d2) {
          if (a = a.attributes.CodecPrivateData) return a;
          if (b !== "audio") return null;
          b = d2.channelsCount || 2;
          a = d2.audioSamplingRate || 44100;
          var e = {
            96e3: 0,
            88200: 1,
            64e3: 2,
            48e3: 3,
            44100: 4,
            32e3: 5,
            24e3: 6,
            22050: 7,
            16e3: 8,
            12e3: 9,
            11025: 10,
            8e3: 11,
            7350: 12
          };
          d2 = e[a];
          if (c === "AACH") return c = new Uint8Array(4), a = e[a * 2], c[0] = 40 | d2 >> 1, c[1] = d2 << 7 | b << 3 | a >> 1, c[2] = a << 7 | 8, c[3] = 0, b = new Uint16Array(2), b[0] = (c[0] << 8) + c[1], b[1] = (c[2] << 8) + c[3], b[0].toString(16) + b[1].toString(16);
          c = new Uint8Array(2);
          c[0] = 16 | d2 >> 1;
          c[1] = d2 << 7 | b << 3;
          b = new Uint16Array(1);
          b[0] = (c[0] << 8) + c[1];
          return b[0].toString(16);
        }
        function kA(a, b) {
          var c = 0;
          a === "AACH" && (c = 5);
          b ? c === 0 && (c = (parseInt(b.substr(0, 2), 16) & 248) >> 3) : (c = 2, a === "AACH" && (c = 5));
          return "mp4a.40." + c;
        }
        function lA(a) {
          var b = /00000001[0-9]7/.exec(a);
          return b.length && a ? "avc1." + a.substr(a.indexOf(b[0]) + 10, 6) : "";
        }
        function mA(a, b, c, d2, e) {
          var f = d2.attributes.Url.replace("{bitrate}", String(c.bandwidth));
          d2 = [];
          e = t2(e);
          for (var g = e.next(), h = {}; !g.done; h = {
            mg: void 0
          }, g = e.next()) h.mg = g.value, d2.push(new Cj(h.mg.start, h.mg.end, /* @__PURE__ */ function(k2) {
            return function() {
              return nc(a.l, [f.replace("{start time}", String(k2.mg.xi))]);
            };
          }(h), 0, null, b, 0, 0, c.mssPrivateData.duration));
          return d2;
        }
        S("shaka.mss.MssParser", dA);
        var iA = "AAC AACL AACH AACP AVC1 H264 TTML DFXP".split(" "), hA = (/* @__PURE__ */ new Map()).set("CAPT", "main").set("SUBT", "alternate").set("DESC", "main");
        Gi("application/vnd.ms-sstr+xml", function() {
          return new dA();
        });
        function nA(a, b, c, d2, e, f, g) {
          if (c >= 200 && c <= 299 && c != 202 || c == 304) return {
            uri: e || d2,
            originalUri: d2,
            data: b,
            status: c,
            headers: a,
            fromCache: !!a["x-shaka-from-cache"],
            originalRequest: f
          };
          f = null;
          try {
            f = $b(b);
          } catch (h) {
          }
          throw new U(c == 401 || c == 403 ? 2 : 1, 1, 1001, d2, c, f, a, g, e || d2);
        }
        ;
        function oA() {
        }
        function pA(a, b, c, d2, e, f) {
          var g = new qA();
          kh(b.headers).forEach(function(m, n) {
            g.append(n, m);
          });
          var h = new rA(), k2 = {
            Ki: false,
            bk: false
          };
          a = sA(a, b, c, {
            body: b.body || void 0,
            headers: g,
            method: b.method,
            signal: h.signal,
            credentials: b.allowCrossSiteCredentials ? "include" : void 0
          }, k2, d2, e, b.streamDataCallback, f.minBytesForProgressEvents || 0);
          a = new Ng(a, function() {
            k2.Ki = true;
            h.abort();
            return Promise.resolve();
          });
          if (b = b.retryParameters.timeout) {
            var l = new Cf(function() {
              k2.bk = true;
              h.abort();
            });
            l.Y(b / 1e3);
            a.finally(function() {
              l.stop();
            });
          }
          return a;
        }
        function sA(a, b, c, d2, e, f, g, h, k2) {
          var l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B;
          return P(function(E) {
            switch (E.g) {
              case 1:
                return l = tA, m = uA, q = new ArrayBuffer(0), u = r2 = 0, w = {}, v = Date.now(), sa(E, 2), G(E, l(a, d2), 4);
              case 4:
                n = E.h;
                w = vA(n.headers);
                g(w);
                if (d2.method == "HEAD") {
                  E.B(5);
                  break;
                }
                z = (y = n.headers.get("Content-Length")) ? parseInt(y, 10) : 0;
                if (!n.body) return G(E, n.arrayBuffer(), 9);
                A = n.clone().body.getReader();
                C = function(I) {
                  function J() {
                    var K, L, M, N;
                    return P(function(O) {
                      switch (O.g) {
                        case 1:
                          return sa(O, 2), G(O, A.read(), 4);
                        case 4:
                          K = O.h;
                          ua(O, 3);
                          break;
                        case 2:
                          return va(O), O.return();
                        case 3:
                          if (K.done) {
                            O.B(5);
                            break;
                          }
                          r2 += K.value.byteLength;
                          if (!h) {
                            O.B(5);
                            break;
                          }
                          return G(O, h(K.value), 5);
                        case 5:
                          L = Date.now();
                          M = r2 - u;
                          if (L - v > 100 && M >= k2 || K.done) N = K.done ? 0 : z - r2, f(L - v, M, N), u = r2, v = L;
                          K.done ? I.close() : (I.enqueue(K.value), J());
                          H(O);
                      }
                    });
                  }
                  J();
                };
                new m({
                  start: C
                });
                return G(E, n.arrayBuffer(), 8);
              case 8:
                q = E.h;
                E.B(5);
                break;
              case 9:
                q = E.h, D = Date.now(), f(D - v, q.byteLength, 0);
              case 5:
                b.headers.Range && (F = b.headers.Range.replace("bytes=", "").split("-").filter(function(I) {
                  return I;
                }).map(function(I) {
                  return parseInt(I, 10);
                }), F.length == 2 && q.byteLength != F[1] - F[0] + 1 && bb("Payload length does not match range requested bytes", b, n));
                ua(E, 3);
                break;
              case 2:
                B = va(E);
                if (e.Ki) throw new U(1, 1, 7001, a, c);
                if (e.bk) throw new U(1, 1, 1003, a, c);
                throw new U(1, 1, 1002, a, B, c);
              case 3:
                return E.return(nA(w, q, n.status, a, n.url, b, c));
            }
          });
        }
        function vA(a) {
          var b = {};
          a.forEach(function(c, d2) {
            b[d2.trim()] = c;
          });
          return b;
        }
        function wA() {
          if (window7.ReadableStream) try {
            new ReadableStream({});
          } catch (a) {
            return false;
          }
          else return false;
          if (window7.Response) {
            if (!new Response("").body) return false;
          } else return false;
          return !(!window7.fetch || "polyfill" in window7.fetch || !window7.AbortController);
        }
        S("shaka.net.HttpFetchPlugin", oA);
        oA.isSupported = wA;
        oA.parse = pA;
        var tA = window7.fetch, rA = window7.AbortController, uA = window7.ReadableStream, qA = window7.Headers;
        wA() && (Xg("http", pA, 2, true), Xg("https", pA, 2, true), Xg("blob", pA, 2, true));
        function xA() {
        }
        function yA(a, b, c, d2, e, f) {
          var g = new zA(), h = Date.now(), k2 = 0, l = new Promise(function(m, n) {
            g.open(b.method, a, true);
            g.responseType = "arraybuffer";
            g.timeout = b.retryParameters.timeout;
            g.withCredentials = b.allowCrossSiteCredentials;
            var q = {};
            g.onabort = function() {
              n(new U(1, 1, 7001, a, c));
            };
            g.onreadystatechange = function() {
              if (g.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
                var u = g.getAllResponseHeaders().trim().split("\r\n"), w = {};
                u = t2(u);
                for (var v = u.next(); !v.done; v = u.next()) v = v.value.split(": "), w[v[0].toLowerCase()] = v.slice(1).join(": ");
                q = w;
                e(q);
              }
            };
            g.onload = function(u) {
              var w = g.response;
              try {
                d2(Date.now() - h, u.loaded - k2, 0);
                var v = nA(q, w, g.status, a, g.responseURL, b, c);
                m(v);
              } catch (y) {
                n(y);
              }
            };
            g.onerror = function(u) {
              n(new U(1, 1, 1002, a, u, c));
            };
            g.ontimeout = function() {
              n(new U(1, 1, 1003, a, c));
            };
            g.onprogress = function(u) {
              var w = Date.now(), v = f.minBytesForProgressEvents || 0, y = u.loaded - k2;
              if (w - h > 100 && y >= v || u.lengthComputable && u.loaded == u.total) d2(w - h, y, g.readyState == 4 ? 0 : u.total - u.loaded), k2 = u.loaded, h = w;
            };
            for (var r2 in b.headers) g.setRequestHeader(r2.toLowerCase(), b.headers[r2]);
            g.send(b.body);
          });
          return new Ng(l, function() {
            g.abort();
            return Promise.resolve();
          });
        }
        S("shaka.net.HttpXHRPlugin", xA);
        xA.parse = yA;
        var zA = window7.XMLHttpRequest;
        Xg("http", yA, 1, true);
        Xg("https", yA, 1, true);
        Xg("blob", yA, 1, true);
        function AA(a, b, c, d2, e) {
          this.g = a;
          this.i = b;
          this.groupId = c;
          this.h = d2;
          this.j = e;
        }
        function BA(a) {
          var b = a.fc(false);
          return b ? ic(b) : a.T().map(function(c) {
            return "{" + encodeURI(c.split("#xywh=")[0]) + "}";
          }).join("") + ":" + a.startByte + ":" + a.endByte;
        }
        function CA(a, b) {
          return Jm(a.g.T(), a.g.startByte, a.g.endByte, b.streaming.retryParameters);
        }
        ;
        function DA() {
          this.g = this.j = this.i = 0;
          this.h = /* @__PURE__ */ new Map();
          this.l = 0;
        }
        function EA(a, b) {
          a.i += b;
          var c = a.l;
          a.l++;
          a.h.set(c, b);
          return c;
        }
        DA.prototype.close = function(a, b) {
          if (this.h.has(a)) {
            var c = this.h.get(a);
            this.h.delete(a);
            this.j += c;
            this.g += b;
          }
        };
        function FA(a) {
          return a.i == 0 ? 0 : a.j / a.i;
        }
        ;
        function GA(a) {
          var b = this;
          this.A = a;
          this.i = /* @__PURE__ */ new Map();
          this.h = new ih(function() {
            return HA(b).catch(function() {
            });
          });
          this.j = [];
          this.u = function() {
          };
          this.m = function() {
          };
          this.g = new DA();
          this.l = false;
        }
        GA.prototype.destroy = function() {
          return this.h.destroy();
        };
        function IA(a, b, c) {
          a.u = b;
          a.m = c;
        }
        function HA(a) {
          a.l = true;
          var b = a.j.map(function(c) {
            return c();
          });
          a.j = [];
          return Promise.all(b);
        }
        GA.prototype.queue = function(a, b, c, d2, e) {
          var f = this;
          jh(this.h);
          var g = (this.i.get(a) || Promise.resolve()).then(function() {
            var h, k2, l, m, n, q, r2;
            return P(function(u) {
              if (u.g == 1) return G(u, JA(f, b), 2);
              h = u.h;
              if (f.h.g) throw new U(2, 9, 7001);
              if (d2) for (m in k2 = Lb(h), l = new Ah(k2), l.data) n = Number(m), q = l.data[n], r2 = l.g[n], f.m(q, r2);
              f.g.close(c, h.byteLength);
              f.u(FA(f.g), f.g.g);
              return u.return(e(h));
            });
          });
          this.i.set(a, g);
          return g;
        };
        function KA(a, b, c, d2, e, f) {
          jh(a.h);
          var g = (a.i.get(b) || Promise.resolve()).then(function() {
            if (a.h.g) throw new U(2, 9, 7001);
            if (e) {
              var h = Lb(c);
              h = new Ah(h);
              for (var k2 in h.data) {
                var l = Number(k2);
                a.m(h.data[l], h.g[l]);
              }
            }
            a.g.close(d2, c.byteLength);
            a.u(FA(a.g), a.g.g);
            return f(c);
          });
          a.i.set(b, g);
        }
        function LA(a) {
          return P(function(b) {
            return b.g == 1 ? G(b, Promise.all(a.i.values()), 2) : b.return(a.g.g);
          });
        }
        function JA(a, b) {
          var c, d2, e, f;
          return P(function(g) {
            if (g.g == 1) return c = gh, d2 = a.A.request(c, b), e = function() {
              return d2.abort();
            }, a.j.push(e), G(g, d2.promise, 2);
            f = g.h;
            ud(a.j, e);
            return g.return(f.data);
          });
        }
        ;
        function MA(a, b) {
          var c = this;
          this.i = a;
          this.h = a.objectStore(b);
          this.g = new Mg();
          a.onabort = function(d2) {
            d2.preventDefault();
            c.g.reject();
          };
          a.onerror = function(d2) {
            d2.preventDefault();
            c.g.reject();
          };
          a.oncomplete = function() {
            c.g.resolve();
          };
        }
        MA.prototype.abort = function() {
          var a = this;
          return P(function(b) {
            if (b.g == 1) {
              try {
                a.i.abort();
              } catch (c) {
              }
              sa(b, 2);
              return G(b, a.g, 4);
            }
            if (b.g != 2) return ua(b, 0);
            va(b);
            H(b);
          });
        };
        function NA(a, b) {
          return new Promise(function(c, d2) {
            var e = a.h.openCursor();
            e.onerror = d2;
            e.onsuccess = function() {
              var f;
              return P(function(g) {
                if (g.g == 1) {
                  if (e.result == null) return c(), g.return();
                  f = e.result;
                  return G(g, b(f.key, f.value, f), 2);
                }
                f.continue();
                H(g);
              });
            };
          });
        }
        MA.prototype.store = function() {
          return this.h;
        };
        MA.prototype.promise = function() {
          return this.g;
        };
        function OA(a) {
          this.h = a;
          this.g = [];
        }
        OA.prototype.destroy = function() {
          return Promise.all(this.g.map(function(a) {
            return a.abort();
          }));
        };
        function PA(a, b) {
          return QA(a, b, "readwrite");
        }
        function QA(a, b, c) {
          c = a.h.transaction([b], c);
          var d2 = new MA(c, b);
          a.g.push(d2);
          d2.promise().then(function() {
            ud(a.g, d2);
          }, function() {
            ud(a.g, d2);
          });
          return d2;
        }
        ;
        function RA(a, b, c) {
          this.h = new OA(a);
          this.i = b;
          this.g = c;
        }
        p = RA.prototype;
        p.destroy = function() {
          return this.h.destroy();
        };
        p.hasFixedKeySpace = function() {
          return true;
        };
        p.addSegments = function() {
          return SA(this.i);
        };
        p.removeSegments = function(a, b) {
          return TA(this, this.i, a, b);
        };
        p.getSegments = function(a) {
          var b = this, c;
          return P(function(d2) {
            if (d2.g == 1) return G(d2, UA(b, b.i, a), 2);
            c = d2.h;
            return d2.return(c.map(function(e) {
              return b.Pi(e);
            }));
          });
        };
        p.addManifests = function() {
          return SA(this.g);
        };
        p.updateManifest = function() {
          return Promise.reject(new U(2, 9, 9016, "Cannot modify values in " + this.g));
        };
        function VA(a, b, c) {
          a = PA(a.h, a.g);
          var d2 = a.store();
          d2.get(b).onsuccess = function() {
            d2.put(c, b);
          };
          return a.promise();
        }
        p.updateManifestExpiration = function(a, b) {
          var c = PA(this.h, this.g), d2 = c.store();
          d2.get(a).onsuccess = function(e) {
            if (e = e.target.result) e.expiration = b, d2.put(e, a);
          };
          return c.promise();
        };
        p.removeManifests = function(a, b) {
          return TA(this, this.g, a, b);
        };
        p.getManifests = function(a) {
          var b = this, c;
          return P(function(d2) {
            if (d2.g == 1) return G(d2, UA(b, b.g, a), 2);
            c = d2.h;
            return d2.return(Promise.all(c.map(function(e) {
              return b.ee(e);
            })));
          });
        };
        p.getAllManifests = function() {
          var a = this, b, c;
          return P(function(d2) {
            return d2.g == 1 ? (b = QA(a.h, a.g, "readonly"), c = /* @__PURE__ */ new Map(), G(d2, NA(b, function(e, f) {
              var g;
              return P(function(h) {
                if (h.g == 1) return G(h, a.ee(f), 2);
                g = h.h;
                c.set(e, g);
                H(h);
              });
            }), 2)) : d2.g != 3 ? G(d2, b.promise(), 3) : d2.return(c);
          });
        };
        p.Pi = function(a) {
          return a;
        };
        p.ee = function(a) {
          return Promise.resolve(a);
        };
        function SA(a) {
          return Promise.reject(new U(2, 9, 9011, "Cannot add new value to " + a));
        }
        p.add = function(a, b) {
          var c = this, d2, e, f, g, h, k2, l;
          return P(function(m) {
            if (m.g == 1) {
              d2 = PA(c.h, a);
              e = d2.store();
              f = [];
              g = t2(b);
              h = g.next();
              for (k2 = {}; !h.done; k2 = {
                Vh: void 0
              }, h = g.next()) l = h.value, k2.Vh = e.add(l), k2.Vh.onsuccess = /* @__PURE__ */ function(n) {
                return function() {
                  f.push(n.Vh.result);
                };
              }(k2);
              return G(m, d2.promise(), 2);
            }
            return m.return(f);
          });
        };
        function TA(a, b, c, d2) {
          a = PA(a.h, b);
          b = a.store();
          c = t2(c);
          for (var e = c.next(), f = {}; !e.done; f = {
            Ih: void 0
          }, e = c.next()) f.Ih = e.value, b.delete(f.Ih).onsuccess = /* @__PURE__ */ function(g) {
            return function() {
              return d2(g.Ih);
            };
          }(f);
          return a.promise();
        }
        function UA(a, b, c) {
          var d2, e, f, g, h, k2, l;
          return P(function(m) {
            if (m.g == 1) {
              d2 = QA(a.h, b, "readonly");
              e = d2.store();
              f = {};
              g = [];
              h = t2(c);
              k2 = h.next();
              for (l = {}; !k2.done; l = {
                ag: void 0,
                Ef: void 0
              }, k2 = h.next()) l.Ef = k2.value, l.ag = e.get(l.Ef), l.ag.onsuccess = /* @__PURE__ */ function(n) {
                return function() {
                  n.ag.result == void 0 && g.push(n.Ef);
                  f[n.Ef] = n.ag.result;
                };
              }(l);
              return G(m, d2.promise(), 2);
            }
            if (g.length) throw new U(2, 9, 9012, "Could not find values for " + g);
            return m.return(c.map(function(n) {
              return f[n];
            }));
          });
        }
        ;
        function WA(a) {
          this.g = new OA(a);
        }
        WA.prototype.destroy = function() {
          return this.g.destroy();
        };
        WA.prototype.getAll = function() {
          var a = this, b, c;
          return P(function(d2) {
            return d2.g == 1 ? (b = QA(a.g, "session-ids", "readonly"), c = [], G(d2, NA(b, function(e, f) {
              c.push(f);
            }), 2)) : d2.g != 3 ? G(d2, b.promise(), 3) : d2.return(c);
          });
        };
        WA.prototype.add = function(a) {
          var b = PA(this.g, "session-ids"), c = b.store();
          a = t2(a);
          for (var d2 = a.next(); !d2.done; d2 = a.next()) c.add(d2.value);
          return b.promise();
        };
        WA.prototype.remove = function(a) {
          var b = this, c;
          return P(function(d2) {
            return d2.g == 1 ? (c = PA(b.g, "session-ids"), G(d2, NA(c, function(e, f, g) {
              a.includes(f.sessionId) && g.delete();
            }), 2)) : G(d2, c.promise(), 0);
          });
        };
        function XA() {
          this.g = /* @__PURE__ */ new Map();
        }
        XA.prototype.destroy = function() {
          for (var a = [], b = t2(this.g.values()), c = b.next(); !c.done; c = b.next()) a.push(c.value.destroy());
          this.g.clear();
          return Promise.all(a);
        };
        XA.prototype.init = function() {
          var a = this;
          YA.forEach(function(e, f) {
            (e = e()) && a.g.set(f, e);
          });
          for (var b = [], c = t2(this.g.values()), d2 = c.next(); !d2.done; d2 = c.next()) b.push(d2.value.init());
          return Promise.all(b);
        };
        function ZA(a) {
          var b = null;
          a.g.forEach(function(c, d2) {
            c.getCells().forEach(function(e, f) {
              e.hasFixedKeySpace() || b || (b = {
                path: {
                  Xb: d2,
                  jb: f
                },
                jb: e
              });
            });
          });
          if (b) return b;
          throw new U(2, 9, 9013, "Could not find a cell that supports add-operations");
        }
        function $A(a, b) {
          a.g.forEach(function(c, d2) {
            c.getCells().forEach(function(e, f) {
              b({
                Xb: d2,
                jb: f
              }, e);
            });
          });
        }
        function aB(a, b, c) {
          a = a.g.get(b);
          if (!a) throw new U(2, 9, 9013, "Could not find mechanism with name " + b);
          b = a.getCells().get(c);
          if (!b) throw new U(2, 9, 9013, "Could not find cell with name " + c);
          return b;
        }
        function bB(a, b) {
          a.g.forEach(function(c) {
            b(c.getEmeSessionCell());
          });
        }
        function cB(a) {
          var b = Array.from(a.g.keys());
          if (!b.length) throw new U(2, 9, 9e3, "No supported storage mechanisms found");
          return a.g.get(b[0]).getEmeSessionCell();
        }
        function dB(a) {
          var b, c, d2;
          return P(function(e) {
            return e.g == 1 ? (b = Array.from(a.g.values()), c = b.length > 0, c || (d2 = YA, d2.forEach(function(f) {
              (f = f()) && b.push(f);
            })), G(e, Promise.all(b.map(function(f) {
              return f.erase();
            })), 2)) : c ? e.B(0) : G(e, Promise.all(b.map(function(f) {
              return f.destroy();
            })), 0);
          });
        }
        function eB(a, b) {
          YA.set(a, b);
        }
        S("shaka.offline.StorageMuxer", XA);
        XA.unregister = function(a) {
          YA.delete(a);
        };
        XA.register = eB;
        XA.prototype.destroy = XA.prototype.destroy;
        var YA = /* @__PURE__ */ new Map();
        function fB() {
          RA.apply(this, arguments);
        }
        ma(fB, RA);
        fB.prototype.updateManifestExpiration = function(a, b) {
          var c = this, d2, e, f;
          return P(function(g) {
            d2 = PA(c.h, c.g);
            e = d2.store();
            f = new Mg();
            e.get(a).onsuccess = function(h) {
              (h = h.target.result) ? (h.expiration = b, e.put(h), f.resolve()) : f.reject(new U(2, 9, 9012, "Could not find values for " + a));
            };
            return G(g, Promise.all([d2.promise(), f]), 0);
          });
        };
        fB.prototype.ee = function(a) {
          var b, c, d2, e, f, g;
          return P(function(h) {
            if (h.g == 1) {
              b = [];
              for (c = 0; c < a.periods.length; ++c) d2 = c == a.periods.length - 1 ? a.duration : a.periods[c + 1].startTime, e = d2 - a.periods[c].startTime, f = gB(a.periods[c], e), b.push(f);
              return G(h, ow(b), 2);
            }
            g = h.h;
            return h.return({
              creationTime: 0,
              originalManifestUri: a.originalManifestUri,
              duration: a.duration,
              size: a.size,
              expiration: a.expiration == null ? Infinity : a.expiration,
              streams: g,
              sessionIds: a.sessionIds,
              drmInfo: a.drmInfo,
              appMetadata: a.appMetadata,
              sequenceMode: false
            });
          });
        };
        function gB(a, b) {
          hB(a);
          for (var c = t2(a.streams), d2 = c.next(); !d2.done; d2 = c.next()) ;
          return a.streams.map(function(e) {
            return iB(e, a.startTime, b);
          });
        }
        function iB(a, b, c) {
          var d2 = a.initSegmentUri ? jB(a.initSegmentUri) : null, e = b + a.presentationTimeOffset, f = b + c;
          return {
            id: a.id,
            originalId: null,
            groupId: null,
            primary: a.primary,
            type: a.contentType,
            mimeType: a.mimeType,
            codecs: a.codecs,
            frameRate: a.frameRate,
            pixelAspectRatio: void 0,
            hdr: void 0,
            colorGamut: void 0,
            videoLayout: void 0,
            kind: a.kind,
            language: a.language,
            originalLanguage: a.language || null,
            label: a.label,
            width: a.width,
            height: a.height,
            initSegmentKey: d2,
            encrypted: a.encrypted,
            keyIds: /* @__PURE__ */ new Set([a.keyId]),
            segments: a.segments.map(function(g) {
              var h = jB(g.uri);
              return {
                startTime: b + g.startTime,
                endTime: b + g.endTime,
                dataKey: h,
                initSegmentKey: d2,
                appendWindowStart: b,
                appendWindowEnd: f,
                timestampOffset: e,
                tilesLayout: "",
                mimeType: null,
                codecs: null,
                thumbnailSprite: null
              };
            }),
            variantIds: a.variantIds,
            roles: [],
            forced: false,
            audioSamplingRate: null,
            channelsCount: null,
            spatialAudio: false,
            closedCaptions: null,
            tilesLayout: void 0,
            external: false,
            fastSwitching: false,
            isAudioMuxedInVideo: false
          };
        }
        fB.prototype.Pi = function(a) {
          return {
            data: a.data
          };
        };
        function jB(a) {
          var b;
          if ((b = /^offline:[0-9]+\/[0-9]+\/([0-9]+)$/.exec(a)) || (b = /^offline:segment\/([0-9]+)$/.exec(a))) return Number(b[1]);
          throw new U(2, 9, 9004, "Could not parse uri " + a);
        }
        function hB(a) {
          var b = a.streams.filter(function(h) {
            return h.contentType == "audio";
          });
          a = a.streams.filter(function(h) {
            return h.contentType == "video";
          });
          if (!b.every(function(h) {
            return h.variantIds;
          }) || !a.every(function(h) {
            return h.variantIds;
          })) {
            for (var c = t2(b), d2 = c.next(); !d2.done; d2 = c.next()) d2.value.variantIds = [];
            c = t2(a);
            for (d2 = c.next(); !d2.done; d2 = c.next()) d2.value.variantIds = [];
            c = 0;
            if (a.length && !b.length) {
              d2 = c++;
              for (var e = t2(a), f = e.next(); !f.done; f = e.next()) f.value.variantIds.push(d2);
            }
            if (!a.length && b.length) for (d2 = c++, e = t2(b), f = e.next(); !f.done; f = e.next()) f.value.variantIds.push(d2);
            if (a.length && b.length) for (b = t2(b), d2 = b.next(); !d2.done; d2 = b.next()) for (d2 = d2.value, e = t2(a), f = e.next(); !f.done; f = e.next()) {
              f = f.value;
              var g = c++;
              d2.variantIds.push(g);
              f.variantIds.push(g);
            }
          }
        }
        ;
        function kB() {
          RA.apply(this, arguments);
        }
        ma(kB, RA);
        kB.prototype.ee = function(a) {
          var b, c, d2, e, f, g;
          return P(function(h) {
            if (h.g == 1) {
              b = [];
              for (c = 0; c < a.periods.length; ++c) {
                d2 = c == a.periods.length - 1 ? a.duration : a.periods[c + 1].startTime;
                e = d2 - a.periods[c].startTime;
                for (var k2 = a.periods[c], l = [], m = t2(k2.streams), n = m.next(); !n.done; n = m.next()) n = n.value, n.variantIds.length != 0 && l.push(lB(n, k2.startTime, k2.startTime + e));
                f = l;
                b.push(f);
              }
              return G(h, ow(b), 2);
            }
            g = h.h;
            return h.return({
              appMetadata: a.appMetadata,
              creationTime: 0,
              drmInfo: a.drmInfo,
              duration: a.duration,
              expiration: a.expiration == null ? Infinity : a.expiration,
              originalManifestUri: a.originalManifestUri,
              sessionIds: a.sessionIds,
              size: a.size,
              streams: g,
              sequenceMode: false
            });
          });
        };
        function lB(a, b, c) {
          return {
            id: a.id,
            originalId: a.originalId,
            groupId: null,
            primary: a.primary,
            type: a.contentType,
            mimeType: a.mimeType,
            codecs: a.codecs,
            frameRate: a.frameRate,
            pixelAspectRatio: a.pixelAspectRatio,
            hdr: void 0,
            colorGamut: void 0,
            videoLayout: void 0,
            kind: a.kind,
            language: a.language,
            originalLanguage: a.language || null,
            label: a.label,
            width: a.width,
            height: a.height,
            encrypted: a.encrypted,
            keyIds: /* @__PURE__ */ new Set([a.keyId]),
            segments: a.segments.map(function(d2) {
              return {
                startTime: b + d2.startTime,
                endTime: b + d2.endTime,
                initSegmentKey: a.initSegmentKey,
                appendWindowStart: b,
                appendWindowEnd: c,
                timestampOffset: b - a.presentationTimeOffset,
                dataKey: d2.dataKey,
                tilesLayout: "",
                mimeType: null,
                codecs: null,
                thumbnailSprite: null
              };
            }),
            variantIds: a.variantIds,
            roles: [],
            forced: false,
            audioSamplingRate: null,
            channelsCount: null,
            spatialAudio: false,
            closedCaptions: null,
            tilesLayout: void 0,
            external: false,
            fastSwitching: false,
            isAudioMuxedInVideo: false
          };
        }
        ;
        function mB() {
          RA.apply(this, arguments);
        }
        ma(mB, RA);
        p = mB.prototype;
        p.hasFixedKeySpace = function() {
          return false;
        };
        p.addSegments = function(a) {
          return this.add(this.i, a);
        };
        p.addManifests = function(a) {
          return this.add(this.g, a);
        };
        p.updateManifest = function(a, b) {
          return VA(this, a, b);
        };
        p.ee = function(a) {
          a.expiration == null && (a.expiration = Infinity);
          return Promise.resolve(a);
        };
        function nB() {
          this.m = this.j = this.i = this.h = this.g = this.l = null;
        }
        p = nB.prototype;
        p.init = function() {
          var a = this, b = new Mg(), c = false, d2 = new Cf(function() {
            c = true;
            b.reject(new U(2, 9, 9017));
          });
          typeof oB === "number" && oB > 0 && d2.Y(oB);
          var e = window7.indexedDB.open("shaka_offline_db", 5);
          e.onsuccess = function() {
            if (!c) {
              d2.stop();
              var f = e.result;
              a.l = f;
              var g = f.objectStoreNames;
              g = g.contains("manifest") && g.contains("segment") ? new fB(f, "segment", "manifest") : null;
              a.g = g;
              g = f.objectStoreNames;
              g = g.contains("manifest-v2") && g.contains("segment-v2") ? new kB(f, "segment-v2", "manifest-v2") : null;
              a.h = g;
              g = f.objectStoreNames;
              g = g.contains("manifest-v3") && g.contains("segment-v3") ? new kB(f, "segment-v3", "manifest-v3") : null;
              a.i = g;
              g = f.objectStoreNames;
              g = g.contains("manifest-v5") && g.contains("segment-v5") ? new mB(f, "segment-v5", "manifest-v5") : null;
              a.j = g;
              f = f.objectStoreNames.contains("session-ids") ? new WA(f) : null;
              a.m = f;
              b.resolve();
            }
          };
          e.onupgradeneeded = function() {
            for (var f = e.result, g = t2(["segment-v5", "manifest-v5", "session-ids"]), h = g.next(); !h.done; h = g.next()) h = h.value, f.objectStoreNames.contains(h) || f.createObjectStore(h, {
              autoIncrement: true
            });
          };
          e.onerror = function(f) {
            c || (d2.stop(), b.reject(new U(2, 9, 9001, e.error)), f.preventDefault());
          };
          return b;
        };
        p.destroy = function() {
          var a = this;
          return P(function(b) {
            switch (b.g) {
              case 1:
                if (!a.g) {
                  b.B(2);
                  break;
                }
                return G(b, a.g.destroy(), 2);
              case 2:
                if (!a.h) {
                  b.B(4);
                  break;
                }
                return G(b, a.h.destroy(), 4);
              case 4:
                if (!a.i) {
                  b.B(6);
                  break;
                }
                return G(b, a.i.destroy(), 6);
              case 6:
                if (!a.j) {
                  b.B(8);
                  break;
                }
                return G(b, a.j.destroy(), 8);
              case 8:
                if (!a.m) {
                  b.B(10);
                  break;
                }
                return G(b, a.m.destroy(), 10);
              case 10:
                a.l && a.l.close(), H(b);
            }
          });
        };
        p.getCells = function() {
          var a = /* @__PURE__ */ new Map();
          this.g && a.set("v1", this.g);
          this.h && a.set("v2", this.h);
          this.i && a.set("v3", this.i);
          this.j && a.set("v5", this.j);
          return a;
        };
        p.getEmeSessionCell = function() {
          return this.m;
        };
        p.erase = function() {
          var a = this;
          return P(function(b) {
            switch (b.g) {
              case 1:
                if (!a.g) {
                  b.B(2);
                  break;
                }
                return G(b, a.g.destroy(), 2);
              case 2:
                if (!a.h) {
                  b.B(4);
                  break;
                }
                return G(b, a.h.destroy(), 4);
              case 4:
                if (!a.i) {
                  b.B(6);
                  break;
                }
                return G(b, a.i.destroy(), 6);
              case 6:
                if (!a.j) {
                  b.B(8);
                  break;
                }
                return G(b, a.j.destroy(), 8);
              case 8:
                return a.l && a.l.close(), G(b, pB(), 10);
              case 10:
                return a.l = null, a.g = null, a.h = null, a.i = null, a.j = null, G(b, a.init(), 0);
            }
          });
        };
        function pB() {
          var a = new Mg(), b = window7.indexedDB.deleteDatabase("shaka_offline_db");
          b.onblocked = function() {
          };
          b.onsuccess = function() {
            a.resolve();
          };
          b.onerror = function(c) {
            a.reject(new U(2, 9, 9001, b.error));
            c.preventDefault();
          };
          return a;
        }
        var oB = 5;
        S("shaka.offline.indexeddb.StorageMechanismOpenTimeout", oB);
        eB("idb", function() {
          return Sb().oi() ? new nB() : null;
        });
        function qB(a, b, c, d2) {
          this.g = a;
          this.i = b;
          this.h = c;
          this.l = d2;
          this.j = ["offline:", a, "/", b, "/", c, "/", d2].join("");
        }
        qB.prototype.Xb = function() {
          return this.i;
        };
        qB.prototype.jb = function() {
          return this.h;
        };
        qB.prototype.key = function() {
          return this.l;
        };
        qB.prototype.toString = function() {
          return this.j;
        };
        function rB(a) {
          a = /^offline:([a-z]+)\/([^/]+)\/([^/]+)\/([0-9]+)$/.exec(a);
          if (a == null) return null;
          var b = a[1];
          if (b != "manifest" && b != "segment") return null;
          var c = a[2];
          if (!c) return null;
          var d2 = a[3];
          return d2 && b != null ? new qB(b, c, d2, Number(a[4])) : null;
        }
        ;
        function sB(a, b) {
          this.h = a;
          this.g = b;
        }
        function tB(a, b) {
          var c = new Al(null, 0);
          c.yb(b.duration);
          var d2 = b.streams.filter(function(l) {
            return l.type == "audio";
          }), e = b.streams.filter(function(l) {
            return l.type == "video";
          });
          d2 = uB(a, d2, e, c);
          e = b.streams.filter(function(l) {
            return l.type == tc;
          }).map(function(l) {
            return vB(a, l, c);
          });
          var f = b.streams.filter(function(l) {
            return l.type == "image";
          }).map(function(l) {
            return vB(a, l, c);
          }), g = b.drmInfo ? [b.drmInfo] : [];
          if (b.drmInfo) for (var h = t2(d2.values()), k2 = h.next(); !k2.done; k2 = h.next()) k2 = k2.value, k2.audio && k2.audio.encrypted && (k2.audio.drmInfos = g), k2.video && k2.video.encrypted && (k2.video.drmInfos = g);
          return {
            presentationTimeline: c,
            offlineSessionIds: b.sessionIds,
            variants: Array.from(d2.values()),
            textStreams: e,
            imageStreams: f,
            sequenceMode: b.sequenceMode || false,
            ignoreManifestTimestampsInSegmentsMode: false,
            type: b.type || "UNKNOWN",
            serviceDescription: null,
            nextUrl: null,
            periodCount: 1,
            gapCount: 0,
            isLowLatency: false,
            startTime: null
          };
        }
        function uB(a, b, c, d2) {
          for (var e = /* @__PURE__ */ new Set(), f = t2(b), g = f.next(); !g.done; g = f.next()) {
            g = t2(g.value.variantIds);
            for (var h = g.next(); !h.done; h = g.next()) e.add(h.value);
          }
          f = t2(c);
          for (g = f.next(); !g.done; g = f.next()) for (g = t2(g.value.variantIds), h = g.next(); !h.done; h = g.next()) e.add(h.value);
          f = /* @__PURE__ */ new Map();
          e = t2(e);
          for (g = e.next(); !g.done; g = e.next()) g = g.value, f.set(g, {
            id: g,
            language: "",
            disabledUntilTime: 0,
            primary: false,
            audio: null,
            video: null,
            bandwidth: 0,
            allowedByApplication: true,
            allowedByKeySystem: true,
            decodingInfos: []
          });
          b = t2(b);
          for (e = b.next(); !e.done; e = b.next()) for (g = e.value, e = vB(a, g, d2), g = t2(g.variantIds), h = g.next(); !h.done; h = g.next()) h = f.get(h.value), h.language = e.language, h.primary = h.primary || e.primary, h.audio = e;
          c = t2(c);
          for (b = c.next(); !b.done; b = c.next()) for (e = b.value, b = vB(a, e, d2), e = t2(e.variantIds), g = e.next(); !g.done; g = e.next()) g = f.get(g.value), g.primary = g.primary || b.primary, g.video = b;
          return f;
        }
        function vB(a, b, c) {
          var d2 = b.segments.map(function(e) {
            return wB(a, e, b);
          });
          c.ye(d2);
          return {
            id: b.id,
            originalId: b.originalId,
            groupId: b.groupId,
            createSegmentIndex: function() {
              return Promise.resolve();
            },
            segmentIndex: new Zl(d2),
            mimeType: b.mimeType,
            codecs: b.codecs,
            width: b.width || void 0,
            height: b.height || void 0,
            frameRate: b.frameRate,
            pixelAspectRatio: b.pixelAspectRatio,
            hdr: b.hdr,
            colorGamut: b.colorGamut,
            videoLayout: b.videoLayout,
            kind: b.kind,
            encrypted: b.encrypted,
            drmInfos: [],
            keyIds: b.keyIds,
            language: b.language,
            originalLanguage: b.originalLanguage || null,
            label: b.label,
            type: b.type,
            primary: b.primary,
            trickModeVideo: null,
            dependencyStream: null,
            emsgSchemeIdUris: null,
            roles: b.roles,
            forced: b.forced,
            channelsCount: b.channelsCount,
            audioSamplingRate: b.audioSamplingRate,
            spatialAudio: b.spatialAudio,
            closedCaptions: b.closedCaptions,
            tilesLayout: b.tilesLayout,
            mssPrivateData: b.mssPrivateData,
            accessibilityPurpose: null,
            external: b.external,
            fastSwitching: b.fastSwitching,
            fullMimeTypes: /* @__PURE__ */ new Set([ef(b.mimeType, b.codecs)]),
            isAudioMuxedInVideo: false,
            baseOriginalId: null
          };
        }
        function wB(a, b, c) {
          var d2 = new qB("segment", a.h, a.g, b.dataKey);
          a = new Cj(b.startTime, b.endTime, function() {
            return [d2.toString()];
          }, 0, null, b.initSegmentKey != null ? xB(a, b.initSegmentKey) : null, b.timestampOffset, b.appendWindowStart, b.appendWindowEnd, [], b.tilesLayout || "");
          a.mimeType = b.mimeType || c.mimeType || "";
          a.codecs = b.codecs || c.codecs || "";
          b.thumbnailSprite && a.jg(b.thumbnailSprite);
          return a;
        }
        function xB(a, b) {
          var c = new qB("segment", a.h, a.g, b);
          return new Aj(function() {
            return [c.toString()];
          }, 0, null);
        }
        ;
        function yB() {
          this.g = null;
        }
        p = yB.prototype;
        p.configure = function() {
        };
        p.start = function(a, b) {
          var c = this, d2, e, f, g, h, k2, l;
          return P(function(m) {
            switch (m.g) {
              case 1:
                d2 = rB(a);
                c.g = d2;
                if (d2 == null || d2.g != "manifest") throw new U(2, 1, 9004, a);
                e = new XA();
                ta(m, 2);
                return G(m, e.init(), 4);
              case 4:
                return G(m, aB(e, d2.Xb(), d2.jb()), 5);
              case 5:
                return f = m.h, G(m, f.getManifests([d2.key()]), 6);
              case 6:
                return g = m.h, h = g[0], k2 = new sB(d2.Xb(), d2.jb()), l = tB(k2, h), b.makeTextStreamsForClosedCaptions(l), m.return(l);
              case 2:
                return wa(m), G(m, e.destroy(), 7);
              case 7:
                xa(m, 0);
            }
          });
        };
        p.stop = function() {
          return Promise.resolve();
        };
        p.update = function() {
        };
        p.onExpirationUpdated = function(a, b) {
          var c = this, d2, e, f, g, h, k2, l;
          return P(function(m) {
            switch (m.g) {
              case 1:
                return d2 = c.g, e = new XA(), sa(m, 2, 3), G(m, e.init(), 5);
              case 5:
                return G(m, aB(e, d2.Xb(), d2.jb()), 6);
              case 6:
                return f = m.h, G(m, f.getManifests([d2.key()]), 7);
              case 7:
                g = m.h;
                h = g[0];
                k2 = h.sessionIds.includes(a);
                l = h.expiration == void 0 || h.expiration > b;
                if (!k2 || !l) {
                  m.B(3);
                  break;
                }
                return G(m, f.updateManifestExpiration(d2.key(), b), 3);
              case 3:
                return wa(m), G(m, e.destroy(), 10);
              case 10:
                xa(m, 0);
                break;
              case 2:
                va(m), m.B(3);
            }
          });
        };
        p.onInitialVariantChosen = function() {
        };
        p.banLocation = function() {
        };
        p.setMediaElement = function() {
        };
        Gi("application/x-offline-manifest", function() {
          return new yB();
        });
        function zB() {
        }
        function AB(a, b) {
          var c = rB(a);
          c && c.g == "manifest" ? (a = {
            uri: a,
            originalUri: a,
            data: new ArrayBuffer(0),
            headers: {
              "content-type": "application/x-offline-manifest"
            },
            originalRequest: b
          }, a = Qg(a)) : a = c && c.g == "segment" ? BB(c.key(), c, b) : Og(new U(2, 1, 9004, a));
          return a;
        }
        function BB(a, b, c) {
          var d2 = new XA();
          return Qg(void 0).cb(function() {
            return d2.init();
          }).cb(function() {
            return aB(d2, b.Xb(), b.jb());
          }).cb(function(e) {
            return e.getSegments([b.key()]);
          }).cb(function(e) {
            return {
              uri: b,
              data: e[0].data,
              headers: {},
              originalRequest: c
            };
          }).finally(function() {
            return d2.destroy();
          });
        }
        S("shaka.offline.OfflineScheme", zB);
        zB.plugin = AB;
        Xg("offline", AB);
        function CB(a, b, c) {
          var d2, e, f, g, h, k2;
          return P(function(l) {
            switch (l.g) {
              case 1:
                d2 = [];
                for (var m = [], n = t2(c), q = n.next(); !q.done; q = n.next()) {
                  q = q.value;
                  for (var r2 = false, u = t2(m), w = u.next(); !w.done; w = u.next()) if (w = w.value, DB(w.info, q)) {
                    w.sessionIds.push(q.sessionId);
                    r2 = true;
                    break;
                  }
                  r2 || m.push({
                    info: q,
                    sessionIds: [q.sessionId]
                  });
                }
                e = t2(m);
                f = e.next();
              case 2:
                if (f.done) {
                  l.B(4);
                  break;
                }
                g = f.value;
                h = EB(a, b, g);
                return G(l, h, 5);
              case 5:
                k2 = l.h;
                d2 = d2.concat(k2);
                f = e.next();
                l.B(2);
                break;
              case 4:
                return l.return(d2);
            }
          });
        }
        function EB(a, b, c) {
          var d2, e;
          return P(function(f) {
            switch (f.g) {
              case 1:
                return d2 = new Ch({
                  Bc: b,
                  onError: function() {
                  },
                  Qf: function() {
                  },
                  onExpirationUpdated: function() {
                  },
                  onEvent: function() {
                  }
                }), sa(f, 2), d2.configure(a), G(f, Kh(d2, c.info.keySystem, c.info.licenseUri, c.info.serverCertificate, c.info.audioCapabilities, c.info.videoCapabilities), 4);
              case 4:
                ua(f, 3);
                break;
              case 2:
                return va(f), G(f, d2.destroy(), 5);
              case 5:
                return f.return([]);
              case 3:
                return e = [], G(f, Promise.all(c.sessionIds.map(function(g) {
                  return P(function(h) {
                    if (h.g == 1) return sa(h, 2), G(h, Wh(d2, g), 4);
                    if (h.g != 2) return e.push(g), ua(h, 0);
                    va(h);
                    H(h);
                  });
                })), 6);
              case 6:
                return G(f, d2.destroy(), 7);
              case 7:
                return f.return(e);
            }
          });
        }
        function DB(a, b) {
          function c(d2, e) {
            return d2.robustness == e.robustness && d2.contentType == e.contentType;
          }
          return a.keySystem == b.keySystem && a.licenseUri == b.licenseUri && vd(a.audioCapabilities, b.audioCapabilities, c) && vd(a.videoCapabilities, b.videoCapabilities, c);
        }
        ;
        function FB(a, b, c) {
          var d2 = b.presentationTimeline.getDuration();
          b = GB(b);
          return {
            offlineUri: null,
            originalManifestUri: a,
            duration: d2,
            size: 0,
            expiration: Infinity,
            tracks: b,
            appMetadata: c,
            isIncomplete: false
          };
        }
        function HB(a, b) {
          var c = tB(new sB(a.Xb(), a.jb()), b), d2 = b.appMetadata || {};
          c = GB(c);
          return {
            offlineUri: a.toString(),
            originalManifestUri: b.originalManifestUri,
            duration: b.duration,
            size: b.size,
            expiration: b.expiration,
            tracks: c,
            appMetadata: d2,
            isIncomplete: b.isIncomplete || false
          };
        }
        function GB(a) {
          var b = [], c = lg(a.variants);
          c = t2(c);
          for (var d2 = c.next(); !d2.done; d2 = c.next()) b.push(cg(d2.value));
          a = t2(a.textStreams);
          for (c = a.next(); !c.done; c = a.next()) b.push(dg(c.value));
          return b;
        }
        ;
        function IB() {
          this.g = /* @__PURE__ */ new Map();
        }
        function JB(a, b) {
          var c = b.audio, d2 = b.video;
          c && !d2 && a.g.set(c.id, c.bandwidth || b.bandwidth);
          !c && d2 && a.g.set(d2.id, d2.bandwidth || b.bandwidth);
          if (c && d2) {
            var e = c.bandwidth || 393216, f = d2.bandwidth || b.bandwidth - e;
            f <= 0 && (f = b.bandwidth);
            a.g.set(c.id, e);
            a.g.set(d2.id, f);
          }
        }
        function KB(a, b) {
          a.g.set(b.id, b.bandwidth || 2048);
        }
        function LB(a, b) {
          a = a.g.get(b);
          a == null && (a = 0);
          return a;
        }
        ;
        function MB(a) {
          var b = this;
          if (a && a.constructor != Y) throw new U(2, 9, 9008);
          this.g = this.h = null;
          a ? (this.h = a.g, this.g = a.Lb()) : (this.h = Vn(), this.g = new Wg(), this.g.configure(this.h.networking));
          this.i = [];
          this.l = [];
          var c = !a;
          this.j = new ih(function() {
            var d2, e, f, g, h;
            return P(function(k2) {
              switch (k2.g) {
                case 1:
                  return G(k2, Promise.all(b.l.map(function(l) {
                    return HA(l);
                  })), 2);
                case 2:
                  d2 = function() {
                  };
                  e = [];
                  f = t2(b.i);
                  for (g = f.next(); !g.done; g = f.next()) h = g.value, e.push(h.then(d2, d2));
                  return G(k2, Promise.all(e), 3);
                case 3:
                  if (!c) {
                    k2.B(4);
                    break;
                  }
                  return G(k2, b.g.destroy(), 4);
                case 4:
                  b.h = null, b.g = null, H(k2);
              }
            });
          });
          this.m = 1e9;
        }
        function NB() {
          if (Ji(Sb())) a: {
            var a = t2(YA.values());
            for (var b = a.next(); !b.done; b = a.next()) if (b = b.value, b = b()) {
              b.destroy();
              a = true;
              break a;
            }
            a = false;
          }
          else a = false;
          return a;
        }
        p = MB.prototype;
        p.destroy = function() {
          return this.j.destroy();
        };
        p.configure = function(a, b) {
          arguments.length == 2 && typeof a == "string" && (a = Bn(a, b));
          return $n(this.h, a);
        };
        p.getConfiguration = function() {
          var a = Vn();
          $n(a, this.h, Vn());
          return a;
        };
        p.Lb = function() {
          return this.g;
        };
        p.store = function(a, b, c, d2, e) {
          var f = this, g = this.getConfiguration(), h = new GA(this.g);
          this.l.push(h);
          b = OB(this, a, b || {}, d2 || [], e || [], function() {
            var k2;
            return P(function(l) {
              if (l.g == 1) return c ? l.B(2) : G(l, Jo(a, f.g, g.manifest.retryParameters), 3);
              l.g != 2 && (c = l.h);
              k2 = Li(a, c || null);
              return l.return(k2());
            });
          }, g, h);
          b = new Ng(b, function() {
            return HA(h);
          });
          b.finally(function() {
            ud(f.l, h);
          });
          return PB(this, b);
        };
        function OB(a, b, c, d2, e, f, g, h) {
          var k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N, O;
          return P(function(Q) {
            switch (Q.g) {
              case 1:
                return QB(), l = k2 = null, m = new XA(), r2 = q = n = null, sa(Q, 2, 3), G(Q, f(), 5);
              case 5:
                return k2 = Q.h, G(Q, RB(a, b, k2, g), 6);
              case 6:
                u = Q.h;
                SB(a);
                w = !u.presentationTimeline.U() && !u.presentationTimeline.kd();
                if (!w) throw new U(2, 9, 9005, b);
                v = t2(d2);
                y = v.next();
              case 7:
                if (y.done) {
                  Q.B(9);
                  break;
                }
                z = y.value;
                return G(Q, TB(a, z, u), 10);
              case 10:
                A = Q.h;
                u.imageStreams.push(A);
                SB(a);
                y = v.next();
                Q.B(7);
                break;
              case 9:
                C = t2(e), D = C.next();
              case 11:
                if (D.done) return Mh(g.drm.clearKeys, u.variants), E = u.variants.some(function(R) {
                  if (R.audio) {
                    for (var V = t2(R.audio.drmInfos), Ba = V.next(); !Ba.done; Ba = V.next()) if (Ba.value.licenseServerUri.startsWith("data:")) return true;
                  }
                  if (R.video) {
                    for (R = t2(R.video.drmInfos), V = R.next(); !V.done; V = R.next()) if (V.value.licenseServerUri.startsWith("data:")) return true;
                  }
                  return false;
                }), I = g.offline.usePersistentLicense, E && (I = false), G(Q, a.Bd(u, function(R) {
                  r2 = r2 || R;
                }, g, I), 15);
                F = D.value;
                return G(Q, UB(a, u, F.uri, F.language, F.kind, F.mime, F.codecs), 14);
              case 14:
                B = Q.h;
                u.textStreams.push(B);
                SB(a);
                D = C.next();
                Q.B(11);
                break;
              case 15:
                l = Q.h;
                SB(a);
                if (r2) throw r2;
                return G(Q, VB(u, l, g, I), 16);
              case 16:
                return G(Q, m.init(), 17);
              case 17:
                return SB(a), G(Q, ZA(m), 18);
              case 18:
                return n = Q.h, SB(a), J = WB(l, u, b, c, g, h, I), K = J.Ll, L = J.ti, G(Q, n.jb.addManifests([K]), 19);
              case 19:
                M = Q.h;
                SB(a);
                q = M[0];
                SB(a);
                if (r2) throw r2;
                return G(Q, XB(a, L, q, K, h, g, n.jb, u, l, I), 20);
              case 20:
                return SB(a), YB(u, K, l, I), G(Q, n.jb.updateManifest(q, K), 21);
              case 21:
                return SB(a), N = new qB("manifest", n.path.Xb, n.path.jb, q), Q.return(HB(N, K));
              case 3:
                return wa(Q), G(Q, m.destroy(), 22);
              case 22:
                if (!k2) {
                  Q.B(23);
                  break;
                }
                return G(Q, k2.stop(), 23);
              case 23:
                if (!l) {
                  Q.B(25);
                  break;
                }
                return G(Q, l.destroy(), 25);
              case 25:
                xa(Q, 0);
                break;
              case 2:
                O = va(Q);
                if (q == null) {
                  Q.B(27);
                  break;
                }
                return G(Q, ZB(q), 27);
              case 27:
                throw r2 || O;
            }
          });
        }
        function XB(a, b, c, d2, e, f, g, h, k2, l) {
          var m, n, q, r2, u, w, v, y, z, A, C;
          return P(function(D) {
            switch (D.g) {
              case 1:
                m = {};
                n = 0;
                q = function() {
                  if (a.j.g || e.l) throw new U(2, 9, 7001);
                };
                r2 = function(F, B) {
                  var E, I, J, K, L, M, N, O, Q;
                  return P(function(R) {
                    if (R.g == 1) {
                      E = t2(F);
                      I = E.next();
                      for (J = {}; !I.done; J = {
                        uc: void 0
                      }, I = E.next()) J.uc = I.value, q(), K = CA(J.uc, f), L = J.uc.i, M = J.uc.h, N = /* @__PURE__ */ function(V) {
                        return function(Ba) {
                          var aa, Oa, La, Ja;
                          return P(function(Ea) {
                            switch (Ea.g) {
                              case 1:
                                aa = V.uc.g;
                                Oa = aa.fc(false);
                                if (!aa.aesKey || Oa) {
                                  Ea.B(2);
                                  break;
                                }
                                return G(Ea, Im(Ba, aa.aesKey, V.uc.j), 3);
                              case 3:
                                Ba = Ea.h;
                              case 2:
                                return La = BA(aa), G(Ea, g.addSegments([{
                                  data: Ba
                                }]), 4);
                              case 4:
                                Ja = Ea.h, q(), m[La] = Ja[0], n += Ba.byteLength, H(Ea);
                            }
                          });
                        };
                      }(J), O = J.uc.g, (Q = O.fc(false)) ? KA(e, J.uc.groupId, Q, L, M, N) : e.queue(J.uc.groupId, K, L, M, N);
                      return G(R, LA(e), 2);
                    }
                    q();
                    if (!B || e.l) return R.B(0);
                    YB(h, d2, k2, l);
                    return G(R, g.updateManifest(c, d2), 0);
                  });
                };
                u = false;
                sa(D, 2);
                if (!$B(h) || !u || aC(h)) {
                  D.B(4);
                  break;
                }
                return G(D, r2(b.filter(function(F) {
                  return F.h;
                }), true), 5);
              case 5:
                return q(), b = b.filter(function(F) {
                  return !F.h;
                }), w = m, v = n, m = {}, n = 0, G(D, bC(g, c, d2, w, v, function() {
                  return SB(a);
                }), 6);
              case 6:
                q();
              case 4:
                if (u) {
                  D.B(7);
                  break;
                }
                return G(D, r2(b, false), 8);
              case 8:
                return q(), y = m, z = n, m = {}, n = 0, G(D, bC(g, c, d2, y, z, function() {
                  return q();
                }), 9);
              case 9:
                q();
              case 7:
                ua(D, 0);
                break;
              case 2:
                return A = va(D), C = Object.values(m), G(D, g.removeSegments(C, function() {
                }), 10);
              case 10:
                throw A;
            }
          });
        }
        function ZB(a) {
          var b, c, d2, e;
          return P(function(f) {
            switch (f.g) {
              case 1:
                return b = new XA(), G(f, b.init(), 2);
              case 2:
                return G(f, ZA(b), 3);
              case 3:
                return c = f.h, d2 = new qB("manifest", c.path.Xb, c.path.jb, a), G(f, b.destroy(), 4);
              case 4:
                return e = new MB(), G(f, e.remove(d2.toString()), 0);
            }
          });
        }
        function bC(a, b, c, d2, e, f) {
          var g, h, k2, l, m, n, q, r2, u, w, v;
          return P(function(y) {
            switch (y.g) {
              case 1:
                g = false;
                sa(y, 2);
                h = true;
                k2 = t2(c.streams);
                for (l = k2.next(); !l.done; l = k2.next()) for (m = l.value, n = t2(m.segments), q = n.next(); !q.done; q = n.next()) r2 = q.value, u = r2.pendingSegmentRefId ? d2[r2.pendingSegmentRefId] : null, u != null && (r2.dataKey = u, r2.pendingSegmentRefId = void 0), u = r2.pendingInitSegmentRefId ? d2[r2.pendingInitSegmentRefId] : null, u != null && (r2.initSegmentKey = u, r2.pendingInitSegmentRefId = void 0), r2.pendingSegmentRefId && (h = false), r2.pendingInitSegmentRefId && (h = false);
                c.size += e;
                h && (c.isIncomplete = false);
                return G(y, a.updateManifest(b, c), 4);
              case 4:
                g = true;
                f();
                ua(y, 0);
                break;
              case 2:
                return w = va(y), G(y, ZB(b), 5);
              case 5:
                if (g) {
                  y.B(6);
                  break;
                }
                v = Object.values(d2);
                return G(y, a.removeSegments(v, function() {
                }), 6);
              case 6:
                throw w;
            }
          });
        }
        function VB(a, b, c, d2) {
          var e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D, F, B, E, I, J, K, L, M, N, O, Q, R;
          return P(function(V) {
            switch (V.g) {
              case 1:
                return e = {
                  width: Infinity,
                  height: Infinity
                }, Kf(a, c.restrictions, e), G(V, Nf(b, a, d2, c.drm.preferredKeySystems, c.drm.keySystemsMapping), 2);
              case 2:
                f = [];
                g = c.preferredDecodingAttributes;
                h = c.preferredVideoCodecs;
                k2 = c.preferredAudioCodecs;
                l = c.preferredTextFormats;
                If(a, h, k2, g, l);
                m = t2(a.variants);
                for (n = m.next(); !n.done; n = m.next()) q = n.value, f.push(cg(q));
                r2 = t2(a.textStreams);
                for (u = r2.next(); !u.done; u = r2.next()) w = u.value, f.push(dg(w));
                v = t2(a.imageStreams);
                for (y = v.next(); !y.done; y = v.next()) z = y.value, f.push(eg(z));
                return G(V, c.offline.trackSelectionCallback(f), 3);
              case 3:
                A = V.h;
                C = a.presentationTimeline.getDuration();
                D = 0;
                F = t2(A);
                for (B = F.next(); !B.done; B = F.next()) E = B.value, I = E.bandwidth * C / 8, D += I;
                sa(V, 4);
                return G(V, c.offline.downloadSizeCallback(D), 6);
              case 6:
                J = V.h;
                if (!J) throw new U(2, 9, 9014);
                ua(V, 5);
                break;
              case 4:
                K = va(V);
                if (K instanceof U) throw K;
                throw new U(2, 9, 9015);
              case 5:
                L = /* @__PURE__ */ new Set();
                M = /* @__PURE__ */ new Set();
                N = /* @__PURE__ */ new Set();
                O = t2(A);
                for (Q = O.next(); !Q.done; Q = O.next()) R = Q.value, R.type == "variant" && L.add(R.id), R.type == "text" && M.add(R.id), R.type == "image" && N.add(R.id);
                a.variants = a.variants.filter(function(Ba) {
                  return L.has(Ba.id);
                });
                a.textStreams = a.textStreams.filter(function(Ba) {
                  return M.has(Ba.id);
                });
                a.imageStreams = a.imageStreams.filter(function(Ba) {
                  return N.has(Ba.id);
                });
                cC(a);
                H(V);
            }
          });
        }
        function WB(a, b, c, d2, e, f, g) {
          var h = FB(c, b, d2), k2 = e.offline.progressCallback;
          IA(f, function(u, w) {
            h.size = w;
            k2(h, u);
          }, function(u, w) {
            l && g && m == w && Sh(a, "cenc", u);
          });
          var l = $B(b) && !aC(b), m = null;
          l && (m = dC.get(a.g.keySystem));
          for (var n = new IB(), q = t2(b.textStreams), r2 = q.next(); !r2.done; r2 = q.next()) n.g.set(r2.value.id, 52);
          q = t2(b.imageStreams);
          for (r2 = q.next(); !r2.done; r2 = q.next()) KB(n, r2.value);
          q = t2(b.variants);
          for (r2 = q.next(); !r2.done; r2 = q.next()) JB(n, r2.value);
          f = eC(f, n, b, e);
          e = f.streams;
          f = f.ti;
          (n = a.g) && g && (n.initData = []);
          return {
            Ll: {
              creationTime: Date.now(),
              originalManifestUri: c,
              duration: b.presentationTimeline.getDuration(),
              size: 0,
              expiration: a.ke(),
              streams: e,
              sessionIds: g ? bi(a) : [],
              drmInfo: n,
              appMetadata: d2,
              isIncomplete: true,
              sequenceMode: b.sequenceMode,
              type: b.type
            },
            ti: f
          };
        }
        function $B(a) {
          return a.variants.some(function(b) {
            var c = b.audio && b.audio.encrypted;
            return b.video && b.video.encrypted || c;
          });
        }
        function aC(a) {
          return a.variants.some(function(b) {
            return (b.video ? b.video.drmInfos : []).concat(b.audio ? b.audio.drmInfos : []).some(function(c) {
              return c.initData && c.initData.length;
            });
          });
        }
        function YB(a, b, c, d2) {
          b.expiration = c.ke();
          c = bi(c);
          b.sessionIds = d2 ? c : [];
          if ($B(a) && d2 && !c.length) throw new U(2, 9, 9007);
        }
        p.remove = function(a) {
          return fC(this, gC(this, a));
        };
        function gC(a, b) {
          var c, d2, e, f, g, h;
          return P(function(k2) {
            switch (k2.g) {
              case 1:
                QB();
                c = rB(b);
                if (c == null || c.g != "manifest") throw new U(2, 9, 9004, b);
                d2 = c;
                e = new XA();
                ta(k2, 2);
                return G(k2, e.init(), 4);
              case 4:
                return G(k2, aB(e, d2.Xb(), d2.jb()), 5);
              case 5:
                return f = k2.h, G(k2, f.getManifests([d2.key()]), 6);
              case 6:
                return g = k2.h, h = g[0], G(k2, Promise.all([hC(a, h, e), iC(f, d2, h)]), 2);
              case 2:
                return wa(k2), G(k2, e.destroy(), 8);
              case 8:
                xa(k2, 0);
            }
          });
        }
        function jC(a, b) {
          for (var c = [], d2 = t2(a.streams), e = d2.next(); !e.done; e = d2.next()) e = e.value, b && e.type == "video" ? c.push({
            contentType: ef(e.mimeType, e.codecs),
            robustness: a.drmInfo.videoRobustness
          }) : b || e.type != "audio" || c.push({
            contentType: ef(e.mimeType, e.codecs),
            robustness: a.drmInfo.audioRobustness
          });
          return c;
        }
        function hC(a, b, c) {
          return P(function(d2) {
            return G(d2, kC(a.g, a.h.drm, c, b), 0);
          });
        }
        function iC(a, b, c) {
          function d2() {
          }
          var e = lC(c);
          HB(b, c);
          return Promise.all([a.removeSegments(e, d2), a.removeManifests([b.key()], d2)]);
        }
        p.fm = function() {
          return fC(this, mC(this));
        };
        function mC(a) {
          var b, c, d2, e, f, g, h, k2, l, m;
          return P(function(n) {
            switch (n.g) {
              case 1:
                return QB(), b = a.g, c = a.h.drm, d2 = new XA(), e = false, ta(n, 2), G(n, d2.init(), 4);
              case 4:
                f = [], bB(d2, function(q) {
                  return f.push(q);
                }), g = t2(f), h = g.next();
              case 5:
                if (h.done) {
                  n.B(2);
                  break;
                }
                k2 = h.value;
                return G(n, k2.getAll(), 8);
              case 8:
                return l = n.h, G(n, CB(c, b, l), 9);
              case 9:
                return m = n.h, G(n, k2.remove(m), 10);
              case 10:
                m.length != l.length && (e = true);
                h = g.next();
                n.B(5);
                break;
              case 2:
                return wa(n), G(n, d2.destroy(), 11);
              case 11:
                xa(n, 3);
                break;
              case 3:
                return n.return(!e);
            }
          });
        }
        p.list = function() {
          return fC(this, nC());
        };
        function nC() {
          var a, b, c;
          return P(function(d2) {
            switch (d2.g) {
              case 1:
                return QB(), a = [], b = new XA(), ta(d2, 2), G(d2, b.init(), 4);
              case 4:
                return c = Promise.resolve(), $A(b, function(e, f) {
                  c = c.then(function() {
                    var g;
                    return P(function(h) {
                      if (h.g == 1) return G(h, f.getAllManifests(), 2);
                      g = h.h;
                      g.forEach(function(k2, l) {
                        k2 = HB(new qB("manifest", e.Xb, e.jb, l), k2);
                        a.push(k2);
                      });
                      H(h);
                    });
                  });
                }), G(d2, c, 2);
              case 2:
                return wa(d2), G(d2, b.destroy(), 6);
              case 6:
                xa(d2, 3);
                break;
              case 3:
                return d2.return(a);
            }
          });
        }
        function RB(a, b, c, d2) {
          var e, f, g, h, k2;
          return P(function(l) {
            if (l.g == 1) return e = null, f = a.g, g = {
              networkingEngine: f,
              filter: function() {
                return Promise.resolve();
              },
              makeTextStreamsForClosedCaptions: function() {
              },
              onTimelineRegionAdded: function() {
              },
              onEvent: function() {
              },
              onError: function(m) {
                e = m;
              },
              isLowLatencyMode: function() {
                return false;
              },
              updateDuration: function() {
              },
              newDrmInfo: function() {
              },
              onManifestUpdated: function() {
              },
              getBandwidthEstimate: function() {
                return d2.abr.defaultBandwidthEstimate;
              },
              onMetadata: function() {
              },
              disableStream: function() {
              },
              addFont: function() {
              }
            }, c.configure(d2.manifest), SB(a), G(l, c.start(b, g), 2);
            if (l.g != 3) return h = l.h, SB(a), k2 = oC(h), G(l, Promise.all(mb(k2, function(m) {
              return m.createSegmentIndex();
            })), 3);
            SB(a);
            if (e) throw e;
            return l.return(h);
          });
        }
        function TB(a, b, c) {
          var d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y;
          return P(function(z) {
            switch (z.g) {
              case 1:
                return G(z, pC(a, b), 2);
              case 2:
                d2 = z.h;
                if (d2 != "text/vtt") throw new U(1, 2, 2017, b);
                return G(z, qC(b, a.g, a.h.streaming.retryParameters), 3);
              case 3:
                e = z.h;
                f = uf(d2);
                if (!f) throw new U(2, 2, 2014, d2);
                g = f();
                h = {
                  periodStart: 0,
                  segmentStart: 0,
                  segmentEnd: c.presentationTimeline.getDuration(),
                  vttOffset: 0
                };
                k2 = Lb(e);
                l = g.parseMedia(k2, h, b, []);
                m = [];
                n = t2(l);
                q = n.next();
                for (r2 = {}; !q.done; r2 = {
                  ug: void 0,
                  Dd: void 0
                }, q = n.next()) r2.Dd = q.value, r2.ug = null, u = /* @__PURE__ */ function(A) {
                  return function() {
                    A.ug == null && (A.ug = nc([b], [A.Dd.payload]));
                    return A.ug || [];
                  };
                }(r2), w = new Cj(r2.Dd.startTime, r2.Dd.endTime, u, 0, null, null, 0, 0, Infinity), r2.Dd.payload.includes("#xywh") && (v = r2.Dd.payload.split("#xywh=")[1].split(","), v.length === 4 && w.jg({
                  height: parseInt(v[3], 10),
                  positionX: parseInt(v[0], 10),
                  positionY: parseInt(v[1], 10),
                  width: parseInt(v[2], 10)
                })), m.push(w);
                y = d2;
                if (!m.length) {
                  z.B(4);
                  break;
                }
                return G(z, Jo(m[0].T()[0], a.g, a.h.manifest.retryParameters), 5);
              case 5:
                y = z.h;
              case 4:
                return z.return({
                  id: a.m++,
                  originalId: null,
                  groupId: null,
                  createSegmentIndex: function() {
                    return Promise.resolve();
                  },
                  segmentIndex: new Zl(m),
                  mimeType: y || "",
                  codecs: "",
                  kind: "",
                  encrypted: false,
                  drmInfos: [],
                  keyIds: /* @__PURE__ */ new Set(),
                  language: "und",
                  originalLanguage: null,
                  label: null,
                  type: "image",
                  primary: false,
                  trickModeVideo: null,
                  dependencyStream: null,
                  emsgSchemeIdUris: null,
                  roles: [],
                  forced: false,
                  channelsCount: null,
                  audioSamplingRate: null,
                  spatialAudio: false,
                  closedCaptions: null,
                  tilesLayout: "1x1",
                  accessibilityPurpose: null,
                  external: true,
                  fastSwitching: false,
                  fullMimeTypes: /* @__PURE__ */ new Set([ef(y || "", "")]),
                  isAudioMuxedInVideo: false,
                  baseOriginalId: null
                });
            }
          });
        }
        function UB(a, b, c, d2, e, f, g) {
          var h, k2, l;
          return P(function(m) {
            if (m.g == 1) return f ? m.B(2) : G(m, pC(a, c), 3);
            m.g != 2 && (f = m.h);
            h = {
              id: a.m++,
              originalId: null,
              groupId: null,
              createSegmentIndex: function() {
                return Promise.resolve();
              },
              segmentIndex: am(0, b.presentationTimeline.getDuration(), [c]),
              mimeType: f || "",
              codecs: g || "",
              kind: e,
              encrypted: false,
              drmInfos: [],
              keyIds: /* @__PURE__ */ new Set(),
              language: d2,
              originalLanguage: d2,
              label: null,
              type: tc,
              primary: false,
              trickModeVideo: null,
              dependencyStream: null,
              emsgSchemeIdUris: null,
              roles: [],
              forced: false,
              channelsCount: null,
              audioSamplingRate: null,
              spatialAudio: false,
              closedCaptions: null,
              accessibilityPurpose: null,
              external: true,
              fastSwitching: false,
              fullMimeTypes: /* @__PURE__ */ new Set([ef(f || "", g || "")]),
              isAudioMuxedInVideo: false,
              baseOriginalId: null
            };
            k2 = ef(h.mimeType, h.codecs);
            l = vf(k2);
            if (!l) throw new U(2, 2, 2014, f);
            return m.return(h);
          });
        }
        function pC(a, b) {
          var c;
          return P(function(d2) {
            switch (d2.g) {
              case 1:
                return sa(d2, 2), G(d2, Jo(b, a.g, a.h.streaming.retryParameters), 4);
              case 4:
                c = d2.h;
                ua(d2, 3);
                break;
              case 2:
                va(d2);
              case 3:
                if (c) return d2.return(c);
                throw new U(1, 2, 2011, b);
            }
          });
        }
        function qC(a, b, c) {
          var d2, e, f;
          return P(function(g) {
            if (g.g == 1) return d2 = gh, e = ah([a], c), e.method = "GET", G(g, b.request(d2, e).promise, 2);
            f = g.h;
            return g.return(f.data);
          });
        }
        p.Bd = function(a, b, c, d2) {
          var e = this, f;
          return P(function(g) {
            return g.g == 1 ? (f = new Ch({
              Bc: e.g,
              onError: b,
              Qf: function() {
              },
              onExpirationUpdated: function() {
              },
              onEvent: function() {
              }
            }), f.configure(c.drm), G(g, Hh(f, a.variants, d2), 2)) : g.g != 3 ? G(g, Uh(f), 3) : g.return(f);
          });
        };
        function eC(a, b, c, d2) {
          var e = /* @__PURE__ */ new Map(), f = oC(c), g = /* @__PURE__ */ new Map();
          f = t2(f);
          for (var h = f.next(); !h.done; h = f.next()) {
            h = h.value;
            var k2 = rC(a, b, c, h, d2, e);
            g.set(h.id, k2);
          }
          a = t2(c.variants);
          for (b = a.next(); !b.done; b = a.next()) b = b.value, b.audio && g.get(b.audio.id).variantIds.push(b.id), b.video && g.get(b.video.id).variantIds.push(b.id);
          return {
            streams: Array.from(g.values()),
            ti: Array.from(e.values())
          };
        }
        function rC(a, b, c, d2, e, f) {
          var g = {
            id: d2.id,
            originalId: d2.originalId,
            groupId: d2.groupId,
            primary: d2.primary,
            type: d2.type,
            mimeType: d2.mimeType,
            codecs: d2.codecs,
            frameRate: d2.frameRate,
            pixelAspectRatio: d2.pixelAspectRatio,
            hdr: d2.hdr,
            colorGamut: d2.colorGamut,
            videoLayout: d2.videoLayout,
            kind: d2.kind,
            language: d2.language,
            originalLanguage: d2.originalLanguage,
            label: d2.label,
            width: d2.width || null,
            height: d2.height || null,
            encrypted: d2.encrypted,
            keyIds: d2.keyIds,
            segments: [],
            variantIds: [],
            roles: d2.roles,
            forced: d2.forced,
            channelsCount: d2.channelsCount,
            audioSamplingRate: d2.audioSamplingRate,
            spatialAudio: d2.spatialAudio,
            closedCaptions: d2.closedCaptions,
            tilesLayout: d2.tilesLayout,
            mssPrivateData: d2.mssPrivateData,
            external: d2.external,
            fastSwitching: d2.fastSwitching,
            isAudioMuxedInVideo: d2.isAudioMuxedInVideo
          }, h = e.offline.numberOfParallelDownloads, k2 = h === 0 ? d2.id : 0;
          sC(d2, c.presentationTimeline.Nb(), function(l, m) {
            var n = BA(l), q = void 0;
            if (!f.has(n)) {
              var r2 = l.endTime - l.startTime;
              r2 = LB(b, d2.id) * r2;
              r2 = EA(a.g, r2);
              f.set(n, new AA(l, r2, k2, false, m));
            }
            l.ha && (q = BA(l.ha), f.has(q) || (r2 = LB(b, d2.id) * 0.5, r2 = EA(a.g, r2), f.set(q, new AA(l.ha, r2, k2, true, m))));
            g.segments.push({
              pendingInitSegmentRefId: q,
              initSegmentKey: q ? 0 : null,
              startTime: l.startTime,
              endTime: l.endTime,
              appendWindowStart: l.appendWindowStart,
              appendWindowEnd: l.appendWindowEnd,
              timestampOffset: l.timestampOffset,
              tilesLayout: l.tilesLayout,
              pendingSegmentRefId: n,
              dataKey: 0,
              mimeType: l.mimeType,
              codecs: l.codecs,
              thumbnailSprite: l.thumbnailSprite
            });
            h !== 0 && (k2 = (k2 + 1) % h);
          });
          return g;
        }
        function sC(a, b, c) {
          b = a.segmentIndex.find(b);
          if (b != null) for (var d2 = a.segmentIndex.get(b); d2; ) c(d2, b), d2 = a.segmentIndex.get(++b);
        }
        function SB(a) {
          if (a.j.g) throw new U(2, 9, 7001);
        }
        function QB() {
          if (!NB()) throw new U(2, 9, 9e3);
        }
        function fC(a, b) {
          return P(function(c) {
            if (c.g == 1) return a.i.push(b), ta(c, 2), G(c, b, 4);
            if (c.g != 2) return c.return(c.h);
            wa(c);
            ud(a.i, b);
            return xa(c, 0);
          });
        }
        function PB(a, b) {
          var c = b.promise;
          a.i.push(c);
          return b.finally(function() {
            ud(a.i, c);
          });
        }
        function lC(a) {
          var b = /* @__PURE__ */ new Set();
          a = t2(a.streams);
          for (var c = a.next(); !c.done; c = a.next()) {
            c = t2(c.value.segments);
            for (var d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, d2.initSegmentKey != null && b.add(d2.initSegmentKey), b.add(d2.dataKey);
          }
          return Array.from(b);
        }
        function kC(a, b, c, d2) {
          var e, f, g;
          return P(function(h) {
            if (h.g == 1) {
              if (!d2.drmInfo) return h.return();
              e = cB(c);
              f = d2.sessionIds.map(function(k2) {
                return {
                  sessionId: k2,
                  keySystem: d2.drmInfo.keySystem,
                  licenseUri: d2.drmInfo.licenseServerUri,
                  serverCertificate: d2.drmInfo.serverCertificate,
                  audioCapabilities: jC(d2, false),
                  videoCapabilities: jC(d2, true)
                };
              });
              return G(h, CB(b, a, f), 2);
            }
            return h.g != 3 ? (g = h.h, G(h, e.remove(g), 3)) : G(h, e.add(f.filter(function(k2) {
              return !g.includes(k2.sessionId);
            })), 0);
          });
        }
        function oC(a) {
          for (var b = /* @__PURE__ */ new Set(), c = t2(a.variants), d2 = c.next(); !d2.done; d2 = c.next()) d2 = d2.value, d2.audio && b.add(d2.audio), d2.video && b.add(d2.video);
          c = t2(a.textStreams);
          for (d2 = c.next(); !d2.done; d2 = c.next()) b.add(d2.value);
          a = t2(a.imageStreams);
          for (c = a.next(); !c.done; c = a.next()) b.add(c.value);
          return b;
        }
        function cC(a) {
          a.variants.map(function(f) {
            return f.video;
          });
          var b = new Set(a.variants.map(function(f) {
            return f.audio;
          }));
          a = a.textStreams;
          for (var c = t2(b), d2 = c.next(); !d2.done; d2 = c.next()) {
            d2 = t2(b);
            for (var e = d2.next(); !e.done; e = d2.next()) ;
          }
          b = t2(a);
          for (c = b.next(); !c.done; c = b.next()) for (c = t2(a), d2 = c.next(); !d2.done; d2 = c.next()) ;
        }
        S("shaka.offline.Storage", MB);
        MB.deleteAll = function() {
          var a;
          return P(function(b) {
            return b.g == 1 ? (a = new XA(), ta(b, 2), G(b, dB(a), 2)) : b.g != 5 ? (wa(b), G(b, a.destroy(), 5)) : xa(b, 0);
          });
        };
        MB.prototype.list = MB.prototype.list;
        MB.prototype.removeEmeSessions = MB.prototype.fm;
        MB.prototype.remove = MB.prototype.remove;
        MB.prototype.store = MB.prototype.store;
        MB.prototype.getNetworkingEngine = MB.prototype.Lb;
        MB.prototype.getConfiguration = MB.prototype.getConfiguration;
        MB.prototype.configure = MB.prototype.configure;
        MB.prototype.destroy = MB.prototype.destroy;
        MB.support = NB;
        var dC = (/* @__PURE__ */ new Map()).set("org.w3.clearkey", "1077efecc0b24d02ace33c1e52e2fb4b").set("com.widevine.alpha", "edef8ba979d64acea3c827dcd51d21ed").set("com.microsoft.playready", "9a04f07998404286ab92e65be0885f95").set("com.microsoft.playready.recommendation", "9a04f07998404286ab92e65be0885f95").set("com.microsoft.playready.software", "9a04f07998404286ab92e65be0885f95").set("com.microsoft.playready.hardware", "9a04f07998404286ab92e65be0885f95").set("com.huawei.wiseplay", "3d5e6d359b9a41e8b843dd3c6e72c42c");
        vq("offline", NB);
        function tC() {
        }
        function uC() {
          for (var a = t2(vC), b = a.next(); !b.done; b = a.next()) {
            b = b.value;
            try {
              b.callback();
            } catch (c) {
              bb("Error installing polyfill!", c);
            }
          }
        }
        function wC(a, b) {
          a = {
            priority: b || 0,
            callback: a
          };
          for (b = 0; b < vC.length; b++) if (vC[b].priority < a.priority) {
            vC.splice(b, 0, a);
            return;
          }
          vC.push(a);
        }
        S("shaka.polyfill", tC);
        tC.register = wC;
        tC.installAll = uC;
        var vC = [];
        function xC() {
        }
        function yC() {
          if (!Object.getOwnPropertyDescriptor(Element.prototype, "ariaHidden")) for (var a = t2(["ariaHidden", "ariaLabel", "ariaPressed", "ariaSelected"]), b = a.next(); !b.done; b = a.next()) zC(b.value);
        }
        function zC(a) {
          var b = "aria-" + a.toLowerCase().replace(/^aria/, "");
          Object.defineProperty(Element.prototype, a, {
            get: function() {
              return this.getAttribute(b);
            },
            set: function(c) {
              c == null || c == void 0 ? this.removeAttribute(b) : this.setAttribute(b, c);
            }
          });
        }
        tC.Aria = xC;
        xC.install = yC;
        wC(yC);
        function AC(a, b, c) {
          this.g = a;
          this.i = b || null;
          this.h = c || null;
          this.keySystem = a.keySystem;
        }
        AC.prototype.getConfiguration = function() {
          var a = this.g.getConfiguration();
          if (a.videoCapabilities) for (var b = t2(a.videoCapabilities), c = b.next(); !c.done; c = b.next()) c.value.encryptionScheme = this.i;
          if (a.audioCapabilities) for (b = t2(a.audioCapabilities), c = b.next(); !c.done; c = b.next()) c.value.encryptionScheme = this.h;
          return a;
        };
        AC.prototype.createMediaKeys = function() {
          return this.g.createMediaKeys();
        };
        function BC(a) {
          if (a.startsWith("com.apple")) return "cbcs";
          if (a.startsWith("com.widevine") || a.startsWith("com.microsoft") || a.startsWith("com.chromecast") || a.startsWith("org.w3") || a.startsWith("com.huawei")) return "cenc";
          bb("EmeEncryptionSchemePolyfill: Unknown key system:", a, "Please contribute!");
          return null;
        }
        function CC(a) {
          if (!a) return false;
          a = a.getConfiguration();
          var b = a.audioCapabilities && a.audioCapabilities[0];
          return (a = a.videoCapabilities && a.videoCapabilities[0] || b) && a.encryptionScheme !== void 0 ? true : false;
        }
        function DC(a, b) {
          return !a || a == b || (a == "cbcs" || a == "cbcs-1-9") && Sb().sd() ? true : false;
        }
        ;
        function EC() {
        }
        var FC;
        function GC() {
          Sb().lg() && !FC && !navigator.emeEncryptionSchemePolyfilled && navigator.requestMediaKeySystemAccess && MediaKeySystemAccess.prototype.getConfiguration && (FC = navigator.requestMediaKeySystemAccess, navigator.requestMediaKeySystemAccess = HC, navigator.emeEncryptionSchemePolyfilled = true);
        }
        function HC(a, b) {
          var c = this, d2, e;
          return P(function(f) {
            if (f.g == 1) return G(f, FC.call(c, a, b), 2);
            d2 = f.h;
            if (e = CC(d2)) return navigator.requestMediaKeySystemAccess = FC, f.return(d2);
            navigator.requestMediaKeySystemAccess = IC;
            return f.return(IC.call(c, a, b));
          });
        }
        function IC(a, b) {
          var c = this, d2, e, f, g, h, k2, l, m, n, q, r2, u;
          return P(function(w) {
            if (w.g == 1) {
              d2 = BC(a);
              e = [];
              f = t2(b);
              for (g = f.next(); !g.done; g = f.next()) h = g.value, k2 = JC(h.videoCapabilities, d2), l = JC(h.audioCapabilities, d2), h.videoCapabilities && h.videoCapabilities.length && !k2.length || h.audioCapabilities && h.audioCapabilities.length && !l.length || (m = Object.assign({}, h), m.videoCapabilities = k2, m.audioCapabilities = l, e.push(m));
              if (!e.length) throw n = Error("Unsupported keySystem or supportedConfigurations."), n.name = "NotSupportedError", n.code = DOMException.NOT_SUPPORTED_ERR, n;
              return G(w, FC.call(c, a, e), 2);
            }
            q = w.h;
            u = r2 = null;
            e[0] && (e[0].videoCapabilities && (r2 = e[0].videoCapabilities[0].encryptionScheme), e[0].audioCapabilities && (u = e[0].audioCapabilities[0].encryptionScheme));
            return w.return(new AC(q, r2, u));
          });
        }
        function JC(a, b) {
          return a ? a.filter(function(c) {
            return DC(c.encryptionScheme, b);
          }) : a;
        }
        tC.EmeEncryptionScheme = EC;
        EC.install = GC;
        wC(GC);
        function KC() {
        }
        function LC() {
          if (window7.Document) {
            var a = Element.prototype;
            a.requestFullscreen = a.requestFullscreen || a.mozRequestFullScreen || a.msRequestFullscreen || a.webkitRequestFullscreen;
            a = Document.prototype;
            a.exitFullscreen = a.exitFullscreen || a.mozCancelFullScreen || a.msExitFullscreen || a.webkitCancelFullScreen;
            "fullscreenElement" in document || (Object.defineProperty(document, "fullscreenElement", {
              get: function() {
                return document.mozFullScreenElement || document.msFullscreenElement || document.webkitCurrentFullScreenElement || document.webkitFullscreenElement;
              }
            }), Object.defineProperty(document, "fullscreenEnabled", {
              get: function() {
                return document.mozFullScreenEnabled || document.msFullscreenEnabled || document.webkitFullscreenEnabled;
              }
            }));
            document.addEventListener("webkitfullscreenchange", MC);
            document.addEventListener("webkitfullscreenerror", MC);
            document.addEventListener("mozfullscreenchange", MC);
            document.addEventListener("mozfullscreenerror", MC);
            document.addEventListener("MSFullscreenChange", MC);
            document.addEventListener("MSFullscreenError", MC);
          }
        }
        function MC(a) {
          var b = a.type.replace(/^(webkit|moz|MS)/, "").toLowerCase(), c = document.createEvent("Event");
          c.initEvent(b, a.bubbles, a.cancelable);
          a.target.dispatchEvent(c);
        }
        tC.Fullscreen = KC;
        KC.install = LC;
        wC(LC);
        function NC() {
        }
        var OC;
        function PC() {
          Sb().lg() && !OC && !navigator.mediaCapabilitiesEncryptionSchemePolyfilled && navigator.mediaCapabilities && (OC = navigator.mediaCapabilities.decodingInfo, navigator.mediaCapabilities.decodingInfo = QC, navigator.mediaCapabilitiesEncryptionSchemePolyfilled = true);
        }
        function QC(a) {
          var b = this, c, d2, e;
          return P(function(f) {
            switch (f.g) {
              case 1:
                return G(f, OC.call(b, a), 2);
              case 2:
                c = f.h;
                if (!c.supported || !a.keySystemConfiguration) return f.return(c);
                d2 = c.keySystemAccess;
                if (e = CC(d2)) return navigator.mediaCapabilities.decodingInfo = OC, f.return(c);
                navigator.mediaCapabilities.decodingInfo = RC;
                if (d2) {
                  f.B(3);
                  break;
                }
                return G(f, SC(a), 4);
              case 4:
                return c.keySystemAccess = f.h, f.return(c);
              case 3:
                return f.return(RC.call(b, a));
            }
          });
        }
        function RC(a) {
          var b = this, c, d2, e, f, g, h, k2;
          return P(function(l) {
            switch (l.g) {
              case 1:
                return d2 = c = null, !a.keySystemConfiguration || (e = a.keySystemConfiguration, f = e.keySystem, d2 = e.audio && e.audio.encryptionScheme, c = e.video && e.video.encryptionScheme, g = BC(f), h = {
                  powerEfficient: false,
                  smooth: false,
                  supported: false,
                  keySystemAccess: null,
                  configuration: a
                }, DC(d2, g) && DC(c, g)) ? G(l, OC.call(b, a), 2) : l.return(h);
              case 2:
                k2 = l.h;
                if (k2.keySystemAccess) {
                  k2.keySystemAccess = new AC(k2.keySystemAccess, c, d2);
                  l.B(3);
                  break;
                }
                if (!a.keySystemConfiguration) {
                  l.B(3);
                  break;
                }
                return G(l, SC(a), 5);
              case 5:
                k2.keySystemAccess = l.h;
              case 3:
                return l.return(k2);
            }
          });
        }
        function SC(a) {
          var b, c;
          return P(function(d2) {
            if (d2.g == 1) {
              var e = a.keySystemConfiguration, f = [], g = [];
              e.audio && f.push({
                robustness: e.audio.robustness || "",
                contentType: a.audio.contentType,
                encryptionScheme: e.audio.encryptionScheme
              });
              e.video && g.push({
                robustness: e.video.robustness || "",
                contentType: a.video.contentType,
                encryptionScheme: e.video.encryptionScheme
              });
              e = {
                initDataTypes: e.initDataType ? [e.initDataType] : [],
                distinctiveIdentifier: e.distinctiveIdentifier,
                persistentState: e.persistentState,
                sessionTypes: e.sessionTypes
              };
              f.length && (e.audioCapabilities = f);
              g.length && (e.videoCapabilities = g);
              b = e;
              return G(d2, navigator.requestMediaKeySystemAccess(a.keySystemConfiguration.keySystem, [b]), 2);
            }
            c = d2.h;
            return d2.return(c);
          });
        }
        tC.MCapEncryptionScheme = NC;
        NC.install = PC;
        wC(PC, -2);
        function TC() {
        }
        function UC() {
          Sb().mc() || (navigator.mediaCapabilities || (navigator.mediaCapabilities = {}), TC.originalMcap = navigator.mediaCapabilities, navigator.mediaCapabilities.decodingInfo = VC);
        }
        function VC(a) {
          var b, c, d2, e, f, g, h, k2, l, m, n;
          return P(function(q) {
            switch (q.g) {
              case 1:
                b = {
                  supported: false,
                  powerEfficient: true,
                  smooth: true,
                  keySystemAccess: null,
                  configuration: a
                };
                Sb();
                c = a.video;
                d2 = a.audio;
                if (a.type != "media-source") {
                  if (a.type == "file") {
                    if (c && (e = c.contentType, f = Ki().canPlayType(e) != "", !f) || d2 && (g = d2.contentType, h = Ki().canPlayType(g) != "", !h)) return q.return(b);
                  } else return q.return(b);
                  q.B(2);
                  break;
                }
                if (!Ji()) return q.return(b);
                if (!c) {
                  q.B(3);
                  break;
                }
                return G(q, WC(c), 4);
              case 4:
                if (k2 = q.h, !k2) return q.return(b);
              case 3:
                if (d2) {
                  var r2 = Sb().Ka(), u = d2.contentType;
                  r2 === "CAST" && d2.spatialRendering && (u += "; spatialRendering=true");
                  l = dd(u);
                  if (!l) return q.return(b);
                }
              case 2:
                if (!a.keySystemConfiguration) return b.supported = true, q.return(b);
                m = a.keySystemConfiguration;
                return G(q, XC(c, d2, m), 6);
              case 6:
                if (n = q.h) b.supported = true, b.keySystemAccess = n;
              case 5:
                return q.return(b);
            }
          });
        }
        function WC(a) {
          var b, c, d2;
          return P(function(e) {
            return e.g == 1 ? (b = Sb(), c = b.Ka(), c !== "CAST" ? e.B(2) : G(e, YC(a), 3)) : e.g != 2 ? (d2 = e.h, e.return(d2)) : e.return(dd(a.contentType));
          });
        }
        function XC(a, b, c) {
          var d2, e, f, g, h, k2, l, m, n, q, r2;
          return P(function(u) {
            switch (u.g) {
              case 1:
                d2 = [];
                e = [];
                c.audio && (f = {
                  robustness: c.audio.robustness || "",
                  contentType: b.contentType
                }, Sb().mj() && b.contentType.includes('codecs="ac-3"') && (f.contentType = 'audio/mp4; codecs="ec-3"'), c.audio.encryptionScheme && (f.encryptionScheme = c.audio.encryptionScheme), d2.push(f));
                c.video && (g = {
                  robustness: c.video.robustness || "",
                  contentType: a.contentType
                }, c.video.encryptionScheme && (g.encryptionScheme = c.video.encryptionScheme), e.push(g));
                h = {
                  initDataTypes: [c.initDataType],
                  distinctiveIdentifier: c.distinctiveIdentifier,
                  persistentState: c.persistentState,
                  sessionTypes: c.sessionTypes
                };
                d2.length && (h.audioCapabilities = d2);
                e.length && (h.videoCapabilities = e);
                k2 = a ? a.contentType : "";
                l = b ? b.contentType : "";
                m = nf(k2) + ";" + mf(k2);
                n = nf(l) + ";" + mf(l);
                q = c.keySystem;
                r2 = null;
                sa(u, 2);
                if (Ig.has(m + "#" + n + "#" + q)) {
                  r2 = Ig.get(m + "#" + n + "#" + q) || null;
                  u.B(4);
                  break;
                }
                return G(u, navigator.requestMediaKeySystemAccess(c.keySystem, [h]), 5);
              case 5:
                r2 = u.h, Ig.set(m + "#" + n + "#" + q, r2);
              case 4:
                ua(u, 3);
                break;
              case 2:
                va(u);
              case 3:
                return u.return(r2);
            }
          });
        }
        function YC(a) {
          var b, c, d2, e, f;
          return P(function(g) {
            if (g.g == 1) {
              if (!(window7.cast && cast.__platform__ && cast.__platform__.canDisplayType)) return g.return(dd(a.contentType));
              b = a.contentType;
              a.width && a.height && a.width > 1280 && a.height > 720 && (b += "; width=" + a.width + "; height=" + a.height);
              a.framerate && (c = Math.round(a.framerate), c < 24 || c > 30) && (b += "; framerate=" + a.framerate);
              d2 = a.transferFunction || "";
              switch (d2) {
                case "":
                case "srgb":
                  break;
                case "pq":
                  b += "; eotf=smpte2084";
                  break;
                case "hlg":
                  b += "; eotf=arib-std-b67";
                  break;
                default:
                  return g.return(false);
              }
              e = false;
              f = ZC;
              return f.has(b) ? (e = f.get(b), g.B(2)) : G(g, cast.__platform__.canDisplayType(b), 3);
            }
            g.g != 2 && (e = g.h, f.set(b, e));
            return g.return(e);
          });
        }
        tC.MediaCapabilities = TC;
        TC.install = UC;
        TC.originalMcap = null;
        var ZC = /* @__PURE__ */ new Map();
        wC(UC, -1);
        function $C() {
        }
        function aD() {
          var a = Sb(), b = a.Ga() === "WEBKIT" ? a.Fa() : null;
          (window7.MediaSource || window7.ManagedMediaSource) && b && window7.MediaSource && (b <= 12 ? (bD(), cD()) : b <= 15 && bD());
          a = t2(a.wj());
          for (b = a.next(); !b.done; b = a.next()) dD(b.value);
          (window7.MediaSource || window7.ManagedMediaSource) && eD();
          window7.MediaSource && MediaSource.isTypeSupported('video/webm; codecs="vp9"') && !MediaSource.isTypeSupported('video/webm; codecs="vp09.00.10.08"') && fD();
        }
        function bD() {
          var a = MediaSource.prototype.addSourceBuffer;
          MediaSource.prototype.addSourceBuffer = function() {
            var b = a.apply(this, Na.apply(0, arguments));
            b.abort = function() {
            };
            return b;
          };
        }
        function cD() {
          var a = SourceBuffer.prototype.remove;
          SourceBuffer.prototype.remove = function(b, c) {
            return a.call(this, b, c - 1e-3);
          };
        }
        function eD() {
          if (window7.MediaSource) {
            var a = MediaSource.isTypeSupported.bind(MediaSource);
            MediaSource.isTypeSupported = function(c) {
              return jf(c) != "mp2t" && a(c);
            };
          }
          if (window7.ManagedMediaSource) {
            var b = ManagedMediaSource.isTypeSupported.bind(ManagedMediaSource);
            window7.ManagedMediaSource.isTypeSupported = function(c) {
              return jf(c) != "mp2t" && b(c);
            };
          }
        }
        function dD(a) {
          var b = MediaSource.isTypeSupported.bind(MediaSource);
          MediaSource.isTypeSupported = function(d2) {
            return mf(d2) != a && b(d2);
          };
          if (window7.ManagedMediaSource) {
            var c = ManagedMediaSource.isTypeSupported.bind(ManagedMediaSource);
            window7.ManagedMediaSource.isTypeSupported = function(d2) {
              return mf(d2) != a && c(d2);
            };
          }
        }
        function fD() {
          var a = MediaSource.isTypeSupported;
          Sb().Yj() && (MediaSource.isTypeSupported = function(b) {
            var c = b.split(/ *; */), d2 = c.findIndex(function(g) {
              return g.startsWith("codecs=");
            });
            if (d2 < 0) return a(b);
            var e = c[d2].replace("codecs=", "").replace(/"/g, "").split(/\s*,\s*/), f = e.findIndex(function(g) {
              return g.startsWith("vp09");
            });
            f >= 0 && (e[f] = "vp9", c[d2] = 'codecs="' + e.join(",") + '"', b = c.join("; "));
            return a(b);
          });
        }
        tC.MediaSource = $C;
        $C.install = aD;
        wC(aD);
        function gD() {
        }
        function hD() {
          screen.orientation && screen.orientation.unlock || (screen.orientation != void 0 ? iD() : window7.orientation != void 0 && jD());
        }
        function iD() {
          screen.orientation.lock === void 0 && (screen.orientation.lock = function() {
            return Promise.resolve();
          });
          screen.orientation.unlock === void 0 && (screen.orientation.unlock = function() {
          });
        }
        function jD() {
          function a() {
            switch (window7.orientation) {
              case -90:
                b.type = "landscape-secondary";
                b.angle = 270;
                break;
              case 0:
                b.type = "portrait-primary";
                b.angle = 0;
                break;
              case 90:
                b.type = "landscape-primary";
                b.angle = 90;
                break;
              case 180:
                b.type = "portrait-secondary", b.angle = 180;
            }
          }
          var b = new kD();
          screen.orientation = b;
          a();
          window7.addEventListener("orientationchange", function() {
            a();
            var c = new T("change");
            b.dispatchEvent(c);
          });
        }
        tC.Orientation = gD;
        gD.install = hD;
        function kD() {
          lb.call(this);
          this.type = "";
          this.angle = 0;
        }
        ma(kD, lb);
        kD.prototype.lock = function(a) {
          function b(d2) {
            return screen.lockOrientation ? screen.lockOrientation(d2) : screen.mozLockOrientation ? screen.mozLockOrientation(d2) : screen.msLockOrientation ? screen.msLockOrientation(d2) : false;
          }
          var c = false;
          switch (a) {
            case "natural":
              c = b("default");
              break;
            case "any":
              c = true;
              this.unlock();
              break;
            default:
              c = b(a);
          }
          if (c) return Promise.resolve();
          a = Error("screen.orientation.lock() is not available on this device");
          a.name = "NotSupportedError";
          a.code = DOMException.NOT_SUPPORTED_ERR;
          return Promise.reject(a);
        };
        kD.prototype.unlock = function() {
          screen.unlockOrientation ? screen.unlockOrientation() : screen.mozUnlockOrientation ? screen.mozUnlockOrientation() : screen.msUnlockOrientation && screen.msUnlockOrientation();
        };
        wC(hD);
        function lD() {
        }
        var mD, nD, oD, pD, qD, rD;
        function sD(a) {
          if (window7.HTMLVideoElement && window7.WebKitMediaKeys && window7.shakaMediaKeysPolyfill != tD) {
            if (a === void 0 ? 0 : a) mD = true, nD = Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype, "mediaKeys"), oD = HTMLMediaElement.prototype.setMediaKeys, pD = window7.MediaKeys, qD = window7.MediaKeySystemAccess, rD = navigator.requestMediaKeySystemAccess;
            delete HTMLMediaElement.prototype.mediaKeys;
            HTMLMediaElement.prototype.mediaKeys = null;
            HTMLMediaElement.prototype.setMediaKeys = uD;
            window7.MediaKeys = vD;
            window7.MediaKeySystemAccess = wD;
            navigator.requestMediaKeySystemAccess = xD;
            window7.shakaMediaKeysPolyfill = tD;
            Vf.clear();
            Ig.clear();
          }
        }
        function xD(a, b) {
          try {
            var c = new wD(a, b);
            return Promise.resolve(c);
          } catch (d2) {
            return Promise.reject(d2);
          }
        }
        function uD(a) {
          var b = this.mediaKeys;
          b && b != a && yD(b, null);
          delete this.mediaKeys;
          return (this.mediaKeys = a) ? yD(a, this) : Promise.resolve();
        }
        function zD(a) {
          a = Lb(a.initData);
          if (Pb(a).getUint32(0, true) + 4 != a.byteLength) throw new RangeError("Malformed FairPlay init data");
          a = Yb(a.subarray(4), true);
          a = ac(a);
          var b = new Event("encrypted");
          b.initDataType = "skd";
          b.initData = Mb(a);
          this.dispatchEvent(b);
        }
        tC.PatchedMediaKeysApple = lD;
        lD.uninstall = function() {
          window7.shakaMediaKeysPolyfill == tD && mD && (mD = false, Object.defineProperty(HTMLMediaElement.prototype, "mediaKeys", nD), HTMLMediaElement.prototype.setMediaKeys = oD, window7.MediaKeys = pD, window7.MediaKeySystemAccess = qD, navigator.requestMediaKeySystemAccess = rD, nD = rD = oD = qD = pD = null, window7.shakaMediaKeysPolyfill = "", Vf.clear(), Ig.clear());
        };
        lD.install = sD;
        function wD(a, b) {
          this.keySystem = a;
          if (a.startsWith("com.apple.fps")) for (a = t2(b), b = a.next(); !b.done; b = a.next()) {
            var c = b.value;
            if (c.persistentState == "required") b = null;
            else {
              b = {
                audioCapabilities: [],
                videoCapabilities: [],
                persistentState: "optional",
                distinctiveIdentifier: "optional",
                initDataTypes: c.initDataTypes,
                sessionTypes: ["temporary"],
                label: c.label
              };
              var d2 = false, e = false;
              if (c.audioCapabilities) for (var f = t2(c.audioCapabilities), g = f.next(); !g.done; g = f.next()) g = g.value, g.contentType && (d2 = true, WebKitMediaKeys.isTypeSupported(this.keySystem, g.contentType.split(";")[0]) && (b.audioCapabilities.push(g), e = true));
              if (c.videoCapabilities) for (c = t2(c.videoCapabilities), f = c.next(); !f.done; f = c.next()) f = f.value, f.contentType && (d2 = true, WebKitMediaKeys.isTypeSupported(this.keySystem, f.contentType.split(";")[0]) && (b.videoCapabilities.push(f), e = true));
              d2 || (e = WebKitMediaKeys.isTypeSupported(this.keySystem, "video/mp4"));
              b = e ? b : null;
            }
            if (b) {
              this.g = b;
              return;
            }
          }
          a = Error("Unsupported keySystem");
          a.name = "NotSupportedError";
          a.code = DOMException.NOT_SUPPORTED_ERR;
          throw a;
        }
        wD.prototype.createMediaKeys = function() {
          var a = new vD(this.keySystem);
          return Promise.resolve(a);
        };
        wD.prototype.getConfiguration = function() {
          return this.g;
        };
        function vD(a) {
          this.h = new WebKitMediaKeys(a);
          this.g = new Qc();
        }
        vD.prototype.createSession = function(a) {
          a = a || "temporary";
          if (a != "temporary") throw new TypeError("Session type " + a + " is unsupported on this platform.");
          return new AD(this.h, a);
        };
        vD.prototype.setServerCertificate = function() {
          return Promise.resolve(false);
        };
        function yD(a, b) {
          a.g.Ta();
          if (!b) return Promise.resolve();
          a.g.o(b, "webkitneedkey", zD);
          try {
            return Il(b, HTMLMediaElement.HAVE_METADATA, a.g, function() {
              b.webkitSetMediaKeys(a.h);
            }), Promise.resolve();
          } catch (c) {
            return Promise.reject(c);
          }
        }
        vD.prototype.getStatusForPolicy = function() {
          return Promise.resolve("usable");
        };
        function AD(a) {
          lb.call(this);
          this.i = null;
          this.l = a;
          this.g = this.h = null;
          this.j = new Qc();
          this.sessionId = "";
          this.expiration = NaN;
          this.closed = new Mg();
          this.keyStatuses = new BD();
          this.onkeystatuseschange = null;
        }
        ma(AD, lb);
        p = AD.prototype;
        p.generateRequest = function(a, b) {
          var c = this;
          this.h = new Mg();
          try {
            var d2 = this.l.createSession("video/mp4", Lb(b));
            this.i = d2;
            this.sessionId = d2.sessionId || "";
            this.j.o(this.i, "webkitkeymessage", function(e) {
              c.h && (c.h.resolve(), c.h = null);
              e = (/* @__PURE__ */ new Map()).set("messageType", c.keyStatuses.Oc() == void 0 ? "license-request" : "license-renewal").set("message", Mb(e.message));
              e = new T("message", e);
              c.dispatchEvent(e);
            });
            this.j.o(d2, "webkitkeyadded", function() {
              c.g && (CD(c, "usable"), c.g.resolve(), c.g = null);
            });
            this.j.o(d2, "webkitkeyerror", function() {
              var e = Error("EME PatchedMediaKeysApple key error");
              e.errorCode = c.i.error;
              if (c.h != null) c.h.reject(e), c.h = null;
              else if (c.g != null) c.g.reject(e), c.g = null;
              else switch (c.i.error.code) {
                case WebKitMediaKeyError.MEDIA_KEYERR_OUTPUT:
                case WebKitMediaKeyError.MEDIA_KEYERR_HARDWARECHANGE:
                  CD(c, "output-not-allowed");
                  break;
                default:
                  CD(c, "internal-error");
              }
            });
            CD(this, "status-pending");
          } catch (e) {
            this.h.reject(e);
          }
          return this.h;
        };
        p.load = function() {
          return Promise.reject(Error("MediaKeySession.load not yet supported"));
        };
        p.update = function(a) {
          this.g = new Mg();
          try {
            this.i.update(Lb(a));
          } catch (b) {
            this.g.reject(b);
          }
          return this.g;
        };
        p.close = function() {
          try {
            this.i.close(), this.closed.resolve(), this.j.Ta();
          } catch (a) {
            this.closed.reject(a);
          }
          return this.closed;
        };
        p.remove = function() {
          return Promise.reject(Error("MediaKeySession.remove is only applicable for persistent licenses, which are not supported on this platform"));
        };
        function CD(a, b) {
          var c = a.keyStatuses;
          c.size = b == void 0 ? 0 : 1;
          c.g = b;
          b = new T("keystatuseschange");
          a.dispatchEvent(b);
          if (a.onkeystatuseschange) a.onkeystatuseschange(b);
        }
        function BD() {
          this.size = 0;
          this.g = void 0;
        }
        p = BD.prototype;
        p.Oc = function() {
          return this.g;
        };
        p.forEach = function(a) {
          this.g && a(this.g, Dg.value());
        };
        p.get = function(a) {
          if (this.has(a)) return this.g;
        };
        p.has = function(a) {
          var b = Dg.value();
          return this.g && Kb(a, b) ? true : false;
        };
        p.entries = function() {
        };
        p.keys = function() {
        };
        p.values = function() {
        };
        var tD = "apple";
        wC(function() {
          window7.HTMLVideoElement && window7.WebKitMediaKeys && (navigator.requestMediaKeySystemAccess && MediaKeySystemAccess.prototype.getConfiguration || sD());
        });
        function DD() {
        }
        function ED() {
          if (window7.MediaKeys) {
            var a = Sb();
            MediaKeys.prototype.setServerCertificate && a.He() || (MediaKeys.prototype.setServerCertificate = FD);
          }
        }
        function FD() {
          return Promise.resolve(false);
        }
        tC.PatchedMediaKeysCert = DD;
        DD.install = ED;
        wC(ED);
        function GD() {
        }
        function HD() {
          if (!(!window7.HTMLVideoElement || navigator.requestMediaKeySystemAccess && MediaKeySystemAccess.prototype.getConfiguration)) {
            if (HTMLMediaElement.prototype.webkitGenerateKeyRequest) ID = "webkit";
            else if (!HTMLMediaElement.prototype.generateKeyRequest) return;
            navigator.requestMediaKeySystemAccess = JD;
            delete HTMLMediaElement.prototype.mediaKeys;
            HTMLMediaElement.prototype.mediaKeys = null;
            HTMLMediaElement.prototype.setMediaKeys = KD;
            window7.MediaKeys = LD;
            window7.MediaKeySystemAccess = MD;
            window7.shakaMediaKeysPolyfill = ND;
          }
        }
        function OD(a) {
          var b = ID;
          return b ? b + a.charAt(0).toUpperCase() + a.slice(1) : a;
        }
        function JD(a, b) {
          try {
            var c = new MD(a, b);
            return Promise.resolve(c);
          } catch (d2) {
            return Promise.reject(d2);
          }
        }
        function KD(a) {
          var b = this.mediaKeys;
          b && b != a && PD(b, null);
          delete this.mediaKeys;
          (this.mediaKeys = a) && PD(a, this);
          return Promise.resolve();
        }
        tC.PatchedMediaKeysWebkit = GD;
        GD.install = HD;
        function MD(a, b) {
          this.g = this.keySystem = a;
          var c = false;
          a == "org.w3.clearkey" && (this.g = "webkit-org.w3.clearkey", c = false);
          var d2 = false;
          var e = document.getElementsByTagName("video");
          e = e.length ? e[0] : document.createElement("video");
          b = t2(b);
          for (var f = b.next(); !f.done; f = b.next()) {
            f = f.value;
            var g = {
              audioCapabilities: [],
              videoCapabilities: [],
              persistentState: "optional",
              distinctiveIdentifier: "optional",
              initDataTypes: f.initDataTypes,
              sessionTypes: ["temporary"],
              label: f.label
            }, h = false;
            if (f.audioCapabilities) for (var k2 = t2(f.audioCapabilities), l = k2.next(); !l.done; l = k2.next()) l = l.value, l.contentType && (h = true, e.canPlayType(l.contentType.split(";")[0], this.g) && (g.audioCapabilities.push(l), d2 = true));
            if (f.videoCapabilities) for (k2 = t2(f.videoCapabilities), l = k2.next(); !l.done; l = k2.next()) l = l.value, l.contentType && (h = true, e.canPlayType(l.contentType, this.g) && (g.videoCapabilities.push(l), d2 = true));
            h || (d2 = e.canPlayType("video/mp4", this.g) || e.canPlayType("video/webm", this.g));
            f.persistentState == "required" && (c ? (g.persistentState = "required", g.sessionTypes = ["persistent-license"]) : d2 = false);
            if (d2) {
              this.h = g;
              return;
            }
          }
          c = "Unsupported keySystem";
          if (a == "org.w3.clearkey" || a == "com.widevine.alpha") c = "None of the requested configurations were supported.";
          a = Error(c);
          a.name = "NotSupportedError";
          a.code = DOMException.NOT_SUPPORTED_ERR;
          throw a;
        }
        MD.prototype.createMediaKeys = function() {
          var a = new LD(this.g);
          return Promise.resolve(a);
        };
        MD.prototype.getConfiguration = function() {
          return this.h;
        };
        function LD(a) {
          this.l = a;
          this.h = null;
          this.g = new Qc();
          this.i = [];
          this.j = /* @__PURE__ */ new Map();
        }
        function PD(a, b) {
          a.h = b;
          a.g.Ta();
          var c = ID;
          b && (a.g.o(b, c + "needkey", function(d2) {
            var e = new CustomEvent("encrypted");
            e.initDataType = "cenc";
            e.initData = Mb(d2.initData);
            a.h.dispatchEvent(e);
          }), a.g.o(b, c + "keymessage", function(d2) {
            var e = QD(a, d2.sessionId);
            e && (d2 = (/* @__PURE__ */ new Map()).set("messageType", e.keyStatuses.Oc() == void 0 ? "licenserequest" : "licenserenewal").set("message", d2.message), d2 = new T("message", d2), e.h && (e.h.resolve(), e.h = null), e.dispatchEvent(d2));
          }), a.g.o(b, c + "keyadded", function(d2) {
            (d2 = QD(a, d2.sessionId)) && d2.ready();
          }), a.g.o(b, c + "keyerror", function(d2) {
            var e = QD(a, d2.sessionId);
            if (e) {
              var f = Error("EME v0.1b key error"), g = d2.errorCode;
              g.systemCode = d2.systemCode;
              f.errorCode = g;
              !d2.sessionId && e.h ? (d2.systemCode == 45 && (f.message = "Unsupported session type."), e.h.reject(f), e.h = null) : d2.sessionId && e.g ? (e.g.reject(f), e.g = null) : (f = d2.systemCode, d2.errorCode.code == MediaKeyError.MEDIA_KEYERR_OUTPUT ? RD(e, "output-restricted") : f == 1 ? RD(e, "expired") : RD(e, "internal-error"));
            }
          }));
        }
        LD.prototype.createSession = function(a) {
          a = a || "temporary";
          if (a != "temporary" && a != "persistent-license") throw new TypeError("Session type " + a + " is unsupported on this platform.");
          var b = this.h || document.createElement("video");
          b.src || (b.src = "about:blank");
          a = new SD(b, this.l, a);
          this.i.push(a);
          return a;
        };
        LD.prototype.setServerCertificate = function() {
          return Promise.resolve(false);
        };
        LD.prototype.getStatusForPolicy = function() {
          return Promise.resolve("usable");
        };
        function QD(a, b) {
          var c = a.j.get(b);
          return c ? c : (c = a.i.shift()) ? (c.sessionId = b, a.j.set(b, c), c) : null;
        }
        function SD(a, b, c) {
          lb.call(this);
          this.j = a;
          this.m = false;
          this.g = this.h = null;
          this.i = b;
          this.l = c;
          this.sessionId = "";
          this.expiration = NaN;
          this.closed = new Mg();
          this.keyStatuses = new TD();
          this.onkeystatuseschange = null;
        }
        ma(SD, lb);
        p = SD.prototype;
        p.ready = function() {
          RD(this, "usable");
          this.g && this.g.resolve();
          this.g = null;
        };
        function UD(a, b, c) {
          if (a.m) return Promise.reject(Error("The session is already initialized."));
          a.m = true;
          try {
            if (a.l == "persistent-license") {
              if (c) var d2 = Lb(ac("LOAD_SESSION|" + c));
              else {
                var e = ac("PERSISTENT|");
                d2 = mc(e, b);
              }
            } else d2 = Lb(b);
          } catch (g) {
            return Promise.reject(g);
          }
          a.h = new Mg();
          var f = OD("generateKeyRequest");
          try {
            a.j[f](a.i, d2);
          } catch (g) {
            if (g.name != "InvalidStateError") return a.h = null, Promise.reject(g);
            new Cf(function() {
              try {
                a.j[f](a.i, d2);
              } catch (h) {
                a.h.reject(h), a.h = null;
              }
            }).Y(0.01);
          }
          return a.h;
        }
        function VD(a, b, c) {
          if (a.g) a.g.then(function() {
            return VD(a, b, c);
          }).catch(function() {
            return VD(a, b, c);
          });
          else {
            a.g = b;
            if (a.i == "webkit-org.w3.clearkey") {
              var d2 = Xb(c);
              var e = JSON.parse(d2);
              e.keys[0].kty != "oct" && (a.g.reject(Error("Response is not a valid JSON Web Key Set.")), a.g = null);
              d2 = jc(e.keys[0].k);
              e = jc(e.keys[0].kid);
            } else d2 = Lb(c), e = null;
            var f = OD("addKey");
            try {
              a.j[f](a.i, d2, e, a.sessionId);
            } catch (g) {
              a.g.reject(g), a.g = null;
            }
          }
        }
        function RD(a, b) {
          var c = a.keyStatuses;
          c.size = b == void 0 ? 0 : 1;
          c.g = b;
          b = new T("keystatuseschange");
          a.dispatchEvent(b);
          if (a.onkeystatuseschange) a.onkeystatuseschange(b);
        }
        p.generateRequest = function(a, b) {
          return UD(this, b, null);
        };
        p.load = function(a) {
          return this.l == "persistent-license" ? UD(this, null, a) : Promise.reject(Error("Not a persistent session."));
        };
        p.update = function(a) {
          var b = new Mg();
          VD(this, b, a);
          return b;
        };
        p.close = function() {
          if (this.l != "persistent-license") {
            if (!this.sessionId) return this.closed.reject(Error("The session is not callable.")), this.closed;
            var a = OD("cancelKeyRequest");
            try {
              this.j[a](this.i, this.sessionId);
            } catch (b) {
            }
          }
          this.closed.resolve();
          return this.closed;
        };
        p.remove = function() {
          return this.l != "persistent-license" ? Promise.reject(Error("Not a persistent session.")) : this.close();
        };
        function TD() {
          this.size = 0;
          this.g = void 0;
        }
        p = TD.prototype;
        p.Oc = function() {
          return this.g;
        };
        p.forEach = function(a) {
          this.g && a(this.g, Dg.value());
        };
        p.get = function(a) {
          if (this.has(a)) return this.g;
        };
        p.has = function(a) {
          var b = Dg.value();
          return this.g && Kb(a, b) ? true : false;
        };
        p.entries = function() {
        };
        p.keys = function() {
        };
        p.values = function() {
        };
        var ID = "", ND = "webkit";
        wC(HD);
        function WD() {
        }
        function XD() {
          if (window7.HTMLVideoElement) {
            var a = HTMLVideoElement.prototype;
            a.requestPictureInPicture && document.exitPictureInPicture || !a.webkitSupportsPresentationMode || (document.pictureInPictureEnabled = true, document.pictureInPictureElement = null, a.requestPictureInPicture = YD, Object.defineProperty(a, "disablePictureInPicture", {
              get: ZD,
              set: $D,
              enumerable: true,
              configurable: true
            }), document.exitPictureInPicture = aE, document.addEventListener("webkitpresentationmodechanged", bE, true));
          }
        }
        function bE(a) {
          a = a.target;
          if (a.webkitPresentationMode == "picture-in-picture") {
            document.pictureInPictureElement = a;
            var b = new Event("enterpictureinpicture");
            a.dispatchEvent(b);
          } else document.pictureInPictureElement == a && (document.pictureInPictureElement = null), b = new Event("leavepictureinpicture"), a.dispatchEvent(b);
        }
        function YD() {
          return this.webkitSupportsPresentationMode("picture-in-picture") ? (this.webkitSetPresentationMode("picture-in-picture"), document.pictureInPictureElement = this, Promise.resolve()) : Promise.reject(Error("PiP not allowed by video element"));
        }
        function aE() {
          var a = document.pictureInPictureElement;
          return a ? (a.webkitSetPresentationMode("inline"), document.pictureInPictureElement = null, Promise.resolve()) : Promise.reject(Error("No picture in picture element found"));
        }
        function ZD() {
          return this.hasAttribute("disablePictureInPicture") ? true : !this.webkitSupportsPresentationMode("picture-in-picture");
        }
        function $D(a) {
          a ? this.setAttribute("disablePictureInPicture", "") : this.removeAttribute("disablePictureInPicture");
        }
        tC.PiPWebkit = WD;
        WD.install = XD;
        wC(XD);
        function cE() {
        }
        function dE() {
          window7.crypto && ("randomUUID" in window7.crypto || (window7.crypto.randomUUID = eE));
        }
        function eE() {
          var a = URL.createObjectURL(new Blob()), b = a.toString();
          URL.revokeObjectURL(a);
          return b.substr(b.lastIndexOf("/") + 1);
        }
        tC.RandomUUID = cE;
        cE.install = dE;
        wC(dE);
        function fE() {
        }
        function gE() {
          var a = Symbol.prototype;
          "description" in a || Object.defineProperty(a, "description", {
            get: hE
          });
        }
        function hE() {
          var a = /\((.*)\)/.exec(this.toString());
          return a ? a[1] : void 0;
        }
        tC.Symbol = fE;
        fE.install = gE;
        wC(gE);
        function iE() {
        }
        function jE() {
          for (var a = t2([Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, Int8Array, Int16Array, Int32Array, Float32Array, Float64Array]), b = a.next(); !b.done; b = a.next()) b = b.value, b.prototype.indexOf || (b.prototype.indexOf = kE), b.prototype.lastIndexOf || (b.prototype.lastIndexOf = lE), b.prototype.includes || (b.prototype.includes = mE);
        }
        function kE(a, b) {
          return Array.prototype.indexOf.call(this, a, b);
        }
        function lE(a, b) {
          return Array.prototype.lastIndexOf.call(this, a, b);
        }
        function mE(a, b) {
          return this.indexOf(a, b) !== -1;
        }
        tC.TypedArray = iE;
        iE.install = jE;
        wC(jE);
        function nE() {
        }
        function oE() {
          if (window7.HTMLMediaElement) {
            var a = HTMLMediaElement.prototype.play;
            HTMLMediaElement.prototype.play = function() {
              var b = a.apply(this);
              b && b.catch(function() {
              });
              return b;
            };
          }
        }
        tC.VideoPlayPromise = nE;
        nE.install = oE;
        wC(oE);
        function pE() {
        }
        function qE() {
          if (window7.HTMLVideoElement) {
            var a = HTMLVideoElement.prototype;
            !a.getVideoPlaybackQuality && ("webkitDroppedFrameCount" in a || typeof Ki().webkitDroppedFrameCount === "number") && (a.getVideoPlaybackQuality = rE);
          }
        }
        function rE() {
          return {
            droppedVideoFrames: this.webkitDroppedFrameCount,
            totalVideoFrames: this.webkitDecodedFrameCount,
            corruptedVideoFrames: 0,
            creationTime: NaN,
            totalFrameDelay: 0
          };
        }
        tC.VideoPlaybackQuality = pE;
        pE.install = qE;
        wC(qE);
        function sE() {
        }
        function tE() {
          if (!window7.VTTCue && window7.TextTrackCue) {
            var a = null, b = TextTrackCue.length;
            if (b == 3) a = uE;
            else if (b == 6) a = vE;
            else {
              try {
                var c = !!uE(1, 2, "");
              } catch (d2) {
                c = false;
              }
              c && (a = uE);
            }
            a && (window7.VTTCue = function(d2, e, f) {
              return a(d2, e, f);
            });
          }
        }
        function uE(a, b, c) {
          return new window7.TextTrackCue(a, b, c);
        }
        function vE(a, b, c) {
          return new window7.TextTrackCue(a + "-" + b + "-" + c, a, b, c);
        }
        tC.VTTCue = sE;
        sE.install = tE;
        wC(tE);
        function wE(a) {
          lb.call(this);
          this.h = a;
          this.l = null;
          this.g = [];
          this.i = -1;
          this.j = null;
          this.m = new Qc();
        }
        ma(wE, lb);
        p = wE.prototype;
        p.destroy = function() {
          var a = this;
          return P(function(b) {
            if (b.g == 1) return G(b, a.removeAllItems(), 2);
            a.h = null;
            a.m && (a.m.release(), a.m = null);
            lb.prototype.release.call(a);
            H(b);
          });
        };
        p.configure = function(a) {
          this.l = a;
        };
        p.getConfiguration = function() {
          return this.l;
        };
        p.getCurrentItem = function() {
          return this.g.length && this.i >= 0 && this.i < this.g.length ? this.g[this.i] : null;
        };
        p.getCurrentItemIndex = function() {
          return this.i;
        };
        p.getItems = function() {
          return this.g.slice();
        };
        p.insertItems = function(a) {
          this.g.push.apply(this.g, x(a));
          this.dispatchEvent(new T("itemsinserted"));
        };
        p.removeAllItems = function() {
          var a = this;
          return P(function(b) {
            switch (b.g) {
              case 1:
                a.m.Ta();
                if (!(a.g.length && a.i >= 0)) {
                  b.B(2);
                  break;
                }
                return G(b, a.h.rc(), 2);
              case 2:
                if (!a.j) {
                  b.B(4);
                  break;
                }
                if (a.j.Vf.A) {
                  b.B(5);
                  break;
                }
                return G(b, a.j.Vf.destroy(), 5);
              case 5:
                a.j = null;
              case 4:
                a.g = [], a.i = -1, a.dispatchEvent(new T("itemsremoved")), H(b);
            }
          });
        };
        p.playItem = function(a) {
          var b = this, c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w;
          return P(function(v) {
            if (v.g == 1) {
              b.m.Ta();
              if (!b.g.length || a >= b.g.length) throw new U(2, 7, 7007);
              c = b.g[a];
              b.i != a && (b.i = a, b.dispatchEvent(new T("currentitemchanged")));
              d2 = b.h.h;
              e = b.l ? b.l.preloadNextUrlWindow : 0;
              e > 0 && (f = false, b.m.o(d2, "timeupdate", function() {
                var y, z, A, C;
                return P(function(D) {
                  switch (D.g) {
                    case 1:
                      if (b.j || b.g.length <= 1 || f || b.h.U() || !d2.duration) return D.return();
                      y = b.h.ya().end - d2.currentTime;
                      if (isNaN(y)) {
                        D.B(0);
                        break;
                      }
                      if (!(y <= e)) {
                        D.B(0);
                        break;
                      }
                      z = b.l && b.l.repeatMode;
                      A = null;
                      b.i + 1 < b.g.length ? A = b.g[b.i + 1] : z == 1 && (A = b.g[0]);
                      if (!A) {
                        D.B(0);
                        break;
                      }
                      f = true;
                      C = null;
                      sa(D, 5);
                      return G(D, b.h.preload(A.manifestUri, A.startTime, A.mimeType, A.config), 7);
                    case 7:
                      C = D.h;
                      ua(D, 6);
                      break;
                    case 5:
                      va(D), C = null;
                    case 6:
                      b.j = {
                        item: A,
                        Vf: C
                      }, f = false, H(D);
                  }
                });
              }));
              b.m.o(b.h, "complete", function() {
                var y = b.l && b.l.repeatMode, z = false;
                if (y == 2) z = true;
                else {
                  var A = b.i + 1;
                  A < b.g.length ? b.playItem(A) : y == 1 && (b.g.length == 1 ? z = true : b.playItem(0));
                }
                z && (d2.paused ? (d2.currentTime = b.h.ya().start, d2.play()) : b.m.o(d2, "paused", function() {
                  d2.currentTime = b.h.ya().start;
                  d2.play();
                }));
              });
              c.config && (b.h.Aj(), b.h.configure(c.config));
              g = c.manifestUri;
              b.j && b.j.item == c && b.j.Vf && (g = b.j.Vf);
              return G(v, b.h.load(g, c.startTime, c.mimeType), 2);
            }
            b.j = null;
            if (c.extraText) for (h = t2(c.extraText), k2 = h.next(); !k2.done; k2 = h.next()) l = k2.value, l.mime ? b.h.be(l.uri, l.language, l.kind, l.mime, l.codecs) : b.h.be(l.uri, l.language, l.kind);
            if (c.extraThumbnail) for (m = t2(c.extraThumbnail), n = m.next(); !n.done; n = m.next()) q = n.value, b.h.cf(q);
            if (c.extraChapter) for (r2 = t2(c.extraChapter), u = r2.next(); !u.done; u = r2.next()) w = u.value, b.h.bf(w.uri, w.language, w.mime);
            H(v);
          });
        };
        S("shaka.queue.QueueManager", wE);
        wE.prototype.playItem = wE.prototype.playItem;
        wE.prototype.removeAllItems = wE.prototype.removeAllItems;
        wE.prototype.insertItems = wE.prototype.insertItems;
        wE.prototype.getItems = wE.prototype.getItems;
        wE.prototype.getCurrentItemIndex = wE.prototype.getCurrentItemIndex;
        wE.prototype.getCurrentItem = wE.prototype.getCurrentItem;
        wE.prototype.getConfiguration = wE.prototype.getConfiguration;
        wE.prototype.configure = wE.prototype.configure;
        wE.prototype.destroy = wE.prototype.destroy;
        oq = function(a) {
          return new wE(a);
        };
        function xE() {
        }
        xE.prototype.parseInit = function() {
        };
        xE.prototype.setSequenceMode = function() {
        };
        xE.prototype.setManifestType = function() {
        };
        xE.prototype.parseMedia = function(a, b) {
          var c = null, d2 = [];
          a = Xb(a).split(/\r?\n/);
          a = t2(a);
          for (var e = a.next(); !e.done; e = a.next()) if ((e = e.value) && !/^\s+$/.test(e) && (e = yE.exec(e))) {
            var f = zE.exec(e[1]);
            f = parseInt(f[1], 10) * 60 + parseFloat(f[2].replace(",", "."));
            e = new se(f, b.segmentEnd ? b.segmentEnd : f + 2, e[2]);
            c && (c.endTime = f, d2.push(c));
            c = e;
          }
          c && d2.push(c);
          return d2;
        };
        S("shaka.text.LrcTextParser", xE);
        xE.prototype.parseMedia = xE.prototype.parseMedia;
        xE.prototype.setManifestType = xE.prototype.setManifestType;
        xE.prototype.setSequenceMode = xE.prototype.setSequenceMode;
        xE.prototype.parseInit = xE.prototype.parseInit;
        var yE = /^\[(\d{1,2}:\d{1,2}(?:[.,]\d{1,3})?)\](.*)/, zE = /^(\d+):(\d{1,2}(?:[.,]\d{1,3})?)$/;
        rf("application/x-subtitle-lrc", function() {
          return new xE();
        });
        function AE() {
        }
        AE.prototype.parseInit = function() {
        };
        AE.prototype.setSequenceMode = function() {
        };
        AE.prototype.setManifestType = function() {
        };
        AE.prototype.parseMedia = function(a, b, c, d2) {
          var e = Xb(a);
          a = [];
          if (e == "") return a;
          var f = Ld(e, "tt", true);
          if (!f) throw new U(2, 2, 2005, "Failed to parse TTML.");
          e = Vd(f, "body")[0];
          if (!e) return [];
          var g = be(f, BE, "frameRate"), h = be(f, BE, "subFrameRate"), k2 = be(f, BE, "frameRateMultiplier"), l = be(f, BE, "tickRate"), m = be(f, BE, "cellResolution"), n = f.attributes["xml:space"] || "default", q = be(f, CE, "extent");
          if (n != "default" && n != "preserve") throw new U(2, 2, 2005, "Invalid xml:space value: " + n);
          n = n == "default";
          g = new DE(g, h, k2, l);
          m = EE(m);
          h = Vd(f, "metadata")[0];
          h = (h ? h.children : []).filter(function(w) {
            return w != "\n";
          });
          k2 = Vd(f, "style");
          f = Vd(f, "region");
          l = [];
          for (var r2 = t2(f), u = r2.next(); !u.done; u = r2.next()) (u = FE(u.value, k2, q)) && l.push(u);
          if (Sd(e, "p").length) throw new U(2, 2, 2001, "<p> can only be inside <div> in TTML");
          q = t2(Sd(e, "div"));
          for (r2 = q.next(); !r2.done; r2 = q.next()) if (Sd(r2.value, "span").length) throw new U(2, 2, 2001, "<span> can only be inside <p> in TTML");
          if (b = GE(e, b, g, h, k2, f, l, n, m, null, false, c, d2)) b.backgroundColor || (b.backgroundColor = "transparent"), a.push(b);
          return a;
        };
        function GE(a, b, c, d2, e, f, g, h, k2, l, m, n, q) {
          var r2 = l;
          if (Qd(a)) {
            if (!m) return null;
            var u = {
              tagName: "span",
              children: [Td(a)],
              attributes: {},
              parent: null
            };
          } else u = a;
          for (var w = null, v = t2(HE), y = v.next(); !y.done && !(w = IE(u, "backgroundImage", d2, "#", y.value)[0]); y = v.next()) ;
          v = null;
          y = be(u, HE, "backgroundImage");
          var z = /^(urn:)(mpeg:[a-z0-9][a-z0-9-]{0,31}:)(subs:)([0-9]+)$/;
          if (y && z.test(y)) {
            v = parseInt(y.split(":").pop(), 10) - 1;
            if (v >= q.length) return null;
            v = q[v];
          } else n && y && !y.startsWith("#") && (z = new rb(n), y = new rb(y), (y = z.resolve(y).toString()) && (v = y));
          if (a.tagName == "p" || w || v) m = true;
          a = m;
          y = (u.attributes["xml:space"] || (h ? "default" : "preserve")) == "default";
          z = u.children.every(Qd);
          h = [];
          if (!z) for (var A = t2(u.children), C = A.next(); !C.done; C = A.next()) (C = GE(C.value, b, c, d2, e, f, g, y, k2, u, m, n, q)) && h.push(C);
          d2 = l != null;
          n = Td(u);
          n = u.children.length && n && /\S/.test(n);
          A = u.attributes.begin || u.attributes.end || u.attributes.dur;
          if (!(A || n || u.tagName == "br" || h.length != 0 || d2 && !y)) return null;
          q = JE(u, c);
          n = q.start;
          for (q = q.end; r2 && r2.tagName && r2.tagName != "tt"; ) q = KE(r2, c, n, q), n = q.start, q = q.end, r2 = r2.parent;
          n == null && (n = 0);
          n += b.periodStart;
          q = q == null ? Infinity : q + b.periodStart;
          n = Math.max(n, b.segmentStart);
          q = Math.min(q, b.segmentEnd);
          if (!A && h.length > 0) for (n = Infinity, q = 0, b = t2(h), c = b.next(); !c.done; c = b.next()) c = c.value, n = Math.min(n, c.startTime), q = Math.max(q, c.endTime);
          if (u.tagName == "br") return e = new se(n, q, ""), e.lineBreak = true, e;
          b = "";
          z && (b = dc(Td(u) || ""), y && (b = b.replace(/\s+/g, " ")));
          b = new se(n, q, b);
          b.nestedCues = h;
          m || (b.isContainer = true);
          k2 && (b.cellResolution = k2);
          k2 = IE(u, "region", f, "")[0];
          if (u.attributes.region && k2 && k2.attributes["xml:id"]) {
            var D = k2.attributes["xml:id"];
            b.region = g.filter(function(F) {
              return F.id == D;
            })[0];
          }
          g = k2;
          l && d2 && !u.attributes.region && !u.attributes.style && (g = IE(l, "region", f, "")[0]);
          LE(b, u, g, w, v, e, a, h.length == 0);
          return b;
        }
        function FE(a, b, c) {
          var d2 = new qd(), e = a.attributes["xml:id"];
          if (!e) return null;
          d2.id = e;
          e = null;
          c && (e = ME.exec(c) || NE.exec(c));
          c = e ? Number(e[1]) : null;
          e = e ? Number(e[2]) : null;
          var f, g = OE(a, b, "extent");
          if (g) {
            var h = (f = ME.exec(g)) || NE.exec(g);
            h != null && (d2.width = Number(h[1]), d2.height = Number(h[2]), f || (c != null && (d2.width = d2.width * 100 / c), e != null && (d2.height = d2.height * 100 / e)), d2.widthUnits = f || c != null ? rd : 0, d2.heightUnits = f || e != null ? rd : 0);
          }
          if (a = OE(a, b, "origin")) {
            if (h = (f = ME.exec(a)) || NE.exec(a), h != null) d2.viewportAnchorX = Number(h[1]), d2.viewportAnchorY = Number(h[2]), f ? g || (d2.width = 100 - d2.viewportAnchorX, d2.widthUnits = rd, d2.height = 100 - d2.viewportAnchorY, d2.heightUnits = rd) : (e != null && (d2.viewportAnchorY = d2.viewportAnchorY * 100 / e), c != null && (d2.viewportAnchorX = d2.viewportAnchorX * 100 / c)), d2.viewportAnchorUnits = f || c != null ? rd : 0;
          }
          return d2;
        }
        function PE(a) {
          var b = a.match(/rgba\(([^)]+)\)/);
          return b && (b = b[1].split(","), b.length == 4) ? (b[3] = String(Number(b[3]) / 255), "rgba(" + b.join(",") + ")") : a;
        }
        function LE(a, b, c, d2, e, f, g, h) {
          g = g || h;
          QE(b, c, f, "direction", g) == "rtl" && (a.direction = "rtl");
          h = QE(b, c, f, "writingMode", g);
          h == "tb" || h == "tblr" ? a.writingMode = "vertical-lr" : h == "tbrl" ? a.writingMode = "vertical-rl" : h == "rltb" || h == "rl" ? a.direction = "rtl" : h && (a.direction = ve);
          (h = QE(b, c, f, "textAlign", true)) ? (a.positionAlign = RE.get(h), a.lineAlign = SE.get(h), a.textAlign = Se[h.toUpperCase()]) : a.textAlign = ue;
          if (h = QE(b, c, f, "displayAlign", true)) a.displayAlign = Te[h.toUpperCase()];
          if (h = QE(b, c, f, "color", g)) a.color = PE(h);
          if (h = QE(b, c, f, "backgroundColor", g)) a.backgroundColor = PE(h);
          if (h = QE(b, c, f, "border", g)) a.border = h;
          if (h = QE(b, c, f, "fontFamily", g)) switch (h) {
            case "monospaceSerif":
              a.fontFamily = "Courier New,Liberation Mono,Courier,monospace";
              break;
            case "proportionalSansSerif":
              a.fontFamily = "Arial,Helvetica,Liberation Sans,sans-serif";
              break;
            case "sansSerif":
              a.fontFamily = "sans-serif";
              break;
            case "monospaceSansSerif":
              a.fontFamily = "Consolas,monospace";
              break;
            case "proportionalSerif":
              a.fontFamily = "serif";
              break;
            default:
              a.fontFamily = h.split(",").filter(function(k2) {
                return k2 != "default";
              }).join(",");
          }
          (h = QE(b, c, f, "fontWeight", g)) && h == "bold" && (a.fontWeight = Pe);
          h = QE(b, c, f, "wrapOption", g);
          a.wrapLine = h && h == "noWrap" ? false : true;
          (h = QE(b, c, f, "lineHeight", g)) && h.match(TE) && (a.lineHeight = h);
          (h = QE(b, c, f, "fontSize", g)) && (h.match(TE) || h.match(UE)) && (a.fontSize = h);
          if (h = QE(b, c, f, "fontStyle", g)) a.fontStyle = Ve[h.toUpperCase()];
          d2 ? (e = d2.attributes.imageType || d2.attributes.imagetype, h = d2.attributes.encoding, d2 = Td(d2).trim(), e == "PNG" && h == "Base64" && d2 && (a.backgroundImage = "data:image/png;base64," + d2)) : e && (a.backgroundImage = e);
          if (d2 = QE(b, c, f, "textOutline", g)) d2 = d2.split(" "), d2[0].match(TE) ? a.textStrokeColor = a.color : (a.textStrokeColor = PE(d2[0]), d2.shift()), d2[0] && d2[0].match(TE) ? a.textStrokeWidth = d2[0] : a.textStrokeColor = "";
          (d2 = QE(b, c, f, "letterSpacing", g)) && d2.match(TE) && (a.letterSpacing = d2);
          (d2 = QE(b, c, f, "linePadding", g)) && d2.match(TE) && (a.linePadding = d2);
          if (d2 = QE(b, c, f, "opacity", g)) a.opacity = parseFloat(d2);
          (d2 = OE(c, f, "textDecoration")) && VE(a, d2);
          (d2 = WE(b, f, "textDecoration")) && VE(a, d2);
          if (d2 = QE(b, c, f, "textCombine", g)) a.textCombineUpright = d2;
          switch (QE(b, c, f, "ruby", g)) {
            case "container":
              a.rubyTag = "ruby";
              break;
            case "text":
              a.rubyTag = "rt";
          }
        }
        function VE(a, b) {
          b = t2(b.split(" "));
          for (var c = b.next(); !c.done; c = b.next()) switch (c.value) {
            case "underline":
              a.textDecoration.includes(Re) || a.textDecoration.push(Re);
              break;
            case "noUnderline":
              a.textDecoration.includes(Re) && ud(a.textDecoration, Re);
              break;
            case "lineThrough":
              a.textDecoration.includes("lineThrough") || a.textDecoration.push("lineThrough");
              break;
            case "noLineThrough":
              a.textDecoration.includes("lineThrough") && ud(a.textDecoration, "lineThrough");
              break;
            case "overline":
              a.textDecoration.includes("overline") || a.textDecoration.push("overline");
              break;
            case "noOverline":
              a.textDecoration.includes("overline") && ud(a.textDecoration, "overline");
          }
        }
        function QE(a, b, c, d2, e) {
          e = e === void 0 ? true : e;
          return (a = WE(a, c, d2)) ? a : e ? OE(b, c, d2) : null;
        }
        function OE(a, b, c) {
          if (!a) return null;
          var d2 = be(a, CE, c);
          return d2 ? d2 : XE(a, b, c);
        }
        function WE(a, b, c) {
          var d2 = be(a, CE, c);
          return d2 ? d2 : XE(a, b, c);
        }
        function XE(a, b, c) {
          a = IE(a, "style", b, "");
          for (var d2 = null, e = 0; e < a.length; e++) {
            var f = ae(a[e], "urn:ebu:tt:style", c);
            f || (f = be(a[e], CE, c));
            f || (f = WE(a[e], b, c));
            f && (d2 = f);
          }
          return d2;
        }
        function IE(a, b, c, d2, e) {
          var f = [];
          if (!a || c.length < 1) return f;
          var g = a;
          for (a = null; !a && !(a = e ? ae(g, e, b) : g.attributes[b]) && (g = g.parent, g); ) ;
          if (b = a) {
            for (b = t2(b.split(" ")), e = b.next(); !e.done; e = b.next()) for (e = e.value, a = t2(c), g = a.next(); !g.done; g = a.next()) if (g = g.value, d2 + g.attributes["xml:id"] == e) {
              f.push(g);
              break;
            }
          }
          return f;
        }
        function KE(a, b, c, d2) {
          a = JE(a, b);
          c == null ? c = a.start : a.start != null && (c += a.start);
          d2 == null ? d2 = a.end : a.start != null && (d2 += a.start);
          return {
            start: c,
            end: d2
          };
        }
        function JE(a, b) {
          var c = YE(a.attributes.begin, b), d2 = YE(a.attributes.end, b);
          a = YE(a.attributes.dur, b);
          d2 == null && a != null && (d2 = c + a);
          return {
            start: c,
            end: d2
          };
        }
        function YE(a, b) {
          var c = null;
          if (ZE.test(a)) {
            a = ZE.exec(a);
            c = Number(a[1]);
            var d2 = Number(a[2]), e = Number(a[3]), f = Number(a[4]);
            f += (Number(a[5]) || 0) / b.h;
            e += f / b.frameRate;
            c = e + d2 * 60 + c * 3600;
          } else if ($E.test(a)) c = aF($E, a);
          else if (bF.test(a)) c = aF(bF, a);
          else if (cF.test(a)) a = cF.exec(a), c = Number(a[1]) / b.frameRate;
          else if (dF.test(a)) a = dF.exec(a), c = Number(a[1]) / b.g;
          else if (eF.test(a)) c = aF(eF, a);
          else if (a) throw new U(2, 2, 2001, "Could not parse cue time range in TTML");
          return c;
        }
        function aF(a, b) {
          a = a.exec(b);
          return a == null || a[0] == "" ? null : (Number(a[4]) || 0) / 1e3 + (Number(a[3]) || 0) + (Number(a[2]) || 0) * 60 + (Number(a[1]) || 0) * 3600;
        }
        function EE(a) {
          return a ? (a = /^(\d+) (\d+)$/.exec(a)) ? {
            columns: parseInt(a[1], 10),
            rows: parseInt(a[2], 10)
          } : null : null;
        }
        S("shaka.text.TtmlTextParser", AE);
        AE.prototype.parseMedia = AE.prototype.parseMedia;
        AE.prototype.setManifestType = AE.prototype.setManifestType;
        AE.prototype.setSequenceMode = AE.prototype.setSequenceMode;
        AE.prototype.parseInit = AE.prototype.parseInit;
        function DE(a, b, c, d2) {
          this.frameRate = Number(a) || 30;
          this.h = Number(b) || 1;
          this.g = Number(d2);
          this.g == 0 && (this.g = a ? this.frameRate * this.h : 1);
          c && (a = /^(\d+) (\d+)$/g.exec(c)) && (this.frameRate *= Number(a[1]) / Number(a[2]));
        }
        var ME = /^(\d{1,2}(?:\.\d+)?|100(?:\.0+)?)% (\d{1,2}(?:\.\d+)?|100(?:\.0+)?)%$/, UE = /^(\d{1,4}(?:\.\d+)?|100)%$/, TE = /^(\d+px|\d+em|\d*\.?\d+c)$/, NE = /^(\d+)px (\d+)px$/, ZE = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/, $E = /^(?:(\d{2,}):)?(\d{2}):(\d{2})$/, bF = /^(?:(\d{2,}):)?(\d{2}):(\d{2}\.\d+)$/, cF = /^(\d*(?:\.\d*)?)f$/, dF = /^(\d*(?:\.\d*)?)t$/, eF = RegExp("^(?:(\\d*(?:\\.\\d*)?)h)?(?:(\\d*(?:\\.\\d*)?)m)?(?:(\\d*(?:\\.\\d*)?)s)?(?:(\\d*(?:\\.\\d*)?)ms)?$"), SE = (/* @__PURE__ */ new Map()).set("left", ye).set("center", "center").set("right", "end").set("start", ye).set("end", "end"), RE = (/* @__PURE__ */ new Map()).set("left", "line-left").set("center", "center").set("right", "line-right"), BE = ["http://www.w3.org/ns/ttml#parameter", "http://www.w3.org/2006/10/ttaf1#parameter"], CE = ["http://www.w3.org/ns/ttml#styling", "http://www.w3.org/2006/10/ttaf1#styling"], HE = ["http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt", "http://www.smpte-ra.org/schemas/2052-1/2013/smpte-tt"];
        rf("application/ttml+xml", function() {
          return new AE();
        });
        function fF() {
          this.g = new AE();
        }
        fF.prototype.parseInit = function(a) {
          var b = false;
          new ph().box("moov", uh).box("trak", uh).box("mdia", uh).box("minf", uh).box("stbl", uh).W("stsd", wh).box("stpp", function(c) {
            b = true;
            c.parser.stop();
          }).parse(a);
          if (!b) throw new U(2, 2, 2007);
        };
        fF.prototype.setSequenceMode = function() {
        };
        fF.prototype.setManifestType = function() {
        };
        fF.prototype.parseMedia = function(a, b, c) {
          var d2 = [], e = null, f = [], g = /* @__PURE__ */ new Map(), h = [];
          new ph().box("moof", uh).box("traf", uh).W("tfhd", function(y) {
            e = Mi(y.reader, y.flags).ie;
          }).W("trun", function(y) {
            y = Pi(y.reader, y.version, y.flags);
            y = t2(y.Zh);
            for (var z = y.next(); !z.done; z = y.next()) h.push(z.value.sampleSize || e || 0);
          }).W("subs", function(y) {
            for (var z = y.reader, A = z.X(), C = -1, D = 0; D < A; D++) {
              var F = z.X();
              C += F;
              F = z.Ha();
              for (var B = [], E = 0; E < F; E++) y.version == 1 ? B.push(z.X()) : B.push(z.Ha()), z.ba(), z.ba(), z.X();
              g.set(C, B);
            }
          }).box("mdat", zh(function(y) {
            f.push(y);
          })).parse(a, false);
          if (f.length == 0) throw new U(2, 2, 2007);
          for (var k2 = mc.apply(ec, x(f)), l = 0, m = 0; m < h.length; m++) {
            var n = Lb(k2, l, h[m]);
            l += h[m];
            var q = g.get(m);
            if (q && q.length) {
              n = Lb(n, 0, q[0]);
              for (var r2 = [], u = q[0], w = 1; w < q.length; w++) {
                var v = Lb(a, u, q[w]);
                v = hc(v);
                r2.push("data:image/png;base64," + v);
                u += q[w];
              }
              d2 = d2.concat(this.g.parseMedia(n, b, c, r2));
            } else d2 = d2.concat(this.g.parseMedia(n, b, c, []));
          }
          return d2;
        };
        S("shaka.text.Mp4TtmlParser", fF);
        fF.prototype.parseMedia = fF.prototype.parseMedia;
        fF.prototype.setManifestType = fF.prototype.setManifestType;
        fF.prototype.setSequenceMode = fF.prototype.setSequenceMode;
        fF.prototype.parseInit = fF.prototype.parseInit;
        rf('application/mp4; codecs="stpp"', function() {
          return new fF();
        });
        rf('application/mp4; codecs="stpp.ttml"', function() {
          return new fF();
        });
        rf('application/mp4; codecs="stpp.ttml.im1i"', function() {
          return new fF();
        });
        rf('application/mp4; codecs="stpp.ttml.im1t"', function() {
          return new fF();
        });
        rf('application/mp4; codecs="stpp.ttml.im2i"', function() {
          return new fF();
        });
        rf('application/mp4; codecs="stpp.ttml.im2t"', function() {
          return new fF();
        });
        rf('application/mp4; codecs="stpp.ttml.etd1"', function() {
          return new fF();
        });
        rf('application/mp4; codecs="stpp.ttml.etd1|im1t"', function() {
          return new fF();
        });
        rf('application/mp4; codecs="stpp.ttml.im1t|etd1"', function() {
          return new fF();
        });
        rf('application/mp4; codecs="stpp.TTML.im1t"', function() {
          return new fF();
        });
        function gF() {
          this.g = "UNKNOWN";
        }
        gF.prototype.parseInit = function() {
        };
        gF.prototype.setSequenceMode = function() {
        };
        gF.prototype.setManifestType = function(a) {
          this.g = a;
        };
        gF.prototype.parseMedia = function(a, b) {
          a = Xb(a);
          a = a.replace(/\r\n|\r(?=[^\n]|$)/gm, "\n");
          var c = a.split(/\n{2,}/m);
          if (!/^WEBVTT($|[ \t\n])/m.test(c[0])) throw new U(2, 2, 2e3);
          a = b.vttOffset;
          if (this.g == "HLS") if (c[0].includes("X-TIMESTAMP-MAP")) {
            var d2 = c[0];
            a = d2.match(/LOCAL:((?:(\d{1,}):)?(\d{2}):(\d{2})\.(\d{3}))/m);
            d2 = d2.match(/MPEGTS:(\d+)/m);
            if (!a || !d2) throw new U(2, 2, 2e3);
            a = Fd(a[1]);
            if (a == null) throw new U(2, 2, 2e3);
            d2 = Number(d2[1]);
            for (var e = b.segmentStart - b.periodStart; e >= 95443.7176888889; ) e -= 95443.7176888889, d2 += 8589934592;
            a = b.periodStart + d2 / 9e4 - a;
          } else b.periodStart && b.vttOffset == b.periodStart && (a = 0);
          b = [];
          d2 = t2(c[0].split("\n"));
          for (e = d2.next(); !e.done; e = d2.next()) if (e = e.value, /^Region:/.test(e)) {
            e = new xd(e);
            var f = new qd();
            Bd(e);
            yd(e);
            for (var g = Bd(e); g; ) {
              var h = f, k2 = g;
              (g = /^id=(.*)$/.exec(k2)) ? h.id = g[1] : (g = /^width=(\d{1,2}|100)%$/.exec(k2)) ? h.width = Number(g[1]) : (g = /^lines=(\d+)$/.exec(k2)) ? (h.height = Number(g[1]), h.heightUnits = 2) : (g = /^regionanchor=(\d{1,2}|100)%,(\d{1,2}|100)%$/.exec(k2)) ? (h.regionAnchorX = Number(g[1]), h.regionAnchorY = Number(g[2])) : (g = /^viewportanchor=(\d{1,2}|100)%,(\d{1,2}|100)%$/.exec(k2)) ? (h.viewportAnchorX = Number(g[1]), h.viewportAnchorY = Number(g[2])) : /^scroll=up$/.exec(k2) && (h.scroll = "up");
              yd(e);
              g = Bd(e);
            }
            b.push(f);
          }
          d2 = /* @__PURE__ */ new Map();
          Ie(d2);
          e = [];
          c = t2(c.slice(1));
          for (f = c.next(); !f.done; f = c.next()) {
            f = f.value.split("\n");
            if ((f.length != 1 || f[0]) && !/^NOTE($|[ \t])/.test(f[0]) && f[0] == "STYLE") {
              h = [];
              g = -1;
              for (k2 = 1; k2 < f.length; k2++) f[k2].includes("::cue") && (h.push([]), g = h.length - 1), g != -1 && (h[g].push(f[k2]), f[k2].includes("}") && (g = -1));
              h = t2(h);
              for (g = h.next(); !g.done; g = h.next()) {
                var l = g.value;
                g = "global";
                (k2 = l[0].match(/\((.*)\)/)) && (g = k2.pop());
                k2 = l.slice(1, -1);
                l[0].includes("}") && (l = /\{(.*?)\}/.exec(l[0])) && (k2 = l[1].split(";"));
                (l = d2.get(g)) || (l = new se(0, 0, ""));
                for (var m = false, n = 0; n < k2.length; n++) {
                  var q = /^\s*([^:]+):\s*(.*)/.exec(k2[n]);
                  if (q) {
                    var r2 = q[2].trim().replace(";", "");
                    switch (q[1].trim()) {
                      case "background-color":
                      case "background":
                        m = true;
                        l.backgroundColor = r2;
                        break;
                      case "color":
                        m = true;
                        l.color = r2;
                        break;
                      case "font-family":
                        m = true;
                        l.fontFamily = r2;
                        break;
                      case "font-size":
                        m = true;
                        l.fontSize = r2;
                        break;
                      case "font-weight":
                        if (parseInt(r2, 10) >= 700 || r2 == "bold") m = true, l.fontWeight = Pe;
                        break;
                      case "font-style":
                        switch (r2) {
                          case "normal":
                            m = true;
                            l.fontStyle = Be;
                            break;
                          case "italic":
                            m = true;
                            l.fontStyle = Qe;
                            break;
                          case "oblique":
                            m = true, l.fontStyle = "oblique";
                        }
                        break;
                      case "opacity":
                        m = true;
                        l.opacity = parseFloat(r2);
                        break;
                      case "text-combine-upright":
                        m = true;
                        l.textCombineUpright = r2;
                        break;
                      case "text-shadow":
                        m = true;
                        l.textShadow = r2;
                        break;
                      case "white-space":
                        m = true, l.wrapLine = r2 != "noWrap";
                    }
                  }
                }
                m && d2.set(g, l);
              }
            }
            l = f;
            m = a;
            if (l.length == 1 && !l[0] || /^NOTE($|[ \t])/.test(l[0]) || l[0] == "STYLE" || l[0] == "REGION") f = null;
            else if (f = null, l[0].includes("-->") || (f = l[0], l.splice(0, 1)), h = new xd(l[0]), g = Dd(h), n = zd(h, /[ \t]+--\x3e[ \t]+/g), k2 = Dd(h), g == null || n == null || k2 == null) bb("Failed to parse VTT time code. Cue skipped:", f, l), f = null;
            else {
              g += m;
              k2 += m;
              m = l.slice(1).join("\n").trim();
              d2.has("global") ? (l = d2.get("global").clone(), l.startTime = g, l.endTime = k2, l.payload = m) : l = new se(g, k2, m);
              yd(h);
              for (g = Bd(h); g; ) hF(l, g, b), yd(h), g = Bd(h);
              Fe(l, d2);
              f != null && (l.id = f);
              f = l;
            }
            f && e.push(f);
          }
          return e;
        };
        function hF(a, b, c) {
          var d2;
          if (d2 = /^align:(start|middle|center|end|left|right)$/.exec(b)) b = d2[1], b == "middle" ? a.textAlign = ue : a.textAlign = Se[b.toUpperCase()];
          else if (d2 = /^vertical:(lr|rl)$/.exec(b)) a.writingMode = d2[1] == "lr" ? "vertical-lr" : "vertical-rl";
          else if (d2 = /^size:([\d.]+)%$/.exec(b)) a.size = Number(d2[1]);
          else if (d2 = /^position:([\d.]+)%(?:,(line-left|line-right|middle|center|start|end|auto))?$/.exec(b)) a.position = Number(d2[1]), d2[2] && (b = d2[2], a.positionAlign = b == "line-left" || b == "start" ? "line-left" : b == "line-right" || b == "end" ? "line-right" : b == "center" || b == "middle" ? "center" : te);
          else if (d2 = /^region:(.*)$/.exec(b)) {
            if (b = iF(c, d2[1])) a.region = b;
          } else if (c = /^line:([\d.]+)%(?:,(start|end|center))?$/.exec(b)) a.lineInterpretation = 1, a.line = Number(c[1]), c[2] && (a.lineAlign = Ue[c[2].toUpperCase()]);
          else if (c = /^line:(-?\d+)(?:,(start|end|center))?$/.exec(b)) a.lineInterpretation = xe, a.line = Number(c[1]), c[2] && (a.lineAlign = Ue[c[2].toUpperCase()]);
        }
        function iF(a, b) {
          a = a.filter(function(c) {
            return c.id == b;
          });
          return a.length ? a[0] : null;
        }
        S("shaka.text.VttTextParser", gF);
        gF.prototype.parseMedia = gF.prototype.parseMedia;
        gF.prototype.setManifestType = gF.prototype.setManifestType;
        gF.prototype.setSequenceMode = gF.prototype.setSequenceMode;
        gF.prototype.parseInit = gF.prototype.parseInit;
        rf("text/vtt", function() {
          return new gF();
        });
        rf('text/vtt; codecs="vtt"', function() {
          return new gF();
        });
        rf('text/vtt; codecs="wvtt"', function() {
          return new gF();
        });
        function jF() {
          this.g = null;
        }
        jF.prototype.parseInit = function(a) {
          var b = this, c = false;
          new ph().box("moov", uh).box("trak", uh).box("mdia", uh).W("mdhd", function(d2) {
            d2 = Oi(d2.reader, d2.version);
            b.g = d2.timescale;
          }).box("minf", uh).box("stbl", uh).W("stsd", wh).box("wvtt", function() {
            c = true;
          }).parse(a);
          if (!this.g) throw new U(2, 2, 2008);
          if (!c) throw new U(2, 2, 2008);
        };
        jF.prototype.setSequenceMode = function() {
        };
        jF.prototype.setManifestType = function() {
        };
        jF.prototype.parseMedia = function(a, b) {
          if (!a.length) return [];
          if (!this.g) throw new U(2, 2, 2008);
          var c = 0, d2 = [], e, f = [], g = false, h = false, k2 = false, l = null;
          new ph().box("moof", uh).box("traf", uh).W("tfdt", function(A) {
            g = true;
            c = Ni(A.reader, A.version).baseMediaDecodeTime;
          }).W("tfhd", function(A) {
            l = Mi(A.reader, A.flags).ge;
          }).W("trun", function(A) {
            h = true;
            d2 = Pi(A.reader, A.version, A.flags).Zh;
          }).box("mdat", zh(function(A) {
            k2 = true;
            e = A;
          })).parse(a, false);
          if (!k2 && !g && !h) throw new U(2, 2, 2008);
          a = c;
          for (var m = new mh(e, 0), n = t2(d2), q = n.next(); !q.done; q = n.next()) {
            q = q.value;
            var r2 = q.$h || l, u = q.cg ? c + q.cg : a;
            a = u + (r2 || 0);
            var w = 0;
            do {
              var v = m.X();
              w += v;
              var y = m.X(), z = null;
              th(y) == "vttc" ? v > 8 && (z = m.$b(v - 8)) : m.skip(v - 8);
              r2 && z && (v = kF(z, b.periodStart + u / this.g, b.periodStart + a / this.g), f.push(v));
            } while (q.sampleSize && w < q.sampleSize);
          }
          return f.filter(Ff);
        };
        function kF(a, b, c) {
          var d2, e, f;
          new ph().box("payl", zh(function(g) {
            d2 = Xb(g);
          })).box("iden", zh(function(g) {
            e = Xb(g);
          })).box("sttg", zh(function(g) {
            f = Xb(g);
          })).parse(a);
          return d2 ? lF(d2, e, f, b, c) : null;
        }
        function lF(a, b, c, d2, e) {
          a = new se(d2, e, a);
          Fe(a);
          b && (a.id = b);
          if (c) for (b = new xd(c), c = Bd(b); c; ) hF(a, c, []), yd(b), c = Bd(b);
          return a;
        }
        S("shaka.text.Mp4VttParser", jF);
        jF.prototype.parseMedia = jF.prototype.parseMedia;
        jF.prototype.setManifestType = jF.prototype.setManifestType;
        jF.prototype.setSequenceMode = jF.prototype.setSequenceMode;
        jF.prototype.parseInit = jF.prototype.parseInit;
        rf('application/mp4; codecs="wvtt"', function() {
          return new jF();
        });
        function mF() {
        }
        mF.prototype.parseInit = function() {
        };
        mF.prototype.setSequenceMode = function() {
        };
        mF.prototype.setManifestType = function() {
        };
        mF.prototype.parseMedia = function(a) {
          var b = Xb(a).replace(/\r+/g, "");
          b = b.trim();
          a = [];
          if (b == "") return a;
          b = t2(b.split("\n\n"));
          for (var c = b.next(); !c.done; c = b.next()) {
            c = c.value.split("\n");
            var d2 = new xd(c[0]), e = Dd(d2), f = zd(d2, /,/g);
            d2 = Dd(d2);
            if (e == null || f == null || d2 == null) throw new U(2, 2, 2001, "Could not parse cue time range in SubViewer");
            a.push(new se(e, d2, c.slice(1).join("\n").trim()));
          }
          return a;
        };
        S("shaka.text.SbvTextParser", mF);
        mF.prototype.parseMedia = mF.prototype.parseMedia;
        mF.prototype.setManifestType = mF.prototype.setManifestType;
        mF.prototype.setSequenceMode = mF.prototype.setSequenceMode;
        mF.prototype.parseInit = mF.prototype.parseInit;
        rf("text/x-subviewer", function() {
          return new mF();
        });
        function nF() {
          this.g = new gF();
        }
        nF.prototype.parseInit = function() {
        };
        nF.prototype.setSequenceMode = function() {
        };
        nF.prototype.setManifestType = function() {
        };
        nF.prototype.parseMedia = function(a, b, c) {
          a = Xb(a);
          a = oF(a);
          a = Lb(ac(a));
          return this.g.parseMedia(a, b, c, []);
        };
        function oF(a) {
          var b = "WEBVTT\n\n";
          if (a == "") return b;
          a = a.replace(/\r+/g, "");
          a = a.trim();
          a = t2(a.split("\n\n"));
          for (var c = a.next(); !c.done; c = a.next()) c = c.value.split(/\n/), c[0].match(/\d+/) && c.shift(), c[0] = c[0].replace(/,/g, "."), b += c.join("\n").replace(/{b}/g, "<b>").replace(/{\/b}/g, "</b>").replace(/{i}/g, "<i>").replace(/{\/i}/g, "</i>").replace(/{u}/g, "<u>").replace(/{\/u}/g, "</u>") + "\n\n";
          return b;
        }
        S("shaka.text.SrtTextParser", nF);
        nF.srt2webvtt = oF;
        nF.prototype.parseMedia = nF.prototype.parseMedia;
        nF.prototype.setManifestType = nF.prototype.setManifestType;
        nF.prototype.setSequenceMode = nF.prototype.setSequenceMode;
        nF.prototype.parseInit = nF.prototype.parseInit;
        rf("text/srt", function() {
          return new nF();
        });
        function pF() {
        }
        pF.prototype.parseInit = function() {
        };
        pF.prototype.setSequenceMode = function() {
        };
        pF.prototype.setManifestType = function() {
        };
        pF.prototype.parseMedia = function(a) {
          var b = "", c = "", d2 = null, e = null;
          e = Xb(a).split(/\r?\n\s*\r?\n/);
          a = t2(e);
          for (e = a.next(); !e.done; e = a.next()) {
            var f = e.value;
            e = f;
            if (f = qF.exec(f)) d2 = f[1], e = f[2];
            d2 == "V4 Styles" || d2 == "V4+ Styles" ? (b = e, b = c ? b + ("\n" + e) : e) : d2 == "Events" && (c = c ? c + ("\n" + e) : e);
          }
          d2 = [];
          e = null;
          b = t2(b.split(/\r?\n/));
          for (a = b.next(); !a.done; a = b.next()) if (a = a.value, !/^\s*;/.test(a) && (f = rF.exec(a))) {
            if (a = f[1].trim(), f = f[2].trim(), a == "Format") e = f.split(sF);
            else if (a == "Style") {
              a = f.split(sF);
              f = {};
              for (var g = 0; g < e.length && g < a.length; g++) f[e[g]] = a[g];
              d2.push(f);
            }
          }
          e = [];
          b = null;
          c = t2(c.split(/\r?\n/));
          f = c.next();
          for (a = {}; !f.done; a = {
            Sj: void 0
          }, f = c.next()) if (f = f.value, !/^\s*;/.test(f) && (g = rF.exec(f))) {
            if (f = g[1].trim(), g = g[2].trim(), f == "Format") b = g.split(sF);
            else if (f == "Dialogue") {
              g = g.split(sF);
              f = {};
              for (var h = 0; h < b.length && h < g.length; h++) f[b[h]] = g[h];
              h = tF(f.Start);
              var k2 = tF(f.End);
              g = new se(h, k2, g.slice(b.length - 1).join(",").replace(/\\N/g, "\n").replace(/\{[^}]+\}/g, ""));
              a.Sj = f.Style;
              (a = d2.find(/* @__PURE__ */ function(l) {
                return function(m) {
                  return m.Name == l.Sj;
                };
              }(a))) && uF(g, a);
              e.push(g);
            }
          }
          return e;
        };
        function uF(a, b) {
          var c = b.Fontname;
          c && (a.fontFamily = c);
          if (c = b.Fontsize) a.fontSize = c + "px";
          if (c = b.PrimaryColour) {
            if (c = vF(c)) a.color = c;
          }
          if (c = b.BackColour) {
            if (c = vF(c)) a.backgroundColor = c;
          }
          b.Bold && (a.fontWeight = Pe);
          b.Italic && (a.fontStyle = Qe);
          b.Underline && a.textDecoration.push(Re);
          if (c = b.Spacing) a.letterSpacing = c + "px";
          if (c = b.Alignment) switch (parseInt(c, 10)) {
            case 1:
              a.displayAlign = ze;
              a.textAlign = "start";
              break;
            case 2:
              a.displayAlign = ze;
              a.textAlign = ue;
              break;
            case 3:
              a.displayAlign = ze;
              a.textAlign = "end";
              break;
            case 5:
              a.displayAlign = "before";
              a.textAlign = "start";
              break;
            case 6:
              a.displayAlign = "before";
              a.textAlign = ue;
              break;
            case 7:
              a.displayAlign = "before";
              a.textAlign = "end";
              break;
            case 9:
              a.displayAlign = "center";
              a.textAlign = "start";
              break;
            case 10:
              a.displayAlign = "center";
              a.textAlign = ue;
              break;
            case 11:
              a.displayAlign = "center", a.textAlign = "end";
          }
          if (b = b.AlphaLevel) a.opacity = parseFloat(b);
        }
        function vF(a) {
          a = parseInt(a.replace("&H", ""), 16);
          return a >= 0 ? "rgba(" + (a & 255) + "," + (a >> 8 & 255) + "," + (a >> 16 & 255) + "," + (a >> 24 & 255 ^ 255) / 255 + ")" : null;
        }
        function tF(a) {
          a = wF.exec(a);
          return (a[1] ? parseInt(a[1].replace(":", ""), 10) : 0) * 3600 + parseInt(a[2], 10) * 60 + parseFloat(a[3]);
        }
        S("shaka.text.SsaTextParser", pF);
        pF.prototype.parseMedia = pF.prototype.parseMedia;
        pF.prototype.setManifestType = pF.prototype.setManifestType;
        pF.prototype.setSequenceMode = pF.prototype.setSequenceMode;
        pF.prototype.parseInit = pF.prototype.parseInit;
        var qF = /^\s*\[([^\]]+)\]\r?\n([\s\S]*)/, rF = /^\s*([^:]+):\s*(.*)/, sF = /\s*,\s*/, wF = /^(\d+:)?(\d{1,2}):(\d{1,2}(?:[.]\d{1,3})?)?$/;
        rf("text/x-ssa", function() {
          return new pF();
        });
        function xF(a, b) {
          var c = a[b + 1] & 1 ? 7 : 9;
          return b + c <= a.length && (a = ((a[b + 3] & 3) << 11 | a[b + 4] << 3 | (a[b + 5] & 224) >>> 5) - c, a > 0) ? {
            qe: c,
            xa: a
          } : null;
        }
        function yF(a, b) {
          var c = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350], d2 = (a[b + 2] & 60) >>> 2;
          if (d2 > c.length - 1) return null;
          var e = ((a[b + 2] & 192) >>> 6) + 1, f = (a[b + 2] & 1) << 2;
          f |= (a[b + 3] & 192) >>> 6;
          return {
            sampleRate: c[d2],
            channelCount: f,
            codec: "mp4a.40." + e
          };
        }
        function zF(a, b) {
          if (b + 1 < a.length && a[b] === 255 && (a[b + 1] & 246) === 240) {
            var c = a[b + 1] & 1 ? 7 : 9;
            if (b + c >= a.length) return false;
            var d2 = (a[b + 3] & 3) << 11 | a[b + 4] << 3 | (a[b + 5] & 224) >>> 5;
            if (d2 <= c) return false;
            b += d2;
            return b === a.length || b + 1 < a.length && a[b] === 255 && (a[b + 1] & 246) === 240;
          }
          return false;
        }
        function AF(a, b) {
          switch (a) {
            case "mp4a.40.2":
              if (b === 1) return new Uint8Array([0, 200, 0, 128, 35, 128]);
              if (b === 2) return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);
              if (b === 3) return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);
              if (b === 4) return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);
              if (b === 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 (b === 6) return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 0, 178, 0, 32, 8, 224]);
              break;
            default:
              if (b === 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 (b === 2 || b === 3) return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);
          }
          return null;
        }
        ;
        function BF(a) {
          this.j = a;
          this.h = 0;
          this.g = /* @__PURE__ */ new Map();
          this.i = null;
        }
        p = BF.prototype;
        p.destroy = function() {
          this.g.clear();
        };
        p.isSupported = function(a) {
          return a.toLowerCase().split(";")[0] == "audio/aac" ? dd(this.convertCodecs("audio", a)) : false;
        };
        p.convertCodecs = function(a, b) {
          return b.toLowerCase().split(";")[0] == "audio/aac" ? 'audio/mp4; codecs="' + (of(b) || "mp4a.40.2") + '"' : b;
        };
        p.getOriginalMimeType = function() {
          return this.j;
        };
        p.transmux = function(a, b, c, d2) {
          for (var e = Lb(a), f = ck(e), g = f.length; g < e.length && !zF(e, g); g++) ;
          a = c.endTime * 1e3;
          f = bk(f);
          f.length && c && (f = f.find(function(m) {
            return m.description === "com.apple.streaming.transportStreamTimestamp";
          })) && (a = f.data);
          f = yF(e, g);
          if (!f) return Promise.reject(new U(2, 3, 3018, c ? c.T()[0] : null));
          b.audioSamplingRate = f.sampleRate;
          b.channelsCount = f.channelCount;
          for (var h = []; g < e.length; ) {
            var k2 = xF(e, g);
            if (!k2) return Promise.reject(new U(2, 3, 3018, c ? c.T()[0] : null));
            var l = k2.qe + k2.xa;
            g + l <= e.length && h.push({
              data: e.subarray(g + k2.qe, g + l),
              size: k2.xa,
              duration: 1024,
              Ab: 0,
              flags: {
                Cb: 0,
                ub: 0,
                sb: 0,
                pb: 0,
                qb: 2,
                Db: 0
              }
            });
            g += l;
          }
          e = f.sampleRate;
          a = Math.floor(a * e / 1e3);
          d2 = {
            id: b.id,
            type: "audio",
            codecs: f.codec,
            encrypted: b.encrypted && b.drmInfos.length > 0,
            timescale: e,
            duration: d2,
            Gb: [],
            Na: new Uint8Array([]),
            Xa: new Uint8Array([]),
            eb: 0,
            gb: 0,
            data: {
              sequenceNumber: this.h,
              baseMediaDecodeTime: a,
              Eb: h
            },
            stream: b
          };
          d2 = new Vi([d2]);
          c = b.id + "_" + c.i;
          this.g.has(c) ? b = this.g.get(c) : (b = Wi(d2), this.g.set(c, b));
          c = this.i !== b;
          d2 = qj(d2);
          this.i = b;
          this.h++;
          return c ? (b = mc(b, d2), Promise.resolve(b)) : Promise.resolve(d2);
        };
        S("shaka.transmuxer.AacTransmuxer", BF);
        BF.prototype.transmux = BF.prototype.transmux;
        BF.prototype.getOriginalMimeType = BF.prototype.getOriginalMimeType;
        BF.prototype.convertCodecs = BF.prototype.convertCodecs;
        BF.prototype.isSupported = BF.prototype.isSupported;
        BF.prototype.destroy = BF.prototype.destroy;
        Xe("audio/aac", function() {
          return new BF("audio/aac");
        }, cf);
        function CF(a, b) {
          if (b + 8 > a.length || a[b] !== 11 || a[b + 1] !== 119) return null;
          var c = a[b + 4] >> 6;
          if (c >= 3) return null;
          var d2 = a[b + 4] & 63, e = [64, 69, 96, 64, 70, 96, 80, 87, 120, 80, 88, 120, 96, 104, 144, 96, 105, 144, 112, 121, 168, 112, 122, 168, 128, 139, 192, 128, 140, 192, 160, 174, 240, 160, 175, 240, 192, 208, 288, 192, 209, 288, 224, 243, 336, 224, 244, 336, 256, 278, 384, 256, 279, 384, 320, 348, 480, 320, 349, 480, 384, 417, 576, 384, 418, 576, 448, 487, 672, 448, 488, 672, 512, 557, 768, 512, 558, 768, 640, 696, 960, 640, 697, 960, 768, 835, 1152, 768, 836, 1152, 896, 975, 1344, 896, 976, 1344, 1024, 1114, 1536, 1024, 1115, 1536, 1152, 1253, 1728, 1152, 1254, 1728, 1280, 1393, 1920, 1280, 1394, 1920][d2 * 3 + c] * 2;
          if (b + e > a.length) return null;
          var f = a[b + 6] >> 5, g = 0;
          f === 2 ? g += 2 : (f & 1 && f !== 1 && (g += 2), f & 4 && (g += 2));
          g = (a[b + 6] << 8 | a[b + 7]) >> 12 - g & 1;
          var h = a[b + 5] & 7;
          a = new Uint8Array([c << 6 | a[b + 5] >> 3 << 1 | h >> 2, (h & 3) << 6 | f << 3 | g << 2 | d2 >> 4, d2 << 4 & 224]);
          return {
            sampleRate: [48e3, 44100, 32e3][c],
            channelCount: [2, 1, 2, 3, 3, 4, 4, 5][f] + g,
            Na: a,
            xa: e
          };
        }
        function DF(a, b) {
          if (a[b] === 11 && a[b + 1] === 119) {
            var c = 0, d2 = 5;
            b += d2;
            for (var e, f; d2 > 0; ) {
              f = a[b];
              var g = Math.min(d2, 8), h = 8 - g;
              e = 4278190080 >>> 24 + h << h;
              e = (f & e) >> h;
              c = c ? c << g | e : e;
              b += 1;
              d2 -= g;
            }
            if (c < 16) return true;
          }
          return false;
        }
        ;
        function EF(a) {
          this.j = a;
          this.h = 0;
          this.g = /* @__PURE__ */ new Map();
          this.i = null;
        }
        p = EF.prototype;
        p.destroy = function() {
          this.g.clear();
        };
        p.isSupported = function(a) {
          return a.toLowerCase().split(";")[0] == "audio/ac3" ? dd(this.convertCodecs("audio", a)) : false;
        };
        p.convertCodecs = function(a, b) {
          return b.toLowerCase().split(";")[0] == "audio/ac3" ? Sb().Ce() ? 'audio/mp4; codecs="ec-3"' : 'audio/mp4; codecs="ac-3"' : b;
        };
        p.getOriginalMimeType = function() {
          return this.j;
        };
        p.transmux = function(a, b, c, d2) {
          a = Lb(a);
          for (var e = ck(a), f = e.length; f < a.length && !DF(a, f); f++) ;
          var g = c.endTime * 1e3;
          e = bk(e);
          e.length && c && (e = e.find(function(m) {
            return m.description === "com.apple.streaming.transportStreamTimestamp";
          })) && (g = e.data);
          e = 0;
          for (var h = new Uint8Array([]), k2 = []; f < a.length; ) {
            var l = CF(a, f);
            if (!l) return Promise.reject(new U(2, 3, 3018, c ? c.T()[0] : null));
            b.audioSamplingRate = l.sampleRate;
            b.channelsCount = l.channelCount;
            e = l.sampleRate;
            h = l.Na;
            k2.push({
              data: a.subarray(f, f + l.xa),
              size: l.xa,
              duration: 1536,
              Ab: 0,
              flags: {
                Cb: 0,
                ub: 0,
                sb: 0,
                pb: 0,
                qb: 2,
                Db: 0
              }
            });
            f += l.xa;
          }
          a = Math.floor(g * e / 1e3);
          d2 = {
            id: b.id,
            type: "audio",
            codecs: "ac-3",
            encrypted: b.encrypted && b.drmInfos.length > 0,
            timescale: e,
            duration: d2,
            Gb: [],
            Na: h,
            Xa: new Uint8Array([]),
            eb: 0,
            gb: 0,
            data: {
              sequenceNumber: this.h,
              baseMediaDecodeTime: a,
              Eb: k2
            },
            stream: b
          };
          d2 = new Vi([d2]);
          c = b.id + "_" + c.i;
          this.g.has(c) ? b = this.g.get(c) : (b = Wi(d2), this.g.set(c, b));
          c = this.i !== b;
          d2 = qj(d2);
          this.i = b;
          this.h++;
          return c ? (b = mc(b, d2), Promise.resolve(b)) : Promise.resolve(d2);
        };
        S("shaka.transmuxer.Ac3Transmuxer", EF);
        EF.prototype.transmux = EF.prototype.transmux;
        EF.prototype.getOriginalMimeType = EF.prototype.getOriginalMimeType;
        EF.prototype.convertCodecs = EF.prototype.convertCodecs;
        EF.prototype.isSupported = EF.prototype.isSupported;
        EF.prototype.destroy = EF.prototype.destroy;
        Xe("audio/ac3", function() {
          return new EF("audio/ac3");
        }, cf);
        function FF(a, b) {
          if (b + 8 > a.length || (a[b] << 8 | a[b + 1] << 0) !== 2935) return null;
          var c = new ek(a.subarray(b + 2));
          gk(c, 2);
          gk(c, 3);
          var d2 = hk(c, 11) + 1 << 1, e = hk(c, 2);
          if (e == 3) {
            e = hk(c, 2);
            e = [24e3, 22060, 16e3][e];
            var f = 3;
          } else e = [48e3, 44100, 32e3][e], f = hk(c, 2);
          var g = hk(c, 3), h = hk(c, 1);
          c = hk(c, 5);
          if (b + d2 > a.byteLength) return null;
          a = Math.floor(d2 * e / ([1, 2, 3, 6][f] * 16));
          a = new Uint8Array([(a & 8160) >> 5, (a & 31) << 3, e << 6 | c << 1 | 0, 0 | g << 1 | h << 0, 0]);
          return {
            sampleRate: e,
            channelCount: [2, 1, 2, 3, 3, 4, 4, 5][g] + h,
            Na: a,
            xa: d2
          };
        }
        ;
        function GF(a) {
          this.j = a;
          this.h = 0;
          this.g = /* @__PURE__ */ new Map();
          this.i = null;
        }
        p = GF.prototype;
        p.destroy = function() {
          this.g.clear();
        };
        p.isSupported = function(a) {
          return a.toLowerCase().split(";")[0] == "audio/ec3" ? dd(this.convertCodecs("audio", a)) : false;
        };
        p.convertCodecs = function(a, b) {
          return b.toLowerCase().split(";")[0] == "audio/ec3" ? 'audio/mp4; codecs="ec-3"' : b;
        };
        p.getOriginalMimeType = function() {
          return this.j;
        };
        p.transmux = function(a, b, c, d2) {
          a = Lb(a);
          for (var e = ck(a), f = e.length; f < a.length && (a[f] << 8 | a[f + 1] << 0) !== 2935; f++) ;
          var g = c.endTime * 1e3;
          e = bk(e);
          e.length && c && (e = e.find(function(m) {
            return m.description === "com.apple.streaming.transportStreamTimestamp";
          })) && (g = e.data);
          e = 0;
          for (var h = new Uint8Array([]), k2 = []; f < a.length; ) {
            var l = FF(a, f);
            if (!l) return Promise.reject(new U(2, 3, 3018, c ? c.T()[0] : null));
            b.audioSamplingRate = l.sampleRate;
            b.channelsCount = l.channelCount;
            e = l.sampleRate;
            h = l.Na;
            k2.push({
              data: a.subarray(f, f + l.xa),
              size: l.xa,
              duration: 1536,
              Ab: 0,
              flags: {
                Cb: 0,
                ub: 0,
                sb: 0,
                pb: 0,
                qb: 2,
                Db: 0
              }
            });
            f += l.xa;
          }
          a = Math.floor(g * e / 1e3);
          d2 = {
            id: b.id,
            type: "audio",
            codecs: "ec-3",
            encrypted: b.encrypted && b.drmInfos.length > 0,
            timescale: e,
            duration: d2,
            Gb: [],
            Na: h,
            Xa: new Uint8Array([]),
            eb: 0,
            gb: 0,
            data: {
              sequenceNumber: this.h,
              baseMediaDecodeTime: a,
              Eb: k2
            },
            stream: b
          };
          d2 = new Vi([d2]);
          c = b.id + "_" + c.i;
          this.g.has(c) ? b = this.g.get(c) : (b = Wi(d2), this.g.set(c, b));
          c = this.i !== b;
          d2 = qj(d2);
          this.i = b;
          this.h++;
          return c ? (b = mc(b, d2), Promise.resolve(b)) : Promise.resolve(d2);
        };
        S("shaka.transmuxer.Ec3Transmuxer", GF);
        GF.prototype.transmux = GF.prototype.transmux;
        GF.prototype.getOriginalMimeType = GF.prototype.getOriginalMimeType;
        GF.prototype.convertCodecs = GF.prototype.convertCodecs;
        GF.prototype.isSupported = GF.prototype.isSupported;
        GF.prototype.destroy = GF.prototype.destroy;
        Xe("audio/ec3", function() {
          return new GF("audio/ec3");
        }, cf);
        function HF(a) {
          if (!a.length) return null;
          var b = a.find(function(w) {
            return w.type == 7;
          });
          a = a.find(function(w) {
            return w.type == 8;
          });
          if (!b || !a) return null;
          var c = new ek(b.data), d2 = mk(c);
          mk(c);
          mk(c);
          jk(c);
          if (IF.includes(d2) && (d2 = X(c), d2 === 3 && gk(c, 1), jk(c), jk(c), gk(c, 1), lk(c))) {
            d2 = d2 !== 3 ? 8 : 12;
            for (var e = 0; e < d2; e++) lk(c) && (e < 6 ? nk(c, 16) : nk(c, 64));
          }
          jk(c);
          d2 = X(c);
          if (d2 === 0) X(c);
          else if (d2 === 1) for (gk(c, 1), jk(c), jk(c), d2 = X(c), e = 0; e < d2; e++) jk(c);
          jk(c);
          gk(c, 1);
          var f = X(c), g = X(c), h = hk(c, 1);
          h === 0 && gk(c, 1);
          gk(c, 1);
          var k2 = 0, l = 0, m = 0, n = 0;
          lk(c) && (k2 = X(c), l = X(c), m = X(c), n = X(c));
          e = d2 = 1;
          if (lk(c) && lk(c)) {
            var q = mk(c), r2 = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2], u = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
            q > 0 && q <= 16 ? (d2 = r2[q - 1], e = u[q - 1]) : q === 255 && (d2 = hk(c, 16), e = hk(c, 16));
          }
          c = (2 - h) * (g + 1) * 16 - m * 2 - n * 2;
          f = (f + 1) * 16 - k2 * 2 - l * 2;
          k2 = [];
          b = b.fullData;
          k2.push(b.byteLength >>> 8 & 255);
          k2.push(b.byteLength & 255);
          k2 = k2.concat.apply(k2, x(b));
          b = [];
          a = a.fullData;
          b.push(a.byteLength >>> 8 & 255);
          b.push(a.byteLength & 255);
          b = b.concat.apply(b, x(a));
          a = new Uint8Array([1, k2[3], k2[4], k2[5], 255, 225].concat(k2, [1], b));
          return {
            height: c,
            width: f,
            Xa: a,
            eb: d2,
            gb: e
          };
        }
        function JF(a) {
          function b(u) {
            e = {
              data: new Uint8Array([]),
              frame: false,
              isKeyframe: false,
              pts: u.pts,
              dts: u.dts,
              nalus: []
            };
          }
          function c() {
            if (e && e.nalus.length && e.frame) {
              for (var u = [], w = t2(e.nalus), v = w.next(); !v.done; v = w.next()) {
                v = v.value;
                var y = v.fullData.byteLength, z = new Uint8Array(4);
                z[0] = y >> 24 & 255;
                z[1] = y >> 16 & 255;
                z[2] = y >> 8 & 255;
                z[3] = y & 255;
                u.push(z);
                u.push(v.fullData);
              }
              e.data = mc.apply(ec, x(u));
              d2.push(e);
            }
          }
          for (var d2 = [], e = null, f = false, g = 0; g < a.length; g++) {
            var h = a[g], k2 = h.nalus, l = false;
            e && k2.length && !f && (c(), b(h));
            k2 = t2(h.nalus);
            for (var m = k2.next(); !m.done; m = k2.next()) {
              m = m.value;
              var n = false;
              switch (m.type) {
                case 1:
                  var q = false;
                  n = true;
                  var r2 = m.data;
                  l && r2.length > 4 && (r2 = ok(new ek(r2)), r2 === 2 || r2 === 4 || r2 === 7 || r2 === 9) && (q = true);
                  q && e && e.frame && !e.isKeyframe && (c(), e = null);
                  e || b(h);
                  e.frame = true;
                  e.isKeyframe = q;
                  break;
                case 5:
                  n = true;
                  e && e.frame && !e.isKeyframe && (c(), e = null);
                  e || b(h);
                  e.frame = true;
                  e.isKeyframe = true;
                  break;
                case 6:
                  n = true;
                  break;
                case 7:
                  l = n = true;
                  break;
                case 8:
                  n = true;
                  break;
                case 9:
                  f = n = true;
                  e && e.frame && (c(), e = null);
                  e || b(h);
                  break;
                case 12:
                  n = true;
                  break;
                default:
                  n = false;
              }
              e && n && e.nalus.push(m);
            }
          }
          c();
          return d2;
        }
        var IF = [100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134];
        function KF(a) {
          if (!a.length) return null;
          var b = a.find(function(g) {
            return g.type == 32;
          }), c = a.find(function(g) {
            return g.type == 33;
          }), d2 = a.find(function(g) {
            return g.type == 34;
          });
          if (!b || !c || !d2) return null;
          var e = LF(b.fullData);
          a = MF(c.fullData);
          var f = NF(d2.fullData);
          b = OF(b.fullData, c.fullData, d2.fullData, {
            Mh: e.Mh,
            ri: e.ri,
            jh: a.jh,
            kh: a.kh,
            dh: a.dh,
            ih: a.ih,
            eh: a.eh,
            fh: a.fh,
            gh: a.gh,
            hh: a.hh,
            Xg: a.Xg,
            Yg: a.Yg,
            Zg: a.Zg,
            $g: a.$g,
            ah: a.ah,
            bh: a.bh,
            Pg: a.Pg,
            Lf: a.Lf,
            Ng: a.Ng,
            Jg: a.Jg,
            Ig: a.Ig,
            Oh: f.Oh
          });
          return {
            height: a.height,
            width: a.width,
            Xa: b,
            eb: a.lm,
            gb: a.jm
          };
        }
        function LF(a) {
          var b = new ek(a, true);
          mk(b);
          mk(b);
          hk(b, 4);
          hk(b, 2);
          hk(b, 6);
          a = hk(b, 3);
          b = lk(b);
          return {
            Mh: a + 1,
            ri: b
          };
        }
        function MF(a) {
          a = new ek(a, true);
          mk(a);
          mk(a);
          var b = 0, c = 0, d2 = 0, e = 0;
          hk(a, 4);
          var f = hk(a, 3);
          lk(a);
          for (var g = hk(a, 2), h = hk(a, 1), k2 = hk(a, 5), l = mk(a), m = mk(a), n = mk(a), q = mk(a), r2 = mk(a), u = mk(a), w = mk(a), v = mk(a), y = mk(a), z = mk(a), A = mk(a), C = [], D = [], F = 0; F < f; F++) C.push(lk(a)), D.push(lk(a));
          if (f > 0) for (F = f; F < 8; F++) hk(a, 2);
          for (F = 0; F < f; F++) C[F] && hk(a, 88), D[F] && mk(a);
          X(a);
          C = X(a);
          C == 3 && hk(a, 1);
          D = X(a);
          F = X(a);
          lk(a) && (b += X(a), c += X(a), d2 += X(a), e += X(a));
          var B = X(a), E = X(a), I = X(a);
          if (lk(a)) for (var J = 0; J <= f; J++) X(a), X(a), X(a);
          else X(a), X(a), X(a);
          X(a);
          X(a);
          X(a);
          X(a);
          X(a);
          X(a);
          if (lk(a) && lk(a)) for (J = 0; J < 4; J++) for (var K = 0; K < (J === 3 ? 2 : 6); K++) if (lk(a)) {
            var L = Math.min(64, 1 << 4 + (J << 1));
            J > 1 && kk(a);
            for (var M = 0; M < L; M++) kk(a);
          } else X(a);
          lk(a);
          lk(a);
          lk(a) && (mk(a), X(a), X(a), lk(a));
          J = X(a);
          for (L = K = 0; L < J; L++) if (M = false, L !== 0 && (M = lk(a)), M) {
            L === J && X(a);
            lk(a);
            X(a);
            for (var N = M = 0; N <= K; N++) {
              var O = lk(a), Q = false;
              O || (Q = lk(a));
              (O || Q) && M++;
            }
            K = M;
          } else {
            N = X(a);
            M = X(a);
            K = N + M;
            for (O = 0; O < N; O++) X(a), lk(a);
            for (N = 0; N < M; N++) X(a), lk(a);
          }
          if (lk(a)) for (J = X(a), K = 0; K < J; K++) {
            for (L = 0; L < I + 4; L++) hk(a, 1);
            hk(a, 1);
          }
          J = I = 1;
          K = 0;
          lk(a);
          lk(a);
          if (lk(a)) {
            lk(a) && (L = mk(a), M = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2], N = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1], L > 0 && L <= 16 ? (I = M[L - 1], J = N[L - 1]) : L === 255 && (I = hk(a, 16), J = hk(a, 16)));
            lk(a) && lk(a);
            lk(a) && (hk(a, 3), lk(a), lk(a) && (mk(a), mk(a), mk(a)));
            lk(a) && (X(a), X(a));
            lk(a);
            lk(a);
            lk(a);
            if (L = lk(a)) X(a), X(a), X(a), X(a);
            if (lk(a) && (hk(a, 32), hk(a, 32), lk(a) && X(a), lk(a))) {
              N = false;
              L = lk(a);
              M = lk(a);
              if (L || M) {
                if (N = lk(a)) mk(a), hk(a, 5), lk(a), hk(a, 5);
                hk(a, 4);
                hk(a, 4);
                N && hk(a, 4);
                hk(a, 5);
                hk(a, 5);
                hk(a, 5);
              }
              for (O = 0; O <= f; O++) {
                var R = true;
                Q = 1;
                lk(a) || (R = lk(a));
                var V = false;
                R ? X(a) : V = lk(a);
                V || (Q = X(a) + 1);
                if (L) {
                  for (R = 0; R < Q; R++) X(a), X(a), N && (X(a), X(a));
                  lk(a);
                }
                if (M) {
                  for (R = 0; R < Q; R++) X(a), X(a), N && (X(a), X(a));
                  lk(a);
                }
              }
            }
            lk(a) && (lk(a), lk(a), lk(a), K = X(a), X(a), X(a), X(a), X(a));
          }
          return {
            dh: A,
            jh: g,
            kh: h,
            ih: k2,
            eh: l,
            fh: m,
            gh: n,
            hh: q,
            Xg: r2,
            Yg: u,
            Zg: w,
            $g: v,
            ah: y,
            bh: z,
            Lf: K,
            Pg: 0,
            Ng: C,
            Jg: B,
            Ig: E,
            width: D - (b + c) * (C === 1 || C === 2 ? 2 : 1),
            height: F - (d2 + e) * (C === 1 ? 2 : 1),
            lm: I,
            jm: J
          };
        }
        function NF(a) {
          var b = new ek(a, true);
          mk(b);
          mk(b);
          X(b);
          X(b);
          lk(b);
          lk(b);
          hk(b, 3);
          lk(b);
          lk(b);
          X(b);
          X(b);
          kk(b);
          lk(b);
          lk(b);
          lk(b) && X(b);
          kk(b);
          kk(b);
          lk(b);
          lk(b);
          lk(b);
          lk(b);
          a = lk(b);
          b = lk(b);
          var c = 1;
          b && a ? c = 0 : b ? c = 3 : a && (c = 2);
          return {
            Oh: c
          };
        }
        function OF(a, b, c, d2) {
          var e = new Uint8Array(23 + (5 + a.byteLength) + (5 + b.byteLength) + (5 + c.byteLength));
          e[0] = 1;
          e[1] = (d2.jh & 3) << 6 | (d2.kh ? 1 : 0) << 5 | d2.ih & 31;
          e[2] = d2.eh;
          e[3] = d2.fh;
          e[4] = d2.gh;
          e[5] = d2.hh;
          e[6] = d2.Xg;
          e[7] = d2.Yg;
          e[8] = d2.Zg;
          e[9] = d2.$g;
          e[10] = d2.ah;
          e[11] = d2.bh;
          e[12] = d2.dh;
          e[13] = 240 | (d2.Lf & 3840) >> 8;
          e[14] = d2.Lf & 255;
          e[15] = 252 | d2.Oh & 3;
          e[16] = 252 | d2.Ng & 3;
          e[17] = 248 | d2.Jg & 7;
          e[18] = 248 | d2.Ig & 7;
          e[19] = 0;
          e[20] = 0;
          e[21] = (d2.Pg & 3) << 6 | (d2.Mh & 7) << 3 | (d2.ri ? 1 : 0) << 2 | 3;
          e[22] = 3;
          e[23] = 160;
          e[24] = 0;
          e[25] = 1;
          e[26] = (a.byteLength & 65280) >> 8;
          e[27] = (a.byteLength & 255) >> 0;
          e.set(a, 28);
          e[23 + (5 + a.byteLength)] = 161;
          e[23 + (5 + a.byteLength) + 1] = 0;
          e[23 + (5 + a.byteLength) + 2] = 1;
          e[23 + (5 + a.byteLength) + 3] = (b.byteLength & 65280) >> 8;
          e[23 + (5 + a.byteLength) + 4] = (b.byteLength & 255) >> 0;
          e.set(b, 23 + (5 + a.byteLength) + 5);
          e[23 + (5 + a.byteLength + 5 + b.byteLength)] = 162;
          e[23 + (5 + a.byteLength + 5 + b.byteLength) + 1] = 0;
          e[23 + (5 + a.byteLength + 5 + b.byteLength) + 2] = 1;
          e[23 + (5 + a.byteLength + 5 + b.byteLength) + 3] = (c.byteLength & 65280) >> 8;
          e[23 + (5 + a.byteLength + 5 + b.byteLength) + 4] = (c.byteLength & 255) >> 0;
          e.set(c, 23 + (5 + a.byteLength + 5 + b.byteLength) + 5);
          return e;
        }
        ;
        function PF(a, b) {
          var c = a[b + 1] >> 3 & 3, d2 = a[b + 1] >> 1 & 3, e = a[b + 2] >> 4 & 15, f = a[b + 2] >> 2 & 3;
          if (c !== 1 && e !== 0 && e !== 15 && f !== 3) {
            var g = a[b + 3] >> 6;
            e = QF[(c === 3 ? 3 - d2 : d2 === 3 ? 3 : 4) * 14 + e - 1] * 1e3;
            f = RF[(c === 3 ? 0 : c === 2 ? 1 : 2) * 3 + f];
            c = SF[c][d2];
            var h = TF[d2], k2 = Math.floor(c * e / f + (a[b + 2] >> 1 & 1)) * h, l = (navigator.userAgent || "").match(/Chrome\/(\d+)/i);
            (l = l ? parseInt(l[1], 10) : 0) && l <= 87 && d2 === 2 && e >= 224e3 && g === 0 && (a[b + 3] |= 128);
            return {
              sampleRate: f,
              channelCount: g === 3 ? 1 : 2,
              xa: k2,
              im: c * 8 * h
            };
          }
          return null;
        }
        function UF(a, b) {
          return a[b] === 255 && (a[b + 1] & 224) === 224 && (a[b + 1] & 6) !== 0;
        }
        function VF(a, b) {
          if (b + 1 < a.length && UF(a, b)) {
            var c = PF(a, b), d2 = 4;
            c && c.xa && (d2 = c.xa);
            b += d2;
            return b === a.length || b + 1 < a.length && UF(a, b);
          }
          return false;
        }
        var QF = [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], RF = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3], SF = [[0, 72, 144, 12], [0, 0, 0, 0], [0, 72, 144, 12], [0, 144, 144, 12]], TF = [0, 1, 1, 4];
        function WF(a) {
          this.j = a;
          this.h = 0;
          this.g = /* @__PURE__ */ new Map();
          this.i = null;
        }
        p = WF.prototype;
        p.destroy = function() {
          this.g.clear();
        };
        p.isSupported = function(a) {
          return a.toLowerCase().split(";")[0] == "audio/mpeg" ? dd(this.convertCodecs("audio", a)) : false;
        };
        p.convertCodecs = function(a, b) {
          return b.toLowerCase().split(";")[0] == "audio/mpeg" ? 'audio/mp4; codecs="mp3"' : b;
        };
        p.getOriginalMimeType = function() {
          return this.j;
        };
        p.transmux = function(a, b, c, d2) {
          for (var e = Lb(a), f = ck(e).length; f < e.length && !VF(e, f); f++) ;
          var g;
          for (a = []; f < e.length; ) {
            var h = PF(e, f);
            if (!h) return Promise.reject(new U(2, 3, 3018, c ? c.T()[0] : null));
            g || (g = h);
            f + h.xa <= e.length && a.push({
              data: e.subarray(f, f + h.xa),
              size: h.xa,
              duration: 1152,
              Ab: 0,
              flags: {
                Cb: 0,
                ub: 0,
                sb: 0,
                pb: 0,
                qb: 2,
                Db: 0
              }
            });
            f += h.xa;
          }
          if (!g) return Promise.reject(new U(2, 3, 3018, c ? c.T()[0] : null));
          e = g.im * 9e4 / g.sampleRate * this.h;
          d2 = {
            id: b.id,
            type: "audio",
            codecs: "mp3",
            encrypted: b.encrypted && b.drmInfos.length > 0,
            timescale: g.sampleRate,
            duration: d2,
            Gb: [],
            Na: new Uint8Array([]),
            Xa: new Uint8Array([]),
            eb: 0,
            gb: 0,
            data: {
              sequenceNumber: this.h,
              baseMediaDecodeTime: e,
              Eb: a
            },
            stream: b
          };
          d2 = new Vi([d2]);
          c = b.id + "_" + c.i;
          this.g.has(c) ? b = this.g.get(c) : (b = Wi(d2), this.g.set(c, b));
          c = this.i !== b;
          d2 = qj(d2);
          this.i = b;
          this.h++;
          return c ? (b = mc(b, d2), Promise.resolve(b)) : Promise.resolve(d2);
        };
        S("shaka.transmuxer.Mp3Transmuxer", WF);
        WF.prototype.transmux = WF.prototype.transmux;
        WF.prototype.getOriginalMimeType = WF.prototype.getOriginalMimeType;
        WF.prototype.convertCodecs = WF.prototype.convertCodecs;
        WF.prototype.isSupported = WF.prototype.isSupported;
        WF.prototype.destroy = WF.prototype.destroy;
        Xe("audio/mpeg", function() {
          return new WF("audio/mpeg");
        }, cf);
        function XF(a) {
          this.h = a;
          this.g = null;
        }
        p = XF.prototype;
        p.destroy = function() {
        };
        p.isSupported = function(a) {
          if (a.toLowerCase().split(";")[0] != "video/mp2t") return false;
          var b = of(a).split(","), c = rc("audio", b);
          b = rc("video", b);
          return !c || b || kf(c) != "mp3" ? false : dd(this.convertCodecs("audio", a));
        };
        p.convertCodecs = function(a, b) {
          return b.toLowerCase().split(";")[0] == "video/mp2t" ? "audio/mpeg" : b;
        };
        p.getOriginalMimeType = function() {
          return this.h;
        };
        p.transmux = function(a, b, c, d2, e) {
          this.g ? this.g.clearData() : this.g = new pk();
          this.g.gg(c.i);
          a = Lb(a);
          a = this.g.parse(a);
          if (a.je().audio != "mp3" || e != "audio") return Promise.reject(new U(2, 3, 3018, c ? c.T()[0] : null));
          c = new Uint8Array([]);
          e = t2(a.Bb());
          for (a = e.next(); !a.done; a = e.next()) if (a = a.value.data) for (b = 0; b < a.length; ) (d2 = PF(a, b)) ? (b + d2.xa <= a.length && (c = mc(c, a.subarray(b, b + d2.xa))), b += d2.xa) : b++;
          return Promise.resolve(c);
        };
        S("shaka.transmuxer.MpegTsTransmuxer", XF);
        XF.prototype.transmux = XF.prototype.transmux;
        XF.prototype.getOriginalMimeType = XF.prototype.getOriginalMimeType;
        XF.prototype.convertCodecs = XF.prototype.convertCodecs;
        XF.prototype.isSupported = XF.prototype.isSupported;
        XF.prototype.destroy = XF.prototype.destroy;
        Xe("video/mp2t", function() {
          return new XF("video/mp2t");
        }, bf);
        function YF(a) {
          this.h = a;
          (this.g = Cx.get("ISOBoxer")()) && ZF(this);
        }
        function ZF(a) {
          function b() {
            this._procFullBox();
            this.flags & 1 && (this._procField("AlgorithmID", "uint", 24), this._procField("IV_size", "uint", 8), this._procFieldArray("KID", 16, "uint", 8));
            this._procField("sample_count", "uint", 32);
            this._procEntries("entry", this.sample_count, function(c) {
              this._procEntryField(c, "InitializationVector", "data", 8);
              this.flags & 2 && (this._procEntryField(c, "NumberOfEntries", "uint", 16), this._procSubEntries(c, "clearAndCryptedData", c.NumberOfEntries, function(d2) {
                this._procEntryField(d2, "BytesOfClearData", "uint", 16);
                this._procEntryField(d2, "BytesOfEncryptedData", "uint", 32);
              }));
            });
          }
          a.g.addBoxProcessor("saio", function() {
            this._procFullBox();
            this.flags & 1 && (this._procField("aux_info_type", "uint", 32), this._procField("aux_info_type_parameter", "uint", 32));
            this._procField("entry_count", "uint", 32);
            this._procFieldArray("offset", this.entry_count, "uint", this.version === 1 ? 64 : 32);
          });
          a.g.addBoxProcessor("saiz", function() {
            this._procFullBox();
            this.flags & 1 && (this._procField("aux_info_type", "uint", 32), this._procField("aux_info_type_parameter", "uint", 32));
            this._procField("default_sample_info_size", "uint", 8);
            this._procField("sample_count", "uint", 32);
            this.default_sample_info_size === 0 && this._procFieldArray("sample_info_size", this.sample_count, "uint", 8);
          });
          a.g.addBoxProcessor("senc", b);
          a.g.addBoxProcessor("uuid", function() {
            for (var c = true, d2 = 0; d2 < 16; d2++) this.usertype[d2] !== $F[d2] && (c = false);
            c && (this._parsing && (this.type = "sepiff"), b.call(this));
          });
        }
        p = YF.prototype;
        p.destroy = function() {
        };
        p.isSupported = function(a, b) {
          var c = a.startsWith("mss/");
          if (!this.g || !c) return false;
          if (b) return dd(this.convertCodecs(b, a));
          b = this.convertCodecs("audio", a);
          a = this.convertCodecs("video", a);
          return dd(b) || dd(a);
        };
        p.convertCodecs = function(a, b) {
          return b.replace("mss/", "");
        };
        p.getOriginalMimeType = function() {
          return this.h;
        };
        p.transmux = function(a, b, c) {
          if (!c) return Promise.resolve(Lb(a));
          if (!b.mssPrivateData) return Promise.reject(new U(2, 3, 3020, c ? c.T()[0] : null));
          try {
            var d2, e = this.g.parseBuffer(a), f = e.fetch("tfhd");
            f.track_ID = b.id + 1;
            var g = e.fetch("tfdt"), h = e.fetch("traf");
            g === null && (g = this.g.createFullBox("tfdt", h, f), g.version = 1, g.flags = 0, g.baseMediaDecodeTime = Math.floor(c.startTime * b.mssPrivateData.timescale));
            var k2 = e.fetch("trun"), l = e.fetch("tfxd");
            l && l._parent.boxes.splice(l._parent.boxes.indexOf(l), 1);
            var m = e.fetch("tfrf");
            m && m._parent.boxes.splice(m._parent.boxes.indexOf(m), 1);
            var n = e.fetch("sepiff");
            if (n !== null) {
              n.type = "senc";
              n.usertype = void 0;
              var q = e.fetch("saio");
              if (q === null) {
                q = this.g.createFullBox("saio", h);
                q.version = 0;
                q.flags = 0;
                q.entry_count = 1;
                q.offset = [0];
                var r2 = this.g.createFullBox("saiz", h);
                r2.version = 0;
                r2.flags = 0;
                r2.sample_count = n.sample_count;
                r2.default_sample_info_size = 0;
                r2.sample_info_size = [];
                if (n.flags & 2) for (d2 = 0; d2 < n.sample_count; d2 += 1) r2.sample_info_size[d2] = 10 + 6 * n.entry[d2].NumberOfEntries;
                else r2.default_sample_info_size = 8;
              }
            }
            f.flags &= 16777214;
            f.flags |= 131072;
            k2.flags |= 1;
            var u = e.fetch("moof");
            k2.data_offset = u.getLength() + 8;
            var w = e.fetch("saio");
            w !== null && (w.offset[0] = aG(u, "traf") + aG(h, "senc") + 16);
            var v = Lb(e.write());
            return Promise.resolve(v);
          } catch (y) {
            return y instanceof U ? Promise.reject(y) : Promise.reject(new U(2, 3, 3022, c ? c.T()[0] : null));
          }
        };
        function aG(a, b) {
          for (var c = 8, d2 = 0; d2 < a.boxes.length && a.boxes[d2].type !== b; d2++) c += a.boxes[d2].size;
          return c;
        }
        S("shaka.transmuxer.MssTransmuxer", YF);
        YF.prototype.transmux = YF.prototype.transmux;
        YF.prototype.getOriginalMimeType = YF.prototype.getOriginalMimeType;
        YF.prototype.convertCodecs = YF.prototype.convertCodecs;
        YF.prototype.isSupported = YF.prototype.isSupported;
        YF.prototype.destroy = YF.prototype.destroy;
        var $F = new Uint8Array([162, 57, 79, 82, 90, 155, 79, 20, 162, 68, 108, 66, 124, 100, 141, 244]);
        Xe("mss/audio/mp4", function() {
          return new YF("mss/audio/mp4");
        }, cf);
        Xe("mss/video/mp4", function() {
          return new YF("mss/video/mp4");
        }, cf);
        function bG(a) {
          this.m = a;
          this.g = 0;
          this.j = /* @__PURE__ */ new Map();
          this.l = this.i = this.h = null;
        }
        p = bG.prototype;
        p.destroy = function() {
          this.j.clear();
          this.i && this.i.destroy();
        };
        p.isSupported = function(a, b) {
          if (a.toLowerCase().split(";")[0] != "video/mp2t") return false;
          var c = a;
          b && (c = this.convertCodecs(b, a));
          var d2 = of(c).split(",");
          c = rc("audio", d2);
          d2 = rc("video", d2);
          if (c && (c = kf(c), !cG.includes(c)) || d2 && (c = kf(d2), !dG.includes(c))) return false;
          if (b) return dd(this.convertCodecs(b, a));
          b = this.convertCodecs("audio", a);
          a = this.convertCodecs("video", a);
          return dd(b) || dd(a);
        };
        p.convertCodecs = function(a, b) {
          return b.toLowerCase().split(";")[0] == "video/mp2t" ? (b = of(b).replace("mp4a.40.34", "mp3").split(",").map(function(c) {
            return Yf(c, "audio/mp4");
          }).map(Zf).join(","), a == "audio" ? 'audio/mp4; codecs="' + b + '"' : 'video/mp4; codecs="' + b + '"') : b;
        };
        p.getOriginalMimeType = function() {
          return this.m;
        };
        p.transmux = function(a, b, c, d2, e) {
          var f = Lb(a);
          if (e == "audio" && !xk(f)) {
            for (var g = ck(f), h = g.length; h < f.length; h++) if (VF(f, h)) return Promise.reject(new U(2, 3, 3018, c ? c.T()[0] : null));
            for (h = g.length; h < f.length; h++) if (zF(f, h)) return this.i || (this.i = new BF("audio/aac")), this.i.transmux(a, b, c, d2, e);
            return Promise.reject(new U(2, 3, 3018, c ? c.T()[0] : null));
          }
          this.h ? this.h.clearData() : this.h = new pk();
          this.h.gg(c.i);
          var k2 = this.h.parse(f), l = [], m = k2.je();
          try {
            var n = null;
            if (e == "video") {
              switch (m.video) {
                case "avc":
                  var q = [], r2 = null, u = k2.hd(), w = JF(u);
                  if (!w.length) throw new U(2, 3, 3023, c ? c.T()[0] : null);
                  for (var v = 0; v < w.length; v++) {
                    var y = w[v];
                    r2 == null && (r2 = y.dts);
                    var z = void 0;
                    z = v + 1 < w.length ? (w[v + 1].dts || 0) - (y.dts || 0) : w.length > 1 ? (y.dts || 0) - (w[v - 1].dts || 0) : (c.endTime - c.startTime) * 9e4;
                    q.push({
                      data: y.data,
                      size: y.data.byteLength,
                      duration: z,
                      Ab: Math.round((y.pts || 0) - (y.dts || 0)),
                      flags: {
                        Cb: 0,
                        ub: 0,
                        sb: 0,
                        pb: 0,
                        qb: y.isKeyframe ? 2 : 1,
                        Db: y.isKeyframe ? 0 : 1
                      }
                    });
                  }
                  for (var A = [], C = t2(u), D = C.next(); !D.done; D = C.next()) A.push.apply(A, x(D.value.nalus));
                  var F = HF(A);
                  if (!F || r2 == null) throw new U(2, 3, 3018, c ? c.T()[0] : null);
                  b.height = F.height;
                  b.width = F.width;
                  n = {
                    id: b.id,
                    type: "video",
                    codecs: "avc1",
                    encrypted: b.encrypted && b.drmInfos.length > 0,
                    timescale: 9e4,
                    duration: d2,
                    Gb: [],
                    Na: new Uint8Array([]),
                    Xa: F.Xa,
                    eb: F.eb,
                    gb: F.gb,
                    data: {
                      sequenceNumber: this.g,
                      baseMediaDecodeTime: r2,
                      Eb: q
                    },
                    stream: b
                  };
                  break;
                case "hvc":
                  var B = [], E = null, I = [], J = k2.hd();
                  if (!J.length) throw new U(2, 3, 3023, c ? c.T()[0] : null);
                  for (var K = 0; K < J.length; K++) {
                    var L = J[K], M = L.nalus;
                    I.push.apply(I, x(M));
                    for (var N = false, O = [], Q = false, R = t2(M), V = R.next(); !V.done; V = R.next()) {
                      var Ba = V.value;
                      switch (Ba.type) {
                        case 1:
                        case 0:
                          var aa = Q = true;
                          break;
                        case 19:
                        case 20:
                        case 21:
                          N = aa = Q = true;
                          break;
                        case 32:
                          aa = true;
                          break;
                        case 33:
                          aa = true;
                          break;
                        case 34:
                          aa = true;
                          break;
                        case 35:
                          Q = aa = true;
                          break;
                        case 39:
                        case 40:
                          aa = true;
                          break;
                        default:
                          aa = false;
                      }
                      if (Q && aa) {
                        var Oa = Ba.fullData.byteLength, La = new Uint8Array(4);
                        La[0] = Oa >> 24 & 255;
                        La[1] = Oa >> 16 & 255;
                        La[2] = Oa >> 8 & 255;
                        La[3] = Oa & 255;
                        O.push(La);
                        O.push(Ba.fullData);
                      }
                    }
                    var Ja = O.length ? {
                      data: mc.apply(ec, x(O)),
                      isKeyframe: N
                    } : null;
                    if (Ja) {
                      E == null && L.dts != null && (E = L.dts);
                      var Ea = void 0;
                      Ea = K + 1 < J.length ? (J[K + 1].dts || 0) - (L.dts || 0) : J.length > 1 ? (L.dts || 0) - (J[K - 1].dts || 0) : (c.endTime - c.startTime) * 9e4;
                      B.push({
                        data: Ja.data,
                        size: Ja.data.byteLength,
                        duration: Ea,
                        Ab: Math.round((L.pts || 0) - (L.dts || 0)),
                        flags: {
                          Cb: 0,
                          ub: 0,
                          sb: 0,
                          pb: 0,
                          qb: Ja.isKeyframe ? 2 : 1,
                          Db: Ja.isKeyframe ? 0 : 1
                        }
                      });
                    }
                  }
                  var ya = KF(I);
                  if (!ya || E == null) throw new U(2, 3, 3018, c ? c.T()[0] : null);
                  b.height = ya.height;
                  b.width = ya.width;
                  n = {
                    id: b.id,
                    type: "video",
                    codecs: "hvc1",
                    encrypted: b.encrypted && b.drmInfos.length > 0,
                    timescale: 9e4,
                    duration: d2,
                    Gb: [],
                    Na: new Uint8Array([]),
                    Xa: ya.Xa,
                    eb: ya.eb,
                    gb: ya.gb,
                    data: {
                      sequenceNumber: this.g,
                      baseMediaDecodeTime: E,
                      Eb: B
                    },
                    stream: b
                  };
              }
              n && (l.push(n), n = null);
            }
            if (e == "audio") {
              switch (m.audio) {
                case "aac":
                  for (var Fa = [], Da, za = null, Ca = null, fb = null, hb = t2(k2.Bb()), ib = hb.next(); !ib.done; ib = hb.next()) {
                    var xb = ib.value, vb = xb.data;
                    if (vb) {
                      var Va = 0;
                      if (Ca == -1 && fb) vb = mc(fb, xb.data), Ca = null;
                      else if (Ca != null && fb) {
                        Va = Math.max(0, Ca);
                        var Wd = mc(fb, vb.subarray(0, Va));
                        Fa.push({
                          data: Wd,
                          size: Wd.byteLength,
                          duration: 1024,
                          Ab: 0,
                          flags: {
                            Cb: 0,
                            ub: 0,
                            sb: 0,
                            pb: 0,
                            qb: 2,
                            Db: 0
                          }
                        });
                        Ca = fb = null;
                      }
                      Da = yF(vb, Va);
                      if (!Da) throw new U(2, 3, 3018, c ? c.T()[0] : null);
                      b.audioSamplingRate = Da.sampleRate;
                      b.channelsCount = Da.channelCount;
                      za == null && xb.pts !== null && (za = xb.pts);
                      for (; Va < vb.length; ) {
                        var Lc = xF(vb, Va);
                        if (!Lc) {
                          fb = vb.subarray(Va, vb.length);
                          Ca = -1;
                          break;
                        }
                        var Ee = Lc.qe + Lc.xa;
                        Ca = Math.max(0, Va + Ee - vb.length);
                        Ca != 0 ? fb = vb.subarray(Va + Lc.qe, Va + Ee) : Va + Ee <= vb.length && Fa.push({
                          data: vb.subarray(Va + Lc.qe, Va + Ee),
                          size: Lc.xa,
                          duration: 1024,
                          Ab: 0,
                          flags: {
                            Cb: 0,
                            ub: 0,
                            sb: 0,
                            pb: 0,
                            qb: 2,
                            Db: 0
                          }
                        });
                        Va += Ee;
                      }
                    }
                  }
                  if (!Da || za == null) {
                    if (!k2.hd().length) throw new U(2, 3, 3018, c ? c.T()[0] : null);
                    za = c.startTime * 9e4;
                    var Ad = rc("audio", b.codecs.split(","));
                    if (!Ad || !b.channelsCount || !b.audioSamplingRate) throw new U(2, 3, 3018, c ? c.T()[0] : null);
                    Da = {
                      sampleRate: b.audioSamplingRate,
                      channelCount: b.channelsCount,
                      codec: Ad
                    };
                    var xg = AF(Ad, b.channelsCount);
                    if (!xg) throw new U(2, 3, 3018, c ? c.T()[0] : null);
                    for (var Dk = za + (c.endTime - c.startTime) * 9e4, ai = za; ai < Dk; ) Fa.push({
                      data: xg,
                      size: xg.byteLength,
                      duration: 1024,
                      Ab: 0,
                      flags: {
                        Cb: 0,
                        ub: 0,
                        sb: 0,
                        pb: 0,
                        qb: 2,
                        Db: 0
                      }
                    }), ai += 1024 / Da.sampleRate * 9e4;
                  }
                  var gd = Da.sampleRate, OJ = za / 9e4 * gd;
                  n = {
                    id: b.id,
                    type: "audio",
                    codecs: Da.codec,
                    encrypted: b.encrypted && b.drmInfos.length > 0,
                    timescale: gd,
                    duration: d2,
                    Gb: [],
                    Na: new Uint8Array([]),
                    Xa: new Uint8Array([]),
                    eb: 0,
                    gb: 0,
                    data: {
                      sequenceNumber: this.g,
                      baseMediaDecodeTime: OJ,
                      Eb: Fa
                    },
                    stream: b
                  };
                  break;
                case "ac3":
                  for (var yz = [], ll = 0, Np = new Uint8Array([]), ml = null, zz = t2(k2.Bb()), Op = zz.next(); !Op.done; Op = zz.next()) {
                    var Pp = Op.value, Qp = Pp.data;
                    ml == null && Pp.pts !== null && (ml = Pp.pts);
                    for (var Eg = 0; Eg < Qp.length; ) {
                      var Ge = CF(Qp, Eg);
                      Ge ? (b.audioSamplingRate = Ge.sampleRate, b.channelsCount = Ge.channelCount, ll = Ge.sampleRate, Np = Ge.Na, yz.push({
                        data: Qp.subarray(Eg, Eg + Ge.xa),
                        size: Ge.xa,
                        duration: 1536,
                        Ab: 0,
                        flags: {
                          Cb: 0,
                          ub: 0,
                          sb: 0,
                          pb: 0,
                          qb: 2,
                          Db: 0
                        }
                      }), Eg += Ge.xa) : Eg++;
                    }
                  }
                  if (ll == 0 || Np.byteLength == 0 || ml == null) throw new U(2, 3, 3018, c ? c.T()[0] : null);
                  var PJ = ml / 9e4 * ll;
                  n = {
                    id: b.id,
                    type: "audio",
                    codecs: "ac-3",
                    encrypted: b.encrypted && b.drmInfos.length > 0,
                    timescale: ll,
                    duration: d2,
                    Gb: [],
                    Na: Np,
                    Xa: new Uint8Array([]),
                    eb: 0,
                    gb: 0,
                    data: {
                      sequenceNumber: this.g,
                      baseMediaDecodeTime: PJ,
                      Eb: yz
                    },
                    stream: b
                  };
                  break;
                case "ec3":
                  for (var Az = [], nl = 0, Rp = new Uint8Array([]), ol = null, Bz = t2(k2.Bb()), Sp = Bz.next(); !Sp.done; Sp = Bz.next()) {
                    var Tp = Sp.value, Up = Tp.data;
                    ol == null && Tp.pts !== null && (ol = Tp.pts);
                    for (var Fg = 0; Fg < Up.length; ) {
                      var He = FF(Up, Fg);
                      He ? (b.audioSamplingRate = He.sampleRate, b.channelsCount = He.channelCount, nl = He.sampleRate, Rp = He.Na, Az.push({
                        data: Up.subarray(Fg, Fg + He.xa),
                        size: He.xa,
                        duration: 1536,
                        Ab: 0,
                        flags: {
                          Cb: 0,
                          ub: 0,
                          sb: 0,
                          pb: 0,
                          qb: 2,
                          Db: 0
                        }
                      }), Fg += He.xa) : Fg++;
                    }
                  }
                  if (nl == 0 || Rp.byteLength == 0 || ol == null) throw new U(2, 3, 3018, c ? c.T()[0] : null);
                  var QJ = ol / 9e4 * nl;
                  n = {
                    id: b.id,
                    type: "audio",
                    codecs: "ec-3",
                    encrypted: b.encrypted && b.drmInfos.length > 0,
                    timescale: nl,
                    duration: d2,
                    Gb: [],
                    Na: Rp,
                    Xa: new Uint8Array([]),
                    eb: 0,
                    gb: 0,
                    data: {
                      sequenceNumber: this.g,
                      baseMediaDecodeTime: QJ,
                      Eb: Az
                    },
                    stream: b
                  };
                  break;
                case "mp3":
                  for (var Cz = [], pl, ql = null, Dz = t2(k2.Bb()), Vp = Dz.next(); !Vp.done; Vp = Dz.next()) {
                    var Wp = Vp.value, mi = Wp.data;
                    if (mi) {
                      ql == null && Wp.pts !== null && (ql = Wp.pts);
                      for (var sf = 0; sf < mi.length; ) {
                        var Gg = PF(mi, sf);
                        Gg ? (pl || (pl = Gg), sf + Gg.xa <= mi.length && Cz.push({
                          data: mi.subarray(sf, sf + Gg.xa),
                          size: Gg.xa,
                          duration: 1152,
                          Ab: 0,
                          flags: {
                            Cb: 0,
                            ub: 0,
                            sb: 0,
                            pb: 0,
                            qb: 2,
                            Db: 0
                          }
                        }), sf += Gg.xa) : sf++;
                      }
                    }
                  }
                  if (!pl || ql == null) throw new U(2, 3, 3018, c ? c.T()[0] : null);
                  var Ez = pl.sampleRate, RJ = ql / 9e4 * Ez;
                  n = {
                    id: b.id,
                    type: "audio",
                    codecs: "mp3",
                    encrypted: b.encrypted && b.drmInfos.length > 0,
                    timescale: Ez,
                    duration: d2,
                    Gb: [],
                    Na: new Uint8Array([]),
                    Xa: new Uint8Array([]),
                    eb: 0,
                    gb: 0,
                    data: {
                      sequenceNumber: this.g,
                      baseMediaDecodeTime: RJ,
                      Eb: Cz
                    },
                    stream: b
                  };
                  break;
                case "opus":
                  var Fz = [], rl = null, Cd = k2.H;
                  if (!Cd) throw new U(2, 3, 3018, c ? c.T()[0] : null);
                  var fc = [];
                  switch (Cd.pk) {
                    case 1:
                    case 2:
                      fc = [0];
                      break;
                    case 0:
                      fc = [255, 1, 1, 0, 1];
                      break;
                    case 128:
                      fc = [255, 2, 0, 0, 1];
                      break;
                    case 3:
                      fc = [1, 2, 1, 0, 2, 1];
                      break;
                    case 4:
                      fc = [1, 2, 2, 0, 1, 2, 3];
                      break;
                    case 5:
                      fc = [1, 3, 2, 0, 4, 1, 2, 3];
                      break;
                    case 6:
                      fc = [1, 4, 2, 0, 4, 1, 2, 3, 5];
                      break;
                    case 7:
                      fc = [1, 4, 2, 0, 4, 1, 2, 3, 5, 6];
                      break;
                    case 8:
                      fc = [1, 5, 3, 0, 6, 1, 2, 3, 4, 5, 7];
                      break;
                    case 130:
                      fc = [1, 1, 2, 0, 1];
                      break;
                    case 131:
                      fc = [1, 1, 3, 0, 1, 2];
                      break;
                    case 132:
                      fc = [1, 1, 4, 0, 1, 2, 3];
                      break;
                    case 133:
                      fc = [1, 1, 5, 0, 1, 2, 3, 4];
                      break;
                    case 134:
                      fc = [1, 1, 6, 0, 1, 2, 3, 4, 5];
                      break;
                    case 135:
                      fc = [1, 1, 7, 0, 1, 2, 3, 4, 5, 6];
                      break;
                    case 136:
                      fc = [1, 1, 8, 0, 1, 2, 3, 4, 5, 6, 7];
                  }
                  var Gz = new Uint8Array([0, Cd.channelCount, 0, 0, Cd.sampleRate >>> 24 & 255, Cd.sampleRate >>> 17 & 255, Cd.sampleRate >>> 8 & 255, Cd.sampleRate >>> 0 & 255, 0, 0].concat(x(fc)));
                  for (var Hz = Cd.sampleRate, Iz = t2(k2.Bb()), Xp = Iz.next(); !Xp.done; Xp = Iz.next()) {
                    var Yp = Xp.value, Hg = Yp.data;
                    rl == null && Yp.pts !== null && (rl = Yp.pts);
                    for (var ni = 0; ni < Hg.length; ) {
                      for (var SJ = (Hg[ni + 1] & 16) !== 0, TJ = (Hg[ni + 1] & 8) !== 0, ie = ni + 2, sl = 0; Hg[ie] === 255; ) sl += 255, ie += 1;
                      sl += Hg[ie];
                      ie += 1;
                      ie += SJ ? 2 : 0;
                      ie += TJ ? 2 : 0;
                      var Jz = Hg.slice(ie, ie + sl);
                      Fz.push({
                        data: Jz,
                        size: Jz.byteLength,
                        duration: 960,
                        Ab: 0,
                        flags: {
                          Cb: 0,
                          ub: 0,
                          sb: 0,
                          pb: 0,
                          qb: 2,
                          Db: 0
                        }
                      });
                      ni = ie + sl;
                    }
                  }
                  if (Gz.byteLength == 0 || rl == null) throw new U(2, 3, 3018, c ? c.T()[0] : null);
                  b.audioSamplingRate = Cd.sampleRate;
                  b.channelsCount = Cd.channelCount;
                  var UJ = rl / 9e4 * Hz;
                  n = {
                    id: b.id,
                    type: "audio",
                    codecs: "opus",
                    encrypted: b.encrypted && b.drmInfos.length > 0,
                    timescale: Hz,
                    duration: d2,
                    Gb: [],
                    Na: Gz,
                    Xa: new Uint8Array([]),
                    eb: 0,
                    gb: 0,
                    data: {
                      sequenceNumber: this.g,
                      baseMediaDecodeTime: UJ,
                      Eb: Fz
                    },
                    stream: b
                  };
              }
              n && (l.push(n), n = null);
            }
          } catch (Zp) {
            return Zp && Zp.code == 3023 ? Promise.resolve(new Uint8Array([])) : Promise.reject(Zp);
          }
          if (!l.length) return Promise.reject(new U(2, 3, 3018, c ? c.T()[0] : null));
          var Kz = new Vi(l), $p = b.id + "_" + c.i;
          if (this.j.has($p)) var oi = this.j.get($p);
          else oi = Wi(Kz), this.j.set($p, oi);
          var VJ = this.l !== oi, Lz = qj(Kz);
          this.l = oi;
          this.g++;
          if (VJ) {
            var WJ = mc(oi, Lz);
            return Promise.resolve(WJ);
          }
          return Promise.resolve(Lz);
        };
        S("shaka.transmuxer.TsTransmuxer", bG);
        bG.prototype.transmux = bG.prototype.transmux;
        bG.prototype.getOriginalMimeType = bG.prototype.getOriginalMimeType;
        bG.prototype.convertCodecs = bG.prototype.convertCodecs;
        bG.prototype.isSupported = bG.prototype.isSupported;
        bG.prototype.destroy = bG.prototype.destroy;
        var cG = ["aac", "ac-3", "ec-3", "mp3", "opus"], dG = ["avc", "hevc"];
        Xe("video/mp2t", function() {
          return new bG("video/mp2t");
        }, af);
        function eG() {
        }
        ma(eG, En);
        S("shaka.util.FairPlayUtils", eG);
        function fG(a, b) {
          var c = this;
          this.parent = a;
          this.controls = b;
          this.eventManager = new Qc();
          this.localization = this.controls.ua;
          this.player = this.controls.Vb();
          this.video = this.controls.Pc();
          this.adManager = this.player.rf();
          this.ad = b.getAd();
          this.eventManager.o(this.adManager, "ad-started", function(d2) {
            c.ad = d2.ad;
          });
          this.eventManager.o(this.adManager, "ad-stopped", function() {
            c.ad = null;
          });
        }
        fG.prototype.release = function() {
          this.eventManager.release();
          this.ad = this.adManager = this.video = this.player = this.localization = this.eventManager = this.controls = this.parent = null;
        };
        S("shaka.ui.Element", fG);
        fG.prototype.release = fG.prototype.release;
        function gG(a) {
          return hG(a, "shaka-back-to-overflow-button");
        }
        function hG(a, b) {
          a = a.getElementsByClassName(b);
          return a.length ? a[0] : null;
        }
        function iG(a) {
          a && (a = hG(a, "shaka-chosen-item")) && a.parentElement.focus();
        }
        function jG() {
          var a = W("i");
          a.classList.add("material-icons-round");
          a.classList.add("shaka-chosen-item");
          a.textContent = "done";
          a.ariaHidden = "true";
          return a;
        }
        function kG(a, b) {
          a && (b ? a.classList.remove("shaka-hidden") : a.classList.add("shaka-hidden"));
        }
        function lG(a, b) {
          var c = Math.floor(a / 86400), d2 = Math.floor(a % 86400 / 3600), e = Math.floor(a / 60 % 60);
          a = Math.floor(a % 60);
          a < 10 && (a = "0" + a);
          a = e + ":" + a;
          b && (e < 10 && (a = "0" + a), a = d2 + ":" + a, c > 0 && (d2 < 10 && (a = "0" + a), a = c + ":" + a));
          return a;
        }
        ;
        function mG(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.g = Oj();
          this.g.classList.add("shaka-ad-info");
          this.g.disabled = true;
          this.parent.appendChild(this.g);
          this.h = new Cf(function() {
            if (c.ad.isLinear()) {
              var d2 = "", e = c.ad.getSequenceLength();
              e > 1 && (d2 = c.ad.getPositionInSequence(), d2 = c.localization.resolve("AD_PROGRESS").replace("[AD_ON]", String(d2)).replace("[NUM_ADS]", String(e)));
              var f = Math.round(c.ad.getRemainingTime()), g = c.ad.getDuration();
              f == -1 || g == -1 ? (c.g.textContent = d2, kG(c.g, d2 != "")) : f > 0 ? (f = lG(g - f, false) + " / " + lG(g, false), d2 = e > 1 ? d2 + ("\xA0\xA0" + f) : c.localization.resolve("AD_TIME").replace("[AD_TIME]", f), c.g.textContent = d2, kG(c.g, d2 != "")) : (c.h.stop(), c.g.textContent = "");
            }
          });
          this.eventManager.o(this.localization, "locale-updated", function() {
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
          });
          this.eventManager.o(this.adManager, "ad-started", function() {
            c.h.La();
            c.h.za(0.5);
          });
          this.eventManager.o(this.adManager, "ad-stopped", function() {
            c.h.stop();
            c.g.textContent = "";
          });
          this.ad && (this.h.La(), this.h.za(0.5));
        }
        ma(mG, fG);
        mG.prototype.release = function() {
          this.h.stop();
          this.h = null;
          fG.prototype.release.call(this);
        };
        S("shaka.ui.AdInfo", mG);
        function nG(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.j = this.controls.g;
          this.h = this.controls.i;
          this.i = [];
          this.g = W("div");
          this.g.classList.add("shaka-no-propagation");
          this.g.classList.add("shaka-context-menu");
          this.g.classList.add("shaka-hidden");
          this.h.appendChild(this.g);
          this.eventManager.o(this.h, "contextmenu", function(d2) {
            if (c.g.classList.contains("shaka-hidden")) {
              d2.preventDefault();
              var e = c.h.getBoundingClientRect();
              c.g.style.left = d2.clientX - e.left + "px";
              c.g.style.top = d2.clientY - e.top + "px";
              kG(c.g, true);
            } else kG(c.g, false);
          });
          this.eventManager.o(window7, "click", function() {
            kG(c.g, false);
          });
          this.eventManager.o(this.g, "click", function() {
            kG(c.g, false);
          });
          oG(this);
        }
        ma(nG, fG);
        nG.prototype.release = function() {
          this.h = null;
          for (var a = t2(this.i), b = a.next(); !b.done; b = a.next()) b.value.release();
          this.i = [];
          fG.prototype.release.call(this);
        };
        nG.prototype.Oi = function() {
          kG(this.g, false);
        };
        function pG(a, b) {
          qG.set(a, b);
        }
        function oG(a) {
          for (var b = t2(a.j.contextMenuElements), c = b.next(); !c.done; c = b.next()) {
            c = c.value;
            var d2 = qG.get(c);
            d2 ? a.i.push(d2.create(a.g, a.controls)) : bb("Unrecognized context menu element:", c);
          }
        }
        S("shaka.ui.ContextMenu", nG);
        nG.registerElement = pG;
        nG.prototype.closeMenu = nG.prototype.Oi;
        var qG = /* @__PURE__ */ new Map();
        function rG(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.button = Oj();
          this.parent.appendChild(this.button);
          this.eventManager.o(this.localization, "locale-updated", function() {
            sG(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            sG(c);
          });
          this.eventManager.o(this.video, "play", function() {
            sG(c);
            c.g();
          });
          this.eventManager.o(this.video, "pause", function() {
            sG(c);
            c.g();
          });
          this.eventManager.o(this.video, "seeking", function() {
            sG(c);
            c.g();
          });
          this.eventManager.o(this.player, "loaded", function() {
            sG(c);
            c.g();
          });
          this.eventManager.o(this.adManager, "ad-paused", function() {
            sG(c);
            c.g();
          });
          this.eventManager.o(this.adManager, "ad-resumed", function() {
            sG(c);
            c.g();
          });
          this.eventManager.o(this.adManager, "ad-started", function() {
            sG(c);
            c.g();
          });
          this.eventManager.o(this.adManager, "ad-stopped", function() {
            sG(c);
            c.g();
          });
          this.eventManager.o(this.button, "click", function() {
            c.controls.Ca() && tG(c.controls);
          });
          sG(this);
          this.g();
        }
        ma(rG, fG);
        rG.prototype.isPaused = function() {
          if (this.ad && this.ad.isLinear()) var a = this.ad.isPaused();
          else a = this.controls, a = a.C.paused && !a.S;
          return a;
        };
        rG.prototype.isEnded = function() {
          return this.ad && this.ad.isLinear() ? false : this.player ? this.player.isEnded() : true;
        };
        function sG(a) {
          if (a.isEnded() && a.video.duration) a.button.ariaLabel = a.localization.resolve("REPLAY");
          else {
            var b = a.isPaused() ? "PLAY" : "PAUSE";
            a.button.ariaLabel = a.localization.resolve(b);
          }
        }
        rG.prototype.g = function() {
          this.isEnded() && this.video.duration ? this.button.textContent = "replay" : this.button.textContent = this.isPaused() ? "play_arrow" : "pause";
        };
        S("shaka.ui.PlayButton", rG);
        function uG(a, b) {
          rG.call(this, a, b);
          this.button.classList.add("shaka-play-button");
          this.button.classList.add("shaka-no-propagation");
        }
        ma(uG, rG);
        uG.prototype.g = function() {
          this.isEnded() ? this.button.setAttribute("icon", "replay") : this.isPaused() ? this.button.setAttribute("icon", "play") : this.button.setAttribute("icon", "pause");
        };
        S("shaka.ui.BigPlayButton", uG);
        function vG(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.u = null;
          this.j = this.D = false;
          this.C = this.A = null;
          this.l = new Cf(function() {
            parseInt(c.h.textContent, 10) === 0 && wG(c.controls, true);
            var d2 = parseInt(c.h.textContent, 10);
            d2 !== 0 && (c.video.currentTime = c.controls.oh() + d2);
            c.g.style.opacity = "0";
            c.D = false;
            c.h.textContent = "0s";
          });
          this.g = W("div");
          this.g.classList.add("shaka-no-propagation");
          this.parent.appendChild(this.g);
          this.h = W("span");
          this.h.textContent = "0s";
          this.g.appendChild(this.h);
          this.i = W("span");
          this.i.classList.add("shaka-forward-rewind-container-icon");
          this.g.appendChild(this.i);
          this.m = false;
          this.eventManager.o(this.g, "touchstart", function(d2) {
            c.controls.Ca() && (d2.touches.length > 0 && (c.A = d2.touches[0].clientX, c.C = d2.touches[0].clientY), c.j = false);
          });
          this.eventManager.o(this.g, "touchmove", function(d2) {
            if (d2.touches.length > 0 && c.A != null && c.C != null) {
              var e = d2.touches[0].clientX - c.A;
              d2 = d2.touches[0].clientY - c.C;
              Math.sqrt(e * e + d2 * d2) > 10 && (c.j = true);
            }
          });
          this.eventManager.o(this.g, "touchend", function(d2) {
            if (c.controls.Ca() && !c.j) {
              if (c.controls.Hc()) d2.preventDefault(), c.controls.Rc();
              else if (c.controls.g.tapSeekDistance > 0) {
                if (d2.preventDefault(), d2 = c.controls.g.tapSeekDistance, !c.D) c.D = true, c.u = Date.now(), c.l.Y(0.5);
                else if (c.u + 500 > Date.now()) {
                  c.l.stop();
                  c.u = Date.now();
                  var e = parseInt(c.h.textContent, 10);
                  e = c.m ? e - d2 : e + d2;
                  c.h.textContent = e.toString() + "s";
                  c.g.style.opacity = "1";
                  c.l.Y(0.5);
                }
              }
            }
          });
        }
        ma(vG, fG);
        S("shaka.ui.HiddenSeekButton", vG);
        function xG(a, b) {
          vG.call(this, a, b);
          this.g.classList.add("shaka-fast-forward-container");
          this.i.textContent = "fast_forward";
          this.m = false;
        }
        ma(xG, vG);
        S("shaka.ui.HiddenFastForwardButton", xG);
        function yG(a, b) {
          vG.call(this, a, b);
          this.g.classList.add("shaka-rewind-container");
          this.i.textContent = "fast_rewind";
          this.m = true;
        }
        ma(yG, vG);
        S("shaka.ui.HiddenRewindButton", yG);
        function zG(a, b, c, d2) {
          fG.call(this, a, b);
          var e = this;
          this.container = W("div");
          this.container.classList.add("shaka-range-container");
          this.container.classList.add.apply(this.container.classList, x(c));
          this.i = false;
          this.bar = document.createElement("input");
          this.G = new Cf(function() {
            e.onChangeEnd();
            e.i = false;
          });
          this.bar.classList.add("shaka-range-element");
          this.bar.classList.add.apply(this.bar.classList, x(d2));
          this.bar.type = "range";
          this.bar.step = "any";
          this.bar.min = "0";
          this.bar.max = "1";
          this.bar.value = "0";
          this.bar.disabled = !this.controls.Ca();
          this.container.appendChild(this.bar);
          this.parent.appendChild(this.container);
          this.L = new Cf(function() {
            e.bar.disabled = false;
          });
          this.eventManager.o(this.controls, "showingui", function() {
            e.L.Y(0);
          });
          this.eventManager.o(this.controls, "hidingui", function() {
            e.L.stop();
            e.bar.disabled = true;
          });
          this.eventManager.o(this.bar, "mousedown", function(f) {
            e.bar.disabled || (e.i = true, e.onChangeStart(), f.stopPropagation());
          });
          this.eventManager.o(this.bar, "touchstart", function(f) {
            e.bar.disabled || (e.i = true, AG(e, f), e.onChangeStart(), f.stopPropagation());
          });
          this.eventManager.o(this.bar, "input", function() {
            e.onChange();
          });
          this.eventManager.o(this.bar, "touchmove", function(f) {
            e.i && (AG(e, f), e.onChange(), f.stopPropagation());
          });
          this.eventManager.o(this.bar, "touchend", function(f) {
            e.i && (e.i = false, AG(e, f), e.onChangeEnd(), f.stopPropagation());
          });
          this.eventManager.o(this.bar, "touchcancel", function(f) {
            e.i && (e.i = false, AG(e, f), e.onChangeEnd(), f.stopPropagation());
          });
          this.eventManager.o(this.bar, "mouseup", function(f) {
            e.i && (e.i = false, e.onChangeEnd(), f.stopPropagation());
          });
          this.eventManager.o(this.bar, "blur", function() {
            e.i && (e.i = false, e.onChangeEnd());
          });
          this.eventManager.o(this.bar, "contextmenu", function(f) {
            f.preventDefault();
            f.stopPropagation();
          });
        }
        ma(zG, fG);
        p = zG.prototype;
        p.release = function() {
          this.G && (this.G.stop(), this.G = null);
          fG.prototype.release.call(this);
        };
        p.setRange = function(a, b) {
          this.bar.min = a;
          this.bar.max = b;
        };
        p.onChangeStart = function() {
        };
        p.onChange = function() {
        };
        p.onChangeEnd = function() {
        };
        p.changeTo = function(a) {
          this.i || (this.i = true, this.onChangeStart());
          var b = parseFloat(this.bar.min), c = parseFloat(this.bar.max);
          this.bar.value = a > c ? c : a < b ? b : a;
          this.onChange();
          this.G.Y(0.5);
        };
        p.getValue = function() {
          return parseFloat(this.bar.value);
        };
        p.setValue = function(a) {
          this.i || (this.bar.value = a);
        };
        function BG(a, b) {
          var c = a.bar.getBoundingClientRect(), d2 = parseFloat(a.bar.min), e = parseFloat(a.bar.max);
          a = parseFloat(a.bar.step) || 1;
          var f = c.left + 6;
          c = c.right - 6;
          b = d2 + (Math.max(f, Math.min(c, b)) - f) / (c - f) * (e - d2);
          b = Math.round((b - d2) / a) * a + d2;
          return b = Math.min(e, Math.max(d2, b));
        }
        function AG(a, b) {
          b.preventDefault();
          a.bar.value = BG(a, b.changedTouches[0].clientX);
        }
        S("shaka.ui.RangeElement", zG);
        zG.prototype.setValue = zG.prototype.setValue;
        zG.prototype.getValue = zG.prototype.getValue;
        zG.prototype.changeTo = zG.prototype.changeTo;
        zG.prototype.onChangeEnd = zG.prototype.onChangeEnd;
        zG.prototype.onChange = zG.prototype.onChange;
        zG.prototype.onChangeStart = zG.prototype.onChangeStart;
        zG.prototype.setRange = zG.prototype.setRange;
        function CG(a, b) {
          zG.call(this, a, b, ["shaka-seek-bar-container"], ["shaka-seek-bar", "shaka-no-propagation", "shaka-show-controls-on-mouse-over"]);
          var c = this;
          this.F = W("div");
          this.F.classList.add("shaka-ad-markers");
          this.container.insertBefore(this.F, this.container.childNodes[0]);
          this.I = this.controls.g;
          this.C = new Cf(function() {
            var d2 = c.getValue();
            c.player.U() || d2 == c.video.duration && (d2 -= 1e-3);
            c.video.currentTime = d2;
          });
          this.D = new Cf(function() {
            DG(c);
          });
          this.M = false;
          this.h = W("div");
          this.h.id = "shaka-player-ui-thumbnail-container";
          this.g = W("img");
          this.g.id = "shaka-player-ui-thumbnail-image";
          this.g.draggable = false;
          this.K = W("div");
          this.K.id = "shaka-player-ui-thumbnail-time-container";
          this.H = W("div");
          this.H.id = "shaka-player-ui-thumbnail-time";
          this.K.appendChild(this.H);
          this.h.appendChild(this.g);
          this.h.appendChild(this.K);
          this.container.appendChild(this.h);
          this.j = W("div");
          this.j.id = "shaka-player-ui-time-container";
          this.container.appendChild(this.j);
          this.l = this.u = null;
          this.J = false;
          this.A = new Cf(function() {
            EG(c);
          });
          this.m = [];
          this.eventManager.o(this.bar, "input", function() {
            c.controls.Rc();
          });
          this.eventManager.o(this.localization, "locale-updated", function() {
            return FG(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            return FG(c);
          });
          this.eventManager.o(this.adManager, "ad-started", function() {
            GG(c) || kG(c.container, false);
          });
          this.eventManager.o(this.adManager, "ad-stopped", function() {
            GG(c) && kG(c.container, true);
          });
          this.eventManager.o(this.adManager, "ad-cue-points-changed", function(d2) {
            c.m = d2.cuepoints;
            HG(c);
          });
          this.eventManager.o(this.player, "unloading", function() {
            c.m = [];
            HG(c);
            c.l && (c.l.abort(), c.l = null);
            c.u = null;
            EG(c);
            IG(c);
          });
          this.eventManager.o(this.bar, "mousemove", function(d2) {
            if (c.controls.Hc()) IG(c), EG(c);
            else {
              var e = BG(c, d2.clientX), f = c.bar.getBoundingClientRect();
              d2 = Math.max(0, d2.clientX - f.left);
              c.player.ph().length ? (IG(c), JG(c, d2, e)) : (EG(c), KG(c, d2, e));
            }
          });
          this.eventManager.o(this.container, "mouseleave", function() {
            IG(c);
            c.A.stop();
            c.A.Y(0.25);
          });
          this.setValue(this.video.currentTime);
          this.update();
          FG(this);
          this.ad && kG(this.container, false);
        }
        ma(CG, zG);
        p = CG.prototype;
        p.release = function() {
          this.C && (this.C.stop(), this.C = null, this.D.stop(), this.D = null);
          zG.prototype.release.call(this);
        };
        p.onChangeStart = function() {
          this.M = !this.video.paused;
          this.controls.ii(true);
          this.video.pause();
          this.A.stop();
          this.J = true;
        };
        p.onChange = function() {
          if (this.video.duration) if (this.update(), this.C.Y(0.125), this.player.ph().length && !this.controls.Hc()) {
            var a = parseFloat(this.bar.min), b = parseFloat(this.bar.max), c = this.bar.getBoundingClientRect(), d2 = Math.round(this.getValue());
            JG(this, (d2 - a) / ((b - a) / c.width), d2);
          } else EG(this);
        };
        p.onChangeEnd = function() {
          this.C.La();
          this.controls.ii(false);
          this.M && this.video.play();
          this.J && (this.J = false, this.A.stop(), this.A.Y(0.25));
        };
        p.isShowing = function() {
          return !this.container.classList.contains("shaka-hidden");
        };
        p.update = function() {
          var a = this.I.seekBarColors, b = this.getValue(), c = this.video.buffered.length, d2 = c ? this.video.buffered.start(0) : 0, e = c ? this.video.buffered.end(c - 1) : 0;
          c = this.player.ya();
          var f = c.end - c.start;
          this.setRange(c.start, c.end);
          GG(this) ? (kG(this.container, true), d2 = (Math.max(d2, c.start) - c.start) / f || 0, e = (Math.min(e, c.end) - c.start) / f || 0, b = (Math.min(Math.max(b, c.start), c.end) - c.start) / f || 0, this.container.style.background = "linear-gradient(" + ["to right", (this.I.showUnbufferedStart ? a.base : a.played) + " " + d2 * 100 + "%", a.played + " " + d2 * 100 + "%", a.played + " " + b * 100 + "%", a.buffered + " " + b * 100 + "%", a.buffered + " " + e * 100 + "%", a.base + " " + e * 100 + "%"].join() + ")") : kG(this.container, false);
        };
        function DG(a) {
          if (a.m.length) {
            for (var b = a.player.ya(), c = b.end - b.start, d2 = ["to right"], e = [], f = a.I.seekBarColors.adBreaks, g = false, h = t2(a.m), k2 = h.next(); !k2.done; k2 = h.next()) if (k2 = k2.value, k2.start == -1 && !k2.end) g = true;
            else if (!k2.end && k2.start >= b.start || typeof k2.end == "number" && k2.end > b.start) {
              var l = (Math.max(k2.start, b.start) - b.start) / c || 0, m = l + 0.01;
              k2.end && (m = (k2.end - b.start) / c || 0);
              e.push({
                start: l,
                end: m
              });
            }
            e = e.sort(function(n, q) {
              return n.start - q.start;
            });
            b = t2(e);
            for (c = b.next(); !c.done; c = b.next()) c = c.value, d2.push("transparent " + c.start * 100 + "%"), d2.push(f + " " + c.start * 100 + "%"), d2.push(f + " " + c.end * 100 + "%"), d2.push("transparent " + c.end * 100 + "%");
            g && (d2.push("transparent 99%"), d2.push(f + " 99%"));
            a.F.style.background = "linear-gradient(" + d2.join(",") + ")";
          } else a.F.style.background = "transparent", a.D.stop();
        }
        function HG(a) {
          function b() {
            DG(a);
            var c = a.player.ya();
            c = c.end - c.start;
            a.player.U() && c > 5 && a.D.za(0.25);
          }
          a.player.aa ? b() : a.eventManager.qa(a.player, "loaded", b);
        }
        function GG(a) {
          var b = a.player.ya();
          b = b.end - b.start;
          return a.player.U() && (b < 5 || !isFinite(b)) ? false : a.ad == null || !a.ad.isLinear();
        }
        function FG(a) {
          a.bar.ariaLabel = a.localization.resolve("SEEK");
        }
        function KG(a, b, c) {
          var d2 = a.j.clientWidth;
          a.j.style.width = "auto";
          a.j.style.height = "20px";
          a.j.style.top = "-30px";
          a.j.style.left = Math.min(a.bar.offsetWidth - d2, Math.max(0, b - d2 / 2)) + "px";
          a.j.style.right = "";
          a.j.style.visibility = "visible";
          b = a.player.ya();
          a.player.U() ? (c = b.end - c, c < 1 ? (a.j.textContent = a.localization.resolve("LIVE"), a.j.style.left = "", a.j.style.right = "0px") : a.j.textContent = "-" + lG(c, c >= 3600)) : (c -= b.start, a.j.textContent = lG(c, c >= 3600));
        }
        function JG(a, b, c) {
          var d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C;
          P(function(D) {
            switch (D.g) {
              case 1:
                c < 0 && (c = 0);
                d2 = false;
                a.m.length && (d2 = a.m.some(function(F) {
                  return F.end ? c >= F.start && c <= F.end : false;
                }));
                if (d2) return EG(a), KG(a, b, c), D.return();
                e = a.player.ya();
                f = Math.max(Math.ceil(e.start), Math.min(Math.floor(e.end), c));
                a.player.U() ? (g = e.end - c, a.H.textContent = g < 1 ? a.localization.resolve("LIVE") : "-" + lG(g, g >= 3600)) : a.H.textContent = lG(c, c >= 3600);
                return G(D, a.player.$i(null, f), 2);
              case 2:
                h = D.h;
                if (!h || !h.uris || !h.uris.length) return EG(a), KG(a, b, c), D.return();
                h.width < h.height ? a.h.classList.add("portrait-thumbnail") : a.h.classList.remove("portrait-thumbnail");
                k2 = -10;
                l = a.h.clientWidth;
                m = Math.floor(l * 9 / 16);
                a.h.style.height = m + "px";
                a.h.style.top = -(m - k2) + "px";
                n = Math.min(a.bar.offsetWidth - l, Math.max(0, b - l / 2));
                a.h.style.left = n + "px";
                a.h.style.visibility = "visible";
                q = h.uris[0].split("#xywh=")[0];
                if (a.u && q === a.u.uris[0].split("#xywh=")[0] && h.startByte == a.u.startByte && h.endByte == a.u.endByte) {
                  D.B(3);
                  break;
                }
                a.u = h;
                a.l && (a.l.abort(), a.l = null);
                if (h.codecs != "mjpg" && !q.startsWith("offline:")) {
                  D.B(4);
                  break;
                }
                a.g.src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>';
                sa(D, 5);
                r2 = gh;
                u = Jm(h.uris, h.startByte, h.endByte, a.player.getConfiguration().streaming.retryParameters);
                a.l = a.player.Lb().request(r2, u, {
                  type: 1
                });
                return G(D, a.l.promise, 7);
              case 7:
                w = D.h;
                a.l = null;
                h.codecs == "mjpg" ? (v = new ph().box("mdat", zh(function(F) {
                  q = URL.createObjectURL(new Blob([F], {
                    type: "image/jpeg"
                  }));
                })), v.parse(w.data, false)) : (y = h.mimeType || "image/jpeg", z = new Blob([w.data], {
                  type: y
                }), q = URL.createObjectURL(z));
                ua(D, 4);
                break;
              case 5:
                A = va(D);
                if (A.code == 7001) return D.return();
                throw A;
              case 4:
                try {
                  a.h.removeChild(a.g);
                } catch (F) {
                }
                a.g = W("img");
                a.g.id = "shaka-player-ui-thumbnail-image";
                a.g.draggable = false;
                a.g.src = q;
                a.g.onload = function() {
                  q.startsWith("blob:") && URL.revokeObjectURL(q);
                };
                a.h.insertBefore(a.g, a.h.firstChild);
              case 3:
                C = l / h.width, h.imageHeight ? a.g.height = h.imageHeight : h.sprite || (a.g.style.height = "100%", a.g.style.objectFit = "contain"), h.imageWidth ? a.g.width = h.imageWidth : h.sprite || (a.g.style.width = "100%", a.g.style.objectFit = "contain"), a.g.style.left = "-" + C * h.positionX + "px", a.g.style.top = "-" + C * h.positionY + "px", a.g.style.transform = "scale(" + C + ")", a.g.style.transformOrigin = "left top", m = Math.floor(l * h.height / h.width), a.h.style.height = m + "px", a.h.style.top = -(m - k2) + "px", H(D);
            }
          });
        }
        function EG(a) {
          a.h.style.visibility = "hidden";
        }
        function IG(a) {
          a.j.style.visibility = "hidden";
        }
        S("shaka.ui.SeekBar", CG);
        function LG() {
        }
        LG.prototype.create = function(a, b) {
          return new CG(a, b);
        };
        CG.Factory = LG;
        function MG(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.j = W("div");
          this.j.classList.add("shaka-skip-ad-container");
          this.parent.appendChild(this.j);
          this.h = W("div");
          this.h.classList.add("shaka-skip-ad-counter");
          kG(this.h, false);
          this.j.appendChild(this.h);
          this.g = Oj();
          this.g.classList.add("shaka-skip-ad-button");
          this.g.disabled = true;
          kG(this.g, false);
          this.g.classList.add("shaka-no-propagation");
          this.j.appendChild(this.g);
          NG(this);
          this.i = new Cf(function() {
            if (c.ad.isSkippable()) {
              var d2 = Math.round(c.ad.getTimeUntilSkippable());
              d2 > 0 ? c.h.textContent = d2 : (c.i.stop(), kG(c.h, false));
            } else OG(c);
          });
          this.eventManager.o(this.localization, "locale-updated", function() {
            NG(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            NG(c);
          });
          this.eventManager.o(this.adManager, "ad-started", function() {
            PG(c);
          });
          this.eventManager.o(this.adManager, "ad-skip-state-changed", function() {
            c.ad.isSkippable() ? c.ad.canSkipNow() && (c.g.disabled = false, c.i.stop(), kG(c.h, false)) : OG(c);
          });
          this.eventManager.o(this.adManager, "ad-stopped", function() {
            OG(c);
          });
          this.eventManager.o(this.g, "click", function() {
            c.ad.skip();
          });
          this.ad && PG(this);
        }
        ma(MG, fG);
        MG.prototype.release = function() {
          this.i.stop();
          this.i = null;
          fG.prototype.release.call(this);
        };
        function NG(a) {
          a.g.textContent = a.localization.resolve("SKIP_AD");
        }
        function PG(a) {
          a.ad.isSkippable() && a.ad.needsSkipUI() && (kG(a.g, true), kG(a.h, true), a.h.textContent = "", a.i.La(), a.i.za(0.5));
        }
        function OG(a) {
          a.i.stop();
          a.g.disabled = true;
          kG(a.g, false);
          kG(a.h, false);
        }
        S("shaka.ui.SkipAdButton", MG);
        function QG() {
          var a = new Float32Array(16);
          a[0] = 1;
          a[5] = 1;
          a[10] = 1;
          a[15] = 1;
          return a;
        }
        function RG(a, b, c) {
          b = 1 / Math.tan(b / 2);
          a[0] = b / c;
          a[1] = 0;
          a[2] = 0;
          a[3] = 0;
          a[4] = 0;
          a[5] = b;
          a[6] = 0;
          a[7] = 0;
          a[8] = 0;
          a[9] = 0;
          a[11] = -1;
          a[12] = 0;
          a[13] = 0;
          a[15] = 0;
          c = 1 / -99.9;
          a[10] = 100.1 * c;
          a[14] = 20 * c;
        }
        function SG(a, b, c) {
          var d2 = b[0], e = b[1], f = b[2], g = b[3], h = b[4], k2 = b[5], l = b[6], m = b[7], n = b[8], q = b[9], r2 = b[10], u = b[11], w = b[12], v = b[13], y = b[14];
          b = b[15];
          var z = c[0], A = c[1], C = c[2], D = c[3];
          a[0] = z * d2 + A * h + C * n + D * w;
          a[1] = z * e + A * k2 + C * q + D * v;
          a[2] = z * f + A * l + C * r2 + D * y;
          a[3] = z * g + A * m + C * u + D * b;
          z = c[4];
          A = c[5];
          C = c[6];
          D = c[7];
          a[4] = z * d2 + A * h + C * n + D * w;
          a[5] = z * e + A * k2 + C * q + D * v;
          a[6] = z * f + A * l + C * r2 + D * y;
          a[7] = z * g + A * m + C * u + D * b;
          z = c[8];
          A = c[9];
          C = c[10];
          D = c[11];
          a[8] = z * d2 + A * h + C * n + D * w;
          a[9] = z * e + A * k2 + C * q + D * v;
          a[10] = z * f + A * l + C * r2 + D * y;
          a[11] = z * g + A * m + C * u + D * b;
          z = c[12];
          A = c[13];
          C = c[14];
          D = c[15];
          a[12] = z * d2 + A * h + C * n + D * w;
          a[13] = z * e + A * k2 + C * q + D * v;
          a[14] = z * f + A * l + C * r2 + D * y;
          a[15] = z * g + A * m + C * u + D * b;
        }
        function TG(a, b) {
          var c = new Float32Array(3), d2 = b[0], e = b[1], f = b[2], g = b[4], h = b[5], k2 = b[6], l = b[8], m = b[9], n = b[10];
          c[0] = Math.sqrt(d2 * d2 + e * e + f * f);
          c[1] = Math.sqrt(g * g + h * h + k2 * k2);
          c[2] = Math.sqrt(l * l + m * m + n * n);
          k2 = 1 / c[0];
          l = 1 / c[1];
          m = 1 / c[2];
          g = b[0] * k2;
          c = b[1] * l;
          d2 = b[2] * m;
          e = b[4] * k2;
          h = b[5] * l;
          f = b[6] * m;
          k2 *= b[8];
          l *= b[9];
          b = b[10] * m;
          m = g + h + b;
          m > 0 ? (b = Math.sqrt(m + 1) * 2, a[3] = 0.25 * b, a[0] = (f - l) / b, a[1] = (k2 - d2) / b, a[2] = (c - e) / b) : g > h && g > b ? (b = Math.sqrt(1 + g - h - b) * 2, a[3] = (f - l) / b, a[0] = 0.25 * b, a[1] = (c + e) / b, a[2] = (k2 + d2) / b) : h > b ? (b = Math.sqrt(1 + h - g - b) * 2, a[3] = (k2 - d2) / b, a[0] = (c + e) / b, a[1] = 0.25 * b, a[2] = (f + l) / b) : (b = Math.sqrt(1 + b - g - h) * 2, a[3] = (c - e) / b, a[0] = (k2 + d2) / b, a[1] = (f + l) / b, a[2] = 0.25 * b);
        }
        function UG(a, b) {
          var c = b[0], d2 = b[1], e = b[2];
          b = b[3];
          var f = c + c, g = d2 + d2, h = e + e;
          c *= f;
          var k2 = d2 * f;
          d2 *= g;
          var l = e * f, m = e * g;
          e *= h;
          f *= b;
          g *= b;
          b *= h;
          a[0] = 1 - d2 - e;
          a[1] = k2 + b;
          a[2] = l - g;
          a[3] = 0;
          a[4] = k2 - b;
          a[5] = 1 - c - e;
          a[6] = m + f;
          a[7] = 0;
          a[8] = l + g;
          a[9] = m - f;
          a[10] = 1 - c - d2;
          a[11] = 0;
          a[12] = 0;
          a[13] = 0;
          a[14] = 0;
          a[15] = 1;
        }
        ;
        function VG() {
          var a = new Float32Array(4);
          a[3] = 1;
          return a;
        }
        function WG(a, b) {
          var c = b[0], d2 = b[1], e = b[2];
          b = b[3];
          var f = c * c + d2 * d2 + e * e + b * b;
          f > 0 && (f = 1 / Math.sqrt(f));
          a[0] = c * f;
          a[1] = d2 * f;
          a[2] = e * f;
          a[3] = b * f;
        }
        ;
        function XG(a) {
          var b = [], c = [], d2 = [], e = Math.PI;
          a = (a === void 0 ? 0 : a) ? e / 2 : e;
          for (var f = 0; f <= 100; f++) {
            var g = f * e / 100, h = Math.sin(g);
            g = Math.cos(g);
            for (var k2 = 0; k2 <= 100; k2++) {
              var l = k2 * 2 * a / 100;
              b.push(Math.sin(l) * h, g, Math.cos(l) * h);
              c.push(k2 / 100, f / 100);
            }
          }
          for (e = 0; e < 100; e++) for (a = 0; a < 100; a++) f = e * 101 + a, h = f + 100 + 1, d2.push(f, h, f + 1), d2.push(h, h + 1, f + 1);
          return {
            dk: b,
            $j: c,
            indices: d2
          };
        }
        ;
        function YG(a, b, c, d2, e) {
          this.i = a;
          this.sa = b;
          this.u = c;
          this.g = d2;
          this.A = new Qc();
          this.M = VG();
          this.h = VG();
          this.ea = this.oa = this.aa = this.l = null;
          this.F = QG();
          this.J = QG();
          this.O = QG();
          this.Z = QG();
          this.D = null;
          this.P = false;
          this.K = this.C = null;
          this.ua = this.va = 0;
          this.$ = this.R = this.S = this.L = null;
          this.I = this.H = 0;
          this.j = 75;
          this.V = 0;
          this.m = e;
          this.G = -1;
          ZG(this);
        }
        YG.prototype.release = function() {
          this.G != -1 && (this.i.cancelVideoFrameCallback(this.G), this.G = -1);
          this.A && (this.A.release(), this.A = null);
          this.C && (this.C.stop(), this.C = null);
          this.K && (this.K.stop(), this.K = null);
        };
        YG.prototype.Wd = function() {
          (this.P = !this.P) || this.g.viewport(0, 0, this.u.width, this.u.height);
          $G(this, false);
        };
        function ZG(a) {
          aH(a);
          bH(a);
          cH(a);
          dH(a);
          eH(a);
          Il(a.i, HTMLMediaElement.HAVE_CURRENT_DATA, a.A, function() {
            a.i.readyState >= HTMLMediaElement.HAVE_ENOUGH_DATA && $G(a);
            if ("requestVideoFrameCallback" in a.i) {
              var b = function() {
                a.G != -1 && ($G(a), a.G != -1 && (a.G = a.i.requestVideoFrameCallback(b)));
              };
              a.G = a.i.requestVideoFrameCallback(b);
            } else {
              var c;
              a.A.o(a.i, "canplaythrough", function() {
                $G(a);
              });
              a.A.o(a.i, "playing", function() {
                a.C && a.C.stop();
                if (!c) {
                  var d2 = a.sa.rb();
                  d2 = t2(d2);
                  for (var e = d2.next(); !e.done; e = d2.next()) (e = e.value.frameRate) && (!c || c < e) && (c = e);
                }
                c || (c = 60);
                $G(a);
                a.C = new Cf(function() {
                  $G(a);
                }).La().za(1 / c);
              });
              a.A.o(a.i, "pause", function() {
                a.C && a.C.stop();
                a.C = null;
                $G(a);
              });
              a.A.o(a.i, "seeked", function() {
                $G(a);
              });
              a.A.o(document, "visibilitychange", function() {
                $G(a);
              });
            }
          });
        }
        function aH(a) {
          var b = a.F, c = [0, 0, 0], d2 = [1, 0, 0], e = [0, 1, 0], f = c[0], g = c[1];
          c = c[2];
          var h = e[0];
          var k2 = e[1];
          var l = e[2];
          var m = d2[0];
          e = d2[1];
          var n = d2[2];
          if (Math.abs(f - m) < 1e-6 && Math.abs(g - e) < 1e-6 && Math.abs(c - n) < 1e-6) for (f = 0; f < 16; f++) b[f] = f % 5 == 0 ? 1 : 0;
          else {
            d2 = f - m;
            e = g - e;
            m = c - n;
            var q = 1 / Math.sqrt(d2 * d2 + e * e + m * m);
            d2 *= q;
            e *= q;
            m *= q;
            n = k2 * m - l * e;
            l = l * d2 - h * m;
            h = h * e - k2 * d2;
            (q = Math.sqrt(n * n + l * l + h * h)) ? (q = 1 / q, n *= q, l *= q, h *= q) : h = l = n = 0;
            k2 = e * h - m * l;
            var r2 = m * n - d2 * h;
            var u = d2 * l - e * n;
            (q = Math.sqrt(k2 * k2 + r2 * r2 + u * u)) ? (q = 1 / q, k2 *= q, r2 *= q, u *= q) : u = r2 = k2 = 0;
            b[0] = n;
            b[1] = k2;
            b[2] = d2;
            b[3] = 0;
            b[4] = l;
            b[5] = r2;
            b[6] = e;
            b[7] = 0;
            b[8] = h;
            b[9] = u;
            b[10] = m;
            b[11] = 0;
            b[12] = -(n * f + l * g + h * c);
            b[13] = -(k2 * f + r2 * g + u * c);
            b[14] = -(d2 * f + e * g + m * c);
            b[15] = 1;
          }
          TG(a.M, a.F);
          a = b = a.Z;
          c = [4, 4, 4];
          f = c[0];
          g = c[1];
          c = c[2];
          b[0] = a[0] * f;
          b[1] = a[1] * f;
          b[2] = a[2] * f;
          b[3] = a[3] * f;
          b[4] = a[4] * g;
          b[5] = a[5] * g;
          b[6] = a[6] * g;
          b[7] = a[7] * g;
          b[8] = a[8] * c;
          b[9] = a[9] * c;
          b[10] = a[10] * c;
          b[11] = a[11] * c;
          b[12] = a[12];
          b[13] = a[13];
          b[14] = a[14];
          b[15] = a[15];
        }
        function bH(a) {
          fH(a);
          a.g.viewport(0, 0, a.g.drawingBufferWidth, a.g.drawingBufferHeight);
          a.g.clearColor(0, 0, 0, 1);
          a.g.enable(a.g.CULL_FACE);
          a.g.cullFace(a.g.FRONT);
          a.g.clear(a.g.COLOR_BUFFER_BIT);
        }
        function cH(a) {
          var b = gH(a, a.g.VERTEX_SHADER), c = gH(a, a.g.FRAGMENT_SHADER);
          a.l = a.g.createProgram();
          a.g.attachShader(a.l, b);
          a.g.attachShader(a.l, c);
          a.g.linkProgram(a.l);
          a.m == "cubemap" ? (a.S = a.g.getAttribLocation(a.l, "aVertexPosition"), a.R = a.g.getAttribLocation(a.l, "aTextureCoord")) : (a.S = a.g.getAttribLocation(a.l, "a_vPosition"), a.g.enableVertexAttribArray(a.S), a.R = a.g.getAttribLocation(a.l, "a_TexCoordinate"), a.g.enableVertexAttribArray(a.R));
        }
        function gH(a, b) {
          switch (b) {
            case a.g.VERTEX_SHADER:
              var c = a.m == "cubemap" ? "attribute vec4 aVertexPosition;\nattribute vec2 aTextureCoord;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvarying highp vec2 vTextureCoord;\nvarying highp vec3 vLighting;\nvoid main(void) {\n  gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n  vTextureCoord = aTextureCoord;\n}" : "attribute vec4 a_vPosition;\n// Per-vertex texture coordinate info\nattribute vec2 a_TexCoordinate;\nuniform mat4 u_VPMatrix;\n// Passed into the fragment shader.\nvarying vec2 v_TexCoordinate;\nvarying vec3 pass_position;\nvoid main()\n{\n gl_Position = u_VPMatrix * a_vPosition;\n // Pass through texture coord\n v_TexCoordinate = a_TexCoordinate;\n pass_position = a_vPosition.xyz;\n}";
              break;
            case a.g.FRAGMENT_SHADER:
              c = a.m == "cubemap" ? "varying highp vec2 vTextureCoord;\nuniform sampler2D uSampler;\nvoid main(void) {\n  highp vec4 texelColor = texture2D(uSampler, vTextureCoord);\n  gl_FragColor = vec4(texelColor.rgb , texelColor.a);\n}" : "precision highp float;\n#define PI 3.141592653589793238462643383279\nvarying vec2 v_TexCoordinate;\nvarying vec3 pass_position;\nuniform sampler2D uSampler;\nvoid main(void) {\nhighp float xValue =\n      (PI + atan(pass_position.z, pass_position.x)) / (2.0 * PI);\n vec2 tc = vec2(xValue, v_TexCoordinate.t);\n tc = vec2(tc.x , tc.y);\nhighp vec4 texelColor =\n      texture2D(uSampler, tc);\n  gl_FragColor = vec4(texelColor.rgb, texelColor.a);\n}";
              break;
            default:
              return null;
          }
          b = a.g.createShader(b);
          a.g.shaderSource(b, c);
          a.g.compileShader(b);
          return b;
        }
        function dH(a) {
          a.L = a.m == "cubemap" ? {
            dk: [-1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1],
            $j: [2 / 3, 0.5, 1 / 3, 0.5, 1 / 3, 0, 2 / 3, 0, 2 / 3, 0.5, 2 / 3, 0, 1, 0, 1, 0.5, 1, 1, 2 / 3, 1, 2 / 3, 0.5, 1, 0.5, 0, 0.5, 0, 0, 1 / 3, 0, 1 / 3, 0.5, 0, 0.5, 1 / 3, 0.5, 1 / 3, 1, 0, 1, 1 / 3, 1, 1 / 3, 0.5, 2 / 3, 0.5, 2 / 3, 1],
            indices: [0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23]
          } : a.m == "halfequirectangular" ? XG(true) : XG();
          a.aa = a.g.createBuffer();
          a.g.bindBuffer(a.g.ARRAY_BUFFER, a.aa);
          a.g.bufferData(a.g.ARRAY_BUFFER, new Float32Array(a.L.dk), a.g.STATIC_DRAW);
          a.oa = a.g.createBuffer();
          a.g.bindBuffer(a.g.ARRAY_BUFFER, a.oa);
          a.g.bufferData(a.g.ARRAY_BUFFER, new Float32Array(a.L.$j), a.g.STATIC_DRAW);
          a.ea = a.g.createBuffer();
          a.g.bindBuffer(a.g.ELEMENT_ARRAY_BUFFER, a.ea);
          a.g.bufferData(a.g.ELEMENT_ARRAY_BUFFER, new Uint16Array(a.L.indices), a.g.STATIC_DRAW);
        }
        function eH(a) {
          a.$ = a.g.createTexture();
          a.g.bindTexture(a.g.TEXTURE_2D, a.$);
          a.g.texParameteri(a.g.TEXTURE_2D, a.g.TEXTURE_WRAP_S, a.g.CLAMP_TO_EDGE);
          a.g.texParameteri(a.g.TEXTURE_2D, a.g.TEXTURE_WRAP_T, a.g.CLAMP_TO_EDGE);
          a.g.texParameteri(a.g.TEXTURE_2D, a.g.TEXTURE_MIN_FILTER, a.g.NEAREST);
          a.g.texParameteri(a.g.TEXTURE_2D, a.g.TEXTURE_MAG_FILTER, a.g.NEAREST);
        }
        function $G(a, b) {
          b = b === void 0 ? true : b;
          var c = a.sa.m == Xq;
          if (!(!a.i || a.i.readyState < 2 || !c && a.i.playbackRate == 0)) {
            RG(a.J, a.j * Math.PI / 180, 1.5625);
            a.m == "cubemap" ? RG(a.J, a.j * Math.PI / 180, 2.5) : RG(a.J, a.j * Math.PI / 180, 1.5625);
            a.g.useProgram(a.l);
            a.g.clear(a.g.COLOR_BUFFER_BIT);
            fH(a);
            b && (a.g.activeTexture(a.g.TEXTURE0), a.g.bindTexture(a.g.TEXTURE_2D, a.$), a.g.pixelStorei(a.g.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0), a.g.texImage2D(a.g.TEXTURE_2D, 0, a.g.RGBA, a.g.RGBA, a.g.UNSIGNED_BYTE, a.i));
            if (a.m == "equirectangular" || a.m == "halfequirectangular") SG(a.O, a.F, a.Z), SG(a.O, a.J, a.O);
            a.g.bindBuffer(a.g.ARRAY_BUFFER, a.aa);
            a.g.vertexAttribPointer(a.S, 3, a.g.FLOAT, false, 0, 0);
            a.g.enableVertexAttribArray(a.S);
            a.g.bindBuffer(a.g.ARRAY_BUFFER, a.oa);
            a.g.vertexAttribPointer(a.R, 2, a.g.FLOAT, false, 0, 0);
            a.g.enableVertexAttribArray(a.R);
            a.g.bindBuffer(a.g.ELEMENT_ARRAY_BUFFER, a.ea);
            a.m == "cubemap" ? (a.g.uniformMatrix4fv(a.g.getUniformLocation(a.l, "uProjectionMatrix"), false, a.J), a.g.uniformMatrix4fv(a.g.getUniformLocation(a.l, "uModelViewMatrix"), false, a.O)) : a.g.uniformMatrix4fv(a.g.getUniformLocation(a.l, "u_VPMatrix"), false, a.O);
            a.g.uniform1i(a.g.getUniformLocation(a.l, "uSampler"), 0);
            a.P && a.g.viewport(0, 0, a.u.width / 2, a.u.height);
            a.g.drawElements(a.g.TRIANGLES, a.L.indices.length, a.g.UNSIGNED_SHORT, 0);
            a.P && (a.g.viewport(a.u.width / 2, 0, a.u.width / 2, a.u.height), a.g.drawElements(a.g.TRIANGLES, a.L.indices.length, a.g.UNSIGNED_SHORT, 0));
          }
        }
        function fH(a) {
          var b = a.i.videoWidth;
          b || (b = a.u.scrollWidth);
          var c = a.i.videoHeight;
          c || (c = a.u.scrollHeight);
          if (a.va !== b || a.ua !== c) {
            a.u.width = b;
            a.u.height = c;
            a.va = b;
            a.ua = c;
            var d2 = b / c, e = a.J, f = -d2, g = 1 / (d2 - f);
            e[0] = 0 * g;
            e[1] = 0;
            e[2] = 0;
            e[3] = 0;
            e[4] = 0;
            e[5] = 0;
            e[6] = 0;
            e[7] = 0;
            e[8] = (d2 + f) * g;
            e[9] = 0;
            e[10] = -1;
            e[11] = -1;
            e[12] = 0;
            e[13] = 0;
            e[14] = -0;
            e[15] = 0;
            a.J = e;
            a.g.viewport(0, 0, b, c);
          }
        }
        function hH(a, b, c, d2) {
          var e = Infinity, f = 90 * Math.PI / 180;
          a.m == "halfequirectangular" && (e = 90 * Math.PI / 180, f /= 2);
          var g = a.m == "cubemap" ? a.O : a.F;
          a.H += b;
          a.I += c;
          if (a.H < e && a.H > -e) {
            e = Math.sin(b);
            b = Math.cos(b);
            var h = g[0], k2 = g[1], l = g[2], m = g[3], n = g[8], q = g[9], r2 = g[10], u = g[11];
            g !== g && (g[4] = g[4], g[5] = g[5], g[6] = g[6], g[7] = g[7], g[12] = g[12], g[13] = g[13], g[14] = g[14], g[15] = g[15]);
            g[0] = h * b - n * e;
            g[1] = k2 * b - q * e;
            g[2] = l * b - r2 * e;
            g[3] = m * b - u * e;
            g[8] = h * e + n * b;
            g[9] = k2 * e + q * b;
            g[10] = l * e + r2 * b;
            g[11] = m * e + u * b;
          } else a.H -= b;
          a.I < f && a.I > -f ? (f = QG(), e = QG(), b = -1 * c, c = Math.sin(b), b = Math.cos(b), h = e[4], k2 = e[5], l = e[6], m = e[7], n = e[8], q = e[9], r2 = e[10], u = e[11], e !== f && (f[0] = e[0], f[1] = e[1], f[2] = e[2], f[3] = e[3], f[12] = e[12], f[13] = e[13], f[14] = e[14], f[15] = e[15]), f[4] = h * b + n * c, f[5] = k2 * b + q * c, f[6] = l * b + r2 * c, f[7] = m * b + u * c, f[8] = n * b - h * c, f[9] = q * b - k2 * c, f[10] = r2 * b - l * c, f[11] = u * b - m * c, SG(g, f, g)) : a.I -= c;
          c = QG();
          f = QG();
          e = Math.sin(d2);
          d2 = Math.cos(d2);
          b = f[0];
          h = f[1];
          k2 = f[2];
          l = f[3];
          m = f[4];
          n = f[5];
          q = f[6];
          r2 = f[7];
          f !== c && (c[8] = f[8], c[9] = f[9], c[10] = f[10], c[11] = f[11], c[12] = f[12], c[13] = f[13], c[14] = f[14], c[15] = f[15]);
          c[0] = b * d2 + m * e;
          c[1] = h * d2 + n * e;
          c[2] = k2 * d2 + q * e;
          c[3] = l * d2 + r2 * e;
          c[4] = m * d2 - b * e;
          c[5] = n * d2 - h * e;
          c[6] = q * d2 - k2 * e;
          c[7] = r2 * d2 - l * e;
          SG(g, c, g);
          $G(a, false);
        }
        function iH(a, b) {
          if (b === void 0 || b) TG(a.h, a.F), a.V = 0, a.D = VG(), a.D[0] = (a.h[0] - a.M[0]) / 20, a.D[1] = (a.h[1] - a.M[1]) / 20, a.D[2] = (a.h[2] - a.M[2]) / 20, a.D[3] = (a.h[3] - a.M[3]) / 20;
          a.h[0] -= a.D[0];
          a.h[1] -= a.D[1];
          a.h[2] -= a.D[2];
          a.h[3] -= a.D[3];
          b = QG();
          WG(a.h, a.h);
          UG(b, a.h);
          a.F = b;
          a.K && (a.K.stop(), a.K = null);
          a.V < 20 ? a.K = new Cf(function() {
            iH(a, false);
            a.H = 0;
            a.I = 0;
            a.V++;
            $G(a, false);
          }).Y(0.025) : (UG(b, a.M), a.F = b);
        }
        ;
        function jH(a, b, c, d2, e) {
          lb.call(this);
          var f = this;
          this.i = a;
          this.l = b;
          this.G = c;
          this.K = d2;
          this.A = e;
          this.u = new Qc();
          this.h = new Qc();
          this.C = kH(this.l);
          this.g = null;
          this.m = false;
          this.J = this.I = this.H = this.F = this.D = 0;
          this.j = null;
          this.u.o(d2, "loading", function() {
            f.g && iH(f.g);
            lH(f);
          });
          this.u.o(d2, "spatialvideoinfo", function(g) {
            g = g.detail;
            switch (g.projection) {
              case "rect":
                f.j = null;
                break;
              case "equi":
                f.j = "equirectangular";
                break;
              case "hequ":
                switch (g.hfov) {
                  case 360:
                    f.j = "equirectangular";
                    break;
                  case 180:
                    f.j = "halfequirectangular";
                    break;
                  default:
                    g.hfov == null ? f.j = "halfequirectangular" : f.j = null;
                }
                break;
              case "fish":
                f.j = "halfequirectangular";
                break;
              default:
                f.j = null;
            }
            lH(f);
          });
          this.u.o(d2, "nospatialvideoinfo", function() {
            f.j = null;
            lH(f);
          });
          this.u.o(d2, "unloading", function() {
            f.j = null;
            lH(f);
          });
          lH(this);
        }
        ma(jH, lb);
        p = jH.prototype;
        p.release = function() {
          this.u && (this.u.release(), this.u = null);
          this.h && (this.h.release(), this.h = null);
          this.g && (this.g.release(), this.g = null);
          lb.prototype.release.call(this);
        };
        p.configure = function(a) {
          this.A = a;
          lH(this);
        };
        p.Lg = function() {
          return this.l ? !!this.C : !!kH(document.createElement("canvas"));
        };
        p.Wb = function() {
          return !!this.g;
        };
        p.Wd = function() {
          this.g ? this.g.Wd() : bb("Not playing VR content");
        };
        p.Bh = function(a) {
          this.g ? hH(this.g, a * mH, 0, 0) : bb("Not playing VR content");
        };
        p.yh = function(a) {
          this.g ? hH(this.g, 0, a * mH, 0) : bb("Not playing VR content");
        };
        p.Ah = function(a) {
          this.g ? hH(this.g, 0, 0, a * mH) : bb("Not playing VR content");
        };
        function lH(a) {
          if (a.A.displayInVrMode || a.j) {
            a.l || (a.l = document.createElement("canvas"), a.l.classList.add("shaka-vr-canvas-container"), a.G.parentElement.insertBefore(a.l, a.G.nextElementSibling), a.C = kH(a.l));
            var b = a.j || a.A.defaultVrProjectionMode;
            a.g ? a.g.m != b && (a.h.Ta(), a.g.release(), nH(a, b)) : (a.l.style.display = "", nH(a, b), a.dispatchEvent(new T("vrstatuschanged", (/* @__PURE__ */ new Map()).set("newStatus", a.Wb()))));
          } else !a.A.displayInVrMode && !a.j && a.l && a.g && (a.l.style.display = "none", a.h.Ta(), a.g.release(), a.g = null, a.dispatchEvent(new T("vrstatuschanged", (/* @__PURE__ */ new Map()).set("newStatus", a.Wb()))));
        }
        function nH(a, b) {
          a.C && a.l && (a.g = new YG(a.G, a.K, a.l, a.C, b), oH(a));
        }
        function kH(a) {
          if (!a) return null;
          var b = Sb().Ka();
          if (b == "TV" || b == "CONSOLE" || b == "CAST") return null;
          b = t2(["webgl2", "webgl"]);
          for (var c = b.next(); !c.done; c = b.next()) if (c = a.getContext(c.value)) return c;
          return null;
        }
        function oH(a) {
          a.h.o(a.i, "mousedown", function(d2) {
            if (!a.m) {
              var e = d2.clientX;
              d2 = d2.clientY;
              a.m = true;
              a.D = e;
              a.F = d2;
            }
          });
          navigator.maxTouchPoints > 0 && a.h.o(a.i, "touchstart", function(d2) {
            if (!a.m) {
              var e = d2.touches[0].clientX;
              d2 = d2.touches[0].clientY;
              a.m = true;
              a.D = e;
              a.F = d2;
            }
          });
          a.h.o(a.i, "wheel", function(d2) {
            if (!a.m) {
              var e = a.g, f = d2.deltaY;
              f /= 50;
              e.j >= 20 && e.j <= 100 && (e.j += f);
              e.j < 20 ? e.j = 20 : e.j > 100 && (e.j = 100);
              $G(e, false);
              d2.preventDefault();
              d2.stopPropagation();
            }
          });
          a.h.o(a.i, "mousemove", function(d2) {
            a.m && pH(a, d2.clientX, d2.clientY);
          });
          navigator.maxTouchPoints > 0 && a.h.o(a.i, "touchmove", function(d2) {
            a.m && pH(a, d2.touches[0].clientX, d2.touches[0].clientY);
            d2.preventDefault();
          });
          a.h.o(a.i, "mouseleave", function() {
            a.m = false;
          });
          a.h.o(a.i, "mouseup", function() {
            a.m = false;
          });
          navigator.maxTouchPoints > 0 && a.h.o(a.i, "touchend", function() {
            a.m = false;
          });
          var b = false;
          if (window7.DeviceOrientationEvent) if (typeof DeviceMotionEvent.requestPermission == "function") {
            var c = function() {
              DeviceMotionEvent.requestPermission().then(function(d2) {
                d2 !== "granted" || b || (b = true, qH(a));
              });
            };
            DeviceMotionEvent.requestPermission().then(function(d2) {
              a.h.Ea(a.i, "click", c);
              a.h.Ea(a.i, "mouseup", c);
              navigator.maxTouchPoints > 0 && a.h.Ea(a.i, "touchend", c);
              d2 !== "granted" ? (a.h.qa(a.i, "click", c), a.h.qa(a.i, "mouseup", c), navigator.maxTouchPoints > 0 && a.h.qa(a.i, "touchend", c)) : (b = true, qH(a));
            }).catch(function() {
              a.h.Ea(a.i, "click", c);
              a.h.Ea(a.i, "mouseup", c);
              navigator.maxTouchPoints > 0 && a.h.Ea(a.i, "touchend", c);
              a.h.qa(a.i, "click", c);
              a.h.qa(a.i, "mouseup", c);
              navigator.maxTouchPoints > 0 && a.h.qa(a.i, "touchend", c);
            });
          } else b = true, qH(a);
        }
        function qH(a) {
          a.h.o(window7, "deviceorientation", function(b) {
            if (a.g) {
              var c = (b.alpha || 0) - a.H, d2 = (b.beta || 0) - a.I, e = (b.gamma || 0) - a.J;
              if (Math.abs(c) > 10 || Math.abs(d2) > 10 || Math.abs(e) > 5) d2 = e = c = 0;
              a.H = b.alpha || 0;
              a.I = b.beta || 0;
              a.J = b.gamma || 0;
              b = screen.orientation.angle;
              b == 90 || b == -90 ? hH(a.g, c * mH * -1, e * mH * -1, 0) : hH(a.g, c * mH * -1, d2 * mH, 0);
            }
          });
        }
        function pH(a, b, c) {
          var d2 = -0.6 * Math.PI / 180;
          hH(a.g, (b - a.D) * d2, (c - a.F) * -1 * d2, 0);
          a.D = b;
          a.F = c;
        }
        var mH = Math.PI / 180;
        function Z(a, b, c, d2, e) {
          lb.call(this);
          var f = this;
          this.Z = true;
          this.g = e;
          this.F = new rt(c, a, this.g.castReceiverAppId, this.g.castAndroidReceiverCompatible);
          this.sa = true;
          this.C = this.F.Pc();
          this.m = c;
          this.u = this.F.Vb();
          this.$ = a;
          this.l = b;
          this.Ob = d2;
          this.oa = this.u.rf();
          this.A = this.j = null;
          this.S = false;
          this.J = [];
          this.Va = [];
          this.Oa = false;
          this.K = new Cf(function() {
            f.l.classList.add("no-cursor");
            f.Oa = false;
            rH(f);
          });
          this.aa = new Cf(function() {
            f.i.removeAttribute("shown");
            sH(f);
            tH(f);
            f.V && f.V.Oi();
            f.O.Y(f.g.closeMenusDelay);
          });
          this.O = new Cf(function() {
            for (var g = t2(f.J), h = g.next(); !h.done; h = g.next()) kG(h.value, false);
            f.g.enableTooltips && f.G.classList.add("shaka-tooltips-on");
          });
          this.va = new Cf(function() {
            f.Ca() && uH(f);
          });
          this.P = null;
          this.I = [];
          this.ua = vH();
          this.h = new Qc();
          this.D = null;
          this.configure(this.g);
          wH(this);
          xH(this);
          this.ea = /* @__PURE__ */ new Set();
          yH(this);
          this.va.za(this.g.refreshTickInSeconds);
          this.h.o(this.ua, "locale-changed", function(g) {
            g = g.locales[0];
            f.oa.setLocale(g);
            f.l.setAttribute("lang", g);
          });
          this.oa.initInterstitial(this.H, this.$, this.m);
          this.h.o(this.u, "texttrackvisibility", function() {
            tH(f);
          });
          this.h.o(this.u, "unloading", function() {
            f.j || (f.wc() && zH(f), f.Id() && f.Vc());
          });
        }
        ma(Z, lb);
        p = Z.prototype;
        p.destroy = function(a) {
          a = a === void 0 ? false : a;
          var b = this;
          return P(function(c) {
            switch (c.g) {
              case 1:
                if (document.pictureInPictureElement != b.m) {
                  c.B(2);
                  break;
                }
                return G(c, document.exitPictureInPicture(), 2);
              case 2:
                b.h && (b.h.release(), b.h = null);
                b.K && (b.K.stop(), b.K = null);
                b.aa && (b.aa.stop(), b.aa = null);
                b.O && (b.O.stop(), b.O = null);
                b.va && (b.va.stop(), b.va = null);
                b.D && (b.D.release(), b.D = null);
                AH(b);
                b.i && (b.l.removeChild(b.i), b.i = null);
                if (!b.F) {
                  c.B(4);
                  break;
                }
                return G(c, b.F.destroy(a), 5);
              case 5:
                b.F = null;
              case 4:
                b.L && (b.l.removeChild(b.L), b.L = null);
                b.H && (b.l.removeChild(b.H), b.H = null);
                if (!b.$) {
                  c.B(6);
                  break;
                }
                return G(c, b.$.destroy(), 7);
              case 7:
                b.$ = null;
              case 6:
                b.u = null, b.m = null, b.C = null, b.ua = null, b.ea.clear(), BH(b), lb.prototype.release.call(b), H(c);
            }
          });
        };
        function AH(a) {
          for (var b = t2(a.I), c = b.next(); !c.done; c = b.next()) c.value.release();
          a.I = [];
        }
        function CH(a, b) {
          DH.set(a, b);
        }
        p.jk = function(a) {
          this.sa = a;
          yH(this);
        };
        p.Kl = function() {
          rH(this);
        };
        p.configure = function(a) {
          var b = this;
          this.g = a;
          this.F.Mi(a.castReceiverAppId, a.castAndroidReceiverCompatible);
          this.A && (this.A = null);
          this.Ma && (this.Ma = null);
          this.V && (this.V = null);
          this.D && this.D.configure(a);
          this.i ? (Sj(this.i), AH(this)) : (EH(this), FH(this), this.D = new jH(this.i, this.Ob, this.m, this.u, this.g));
          this.l.classList.add("shaka-video-container");
          this.m.classList.add("shaka-video");
          GH(this);
          this.g.addBigPlayButton && HH(this);
          this.g.customContextMenu && (this.V = new nG(this.G, this), this.I.push(this.V));
          this.L || IH(this);
          this.g.seekOnTaps && (JH(this), KH(this));
          this.Ia = W("div");
          this.Ia.classList.add("shaka-server-side-ad-container");
          this.i.appendChild(this.Ia);
          LH(this);
          this.J = Array.from(this.l.getElementsByClassName("shaka-settings-menu"));
          this.J.push.apply(this.J, x(Array.from(this.l.getElementsByClassName("shaka-overflow-menu"))));
          this.Va = Array.from(this.l.getElementsByClassName("shaka-show-controls-on-mouse-over"));
          rH(this);
          a = t2(this.l.getElementsByClassName("shaka-no-propagation"));
          for (var c = a.next(); !c.done; c = a.next()) {
            c = c.value;
            var d2 = function(e) {
              return e.stopPropagation();
            };
            this.h.o(c, "click", d2);
            this.h.o(c, "dblclick", d2);
            navigator.maxTouchPoints > 0 && this.h.o(c, "touchend", function(e) {
              b.Ca() && e.stopPropagation();
            });
          }
        };
        p.di = function(a) {
          (this.Z = a) ? (this.l.setAttribute("shaka-controls", "true"), this.m.tabIndex = -1, this.m.controls = false) : this.l.removeAttribute("shaka-controls");
          rH(this);
        };
        p.Lj = function(a) {
          this.m.controls = a;
          this.m.tabIndex = a ? 0 : -1;
          a && this.di(false);
        };
        p.getAd = function() {
          return this.j;
        };
        p.Ck = function() {
          return this.F;
        };
        p.Uk = function() {
          return this.ua;
        };
        p.wl = function() {
          return this.l;
        };
        p.Pc = function() {
          return this.C;
        };
        p.Tk = function() {
          return this.m;
        };
        p.Vb = function() {
          return this.u;
        };
        p.Sk = function() {
          return this.$;
        };
        p.Jk = function() {
          return this.i;
        };
        p.il = function() {
          return this.Ia;
        };
        p.Fk = function() {
          return this.H;
        };
        p.Gk = function() {
          return this.g;
        };
        p.Hl = function() {
          return this.S;
        };
        p.ii = function(a) {
          (this.S = a) ? this.K.stop() : this.K.Y(3);
        };
        p.Bl = function() {
          return this.sa;
        };
        p.oh = function() {
          return this.A ? this.A.getValue() : this.C.currentTime;
        };
        p.Mj = function(a) {
          this.P = a;
        };
        p.Hc = function() {
          return this.J.some(function(a) {
            return !a.classList.contains("shaka-hidden");
          });
        };
        p.Rc = function() {
          this.O.La();
        };
        function MH(a) {
          return !document.fullscreenEnabled || a.m.webkitSupportsFullscreen && a.g.preferVideoFullScreenInVisionOS && Sb().Ka() == "APPLE_VR" ? false : true;
        }
        function NH(a) {
          return "documentPictureInPicture" in window7 && a.g.preferDocumentPictureInPicture;
        }
        p.se = function() {
          return this.F.Qa() ? false : MH(this) || (!this.j || !this.j.isUsingAnotherMediaElement()) && this.m.webkitSupportsFullscreen ? true : false;
        };
        p.wc = function() {
          if (MH(this)) return !!document.fullscreenElement;
          var a = this.m;
          return a.webkitSupportsFullscreen ? a.webkitDisplayingFullscreen : false;
        };
        function OH(a) {
          var b, c, d2;
          return P(function(e) {
            switch (e.g) {
              case 1:
                sa(e, 2);
                if (!MH(a)) {
                  b = a.m;
                  b.webkitSupportsFullscreen && b.webkitEnterFullscreen();
                  e.B(4);
                  break;
                }
                if (!a.Id()) {
                  e.B(5);
                  break;
                }
                return G(e, a.Vc(), 6);
              case 6:
                if (!NH(a)) {
                  e.B(5);
                  break;
                }
                return G(e, new Promise(function(f) {
                  new Cf(f).Y(0.05);
                }), 5);
              case 5:
                return c = a.g.fullScreenElement, G(e, c.requestFullscreen({
                  navigationUI: "hide"
                }), 9);
              case 9:
                if (!a.g.forceLandscapeOnFullscreen || !screen.orientation) {
                  e.B(4);
                  break;
                }
                sa(e, 11);
                return G(e, screen.orientation.lock("landscape"), 13);
              case 13:
                ua(e, 4, 2);
                break;
              case 11:
                va(e, 2);
              case 4:
                ua(e, 0);
                break;
              case 2:
                d2 = va(e), a.dispatchEvent(new T("error", (/* @__PURE__ */ new Map()).set("detail", d2))), H(e);
            }
          });
        }
        function zH(a) {
          var b;
          return P(function(c) {
            if (!MH(a)) return b = a.m, b.webkitSupportsFullscreen && b.webkitExitFullscreen(), c.B(0);
            screen.orientation && screen.orientation.unlock();
            return G(c, document.exitFullscreen(), 0);
          });
        }
        p.ng = function() {
          var a = this;
          return P(function(b) {
            return a.wc() ? G(b, zH(a), 0) : G(b, OH(a), 0);
          });
        };
        p.Df = function() {
          return this.F.Qa() ? false : document.pictureInPictureEnabled || NH(this) ? !this.m.disablePictureInPicture : false;
        };
        p.Id = function() {
          return !!(window7.documentPictureInPicture && window7.documentPictureInPicture.window || document.pictureInPictureElement);
        };
        p.Vc = function() {
          var a = this, b, c;
          return P(function(d2) {
            switch (d2.g) {
              case 1:
                sa(d2, 2);
                if (NH(a)) {
                  if (!a.wc()) {
                    d2.B(10);
                    break;
                  }
                  return G(d2, zH(a), 10);
                }
                return document.pictureInPictureElement ? G(d2, document.exitPictureInPicture(), 5) : (a.wc() && zH(a), b = a.m, G(d2, b.requestPictureInPicture(), 5));
              case 10:
                return G(d2, PH(a), 5);
              case 5:
                ua(d2, 0);
                break;
              case 2:
                c = va(d2), a.dispatchEvent(new T("error", (/* @__PURE__ */ new Map()).set("detail", c))), H(d2);
            }
          });
        };
        function PH(a) {
          var b, c, d2, e, f, g;
          return P(function(h) {
            if (h.g == 1) {
              if (window7.documentPictureInPicture.window) return window7.documentPictureInPicture.window.close(), h.return();
              b = a.l;
              c = b.getBoundingClientRect();
              return G(h, window7.documentPictureInPicture.requestWindow({
                width: c.width,
                height: c.height
              }), 2);
            }
            d2 = h.h;
            QH(d2);
            e = b.parentNode || document.body;
            f = a.l.cloneNode(true);
            f.style.visibility = "hidden";
            f.style.height = getComputedStyle(b).height;
            e.appendChild(f);
            g = document.createElement("style");
            g.append("[data-shaka-player-container] {\n      width: 100% !important; max-height: 100%}");
            d2.document.head.append(g);
            d2.document.body.append(b);
            a.h.qa(d2, "pagehide", function() {
              f.replaceWith(b);
            });
            H(h);
          });
        }
        function QH(a) {
          var b = [].concat(x(document.styleSheets)).map(function(d2) {
            try {
              return [].concat(x(d2.cssRules)).map(function(f) {
                return f.cssText;
              }).join("");
            } catch (f) {
              var e = document.createElement("link");
              e.rel = "stylesheet";
              e.type = d2.type;
              e.media = d2.media;
              e.href = d2.href;
              a.document.head.appendChild(e);
            }
            return "";
          }).filter(Boolean).join("\n"), c = document.createElement("style");
          c.textContent = b;
          a.document.head.appendChild(c);
        }
        p.Rj = function() {
          kG(this.R, true);
          kG(this.H, true);
          this.j.hasCustomClick() ? this.i.setAttribute("ad-active", "true") : this.i.removeAttribute("ad-active");
        };
        p.aj = function() {
          kG(this.R, false);
          kG(this.H, false);
          this.i.removeAttribute("ad-active");
        };
        function tG(a) {
          if (a.Z) {
            if (a.j && (a.j && a.j.isPaused() ? a.j.play() : a.j && a.j.pause(), a.j.isLinear())) return;
            a.C.duration && (a.C.paused && !a.S ? (a.u.isEnded() && (a.C.currentTime = a.u.ya().start), a.C.play()) : a.C.pause());
          }
        }
        function EH(a) {
          a.i = W("div");
          a.i.classList.add("shaka-controls-container");
          a.l.appendChild(a.i);
          a.l.setAttribute("shaka-controls", "true");
          a.h.o(a.i, "touchend", function(b) {
            a.C.duration && (a.Ca() ? (a.P = Date.now(), wG(a, true)) : RH(a, b), b.cancelable && b.preventDefault());
          });
          a.h.o(a.i, "click", function() {
            wG(a);
          });
          a.h.o(a.i, "dblclick", function() {
            a.g.doubleClickForFullscreen && a.se() && a.ng();
          });
        }
        function HH(a) {
          var b = W("div");
          b.classList.add("shaka-play-button-container");
          a.i.appendChild(b);
          a.Ma = new uG(b, a);
          a.I.push(a.Ma);
        }
        function GH(a) {
          var b = W("div");
          b.classList.add("shaka-scrim-container");
          a.i.appendChild(b);
        }
        function SH(a) {
          a.R = W("div");
          a.R.classList.add("shaka-ad-controls");
          var b = a.j != null && a.j.isLinear();
          kG(a.R, b);
          a.M.appendChild(a.R);
          b = new MG(a.R, a);
          a.I.push(b);
        }
        function IH(a) {
          a.L = W("div");
          a.L.classList.add("shaka-spinner-container");
          a.l.appendChild(a.L);
          var b = W("div");
          b.classList.add("shaka-spinner");
          a.L.appendChild(b);
          b.insertAdjacentHTML("beforeend", '<svg focusable="false" stroke="currentColor"\n         viewBox="0 0 38 38" xmlns="http://www.w3.org/2000/svg"\n         width="50px" height="50px" class="q-spinner text-grey-9">\n      <g transform="translate(1 1)" stroke-width="6" fill="none"\n        fill-rule="evenodd">\n        <circle stroke-opacity=".5" cx="18" cy="18" r="16"></circle>\n        <path d="M34 18c0-9.94-8.06-16-16-16">\n          <animateTransform attributeName="transform" type="rotate"\n            from="0 18 18" to="360 18 18" dur="1s" repeatCount="indefinite">\n          </animateTransform>\n        </path>\n      </g>\n    </svg>');
        }
        function JH(a) {
          var b = W("div");
          b.classList.add("shaka-hidden-fast-forward-container");
          a.i.appendChild(b);
          a.Za = new xG(b, a);
          a.I.push(a.Za);
        }
        function KH(a) {
          var b = W("div");
          b.classList.add("shaka-hidden-rewind-container");
          a.i.appendChild(b);
          a.fb = new yG(b, a);
          a.I.push(a.fb);
        }
        function LH(a) {
          a.M = W("div");
          a.M.classList.add("shaka-bottom-controls");
          a.M.classList.add("shaka-no-propagation");
          a.i.appendChild(a.M);
          a.h.o(a.M, "click", function(e) {
            e.target.closest(".shaka-overflow-button") || a.Rc();
          });
          SH(a);
          TH(a);
          a.G = W("div");
          a.G.classList.add("shaka-controls-button-panel");
          a.G.classList.add("shaka-show-controls-on-mouse-over");
          a.g.enableTooltips && a.G.classList.add("shaka-tooltips-on");
          a.M.appendChild(a.G);
          for (var b = t2(a.g.controlPanelElements), c = b.next(); !c.done; c = b.next()) if (c = c.value, DH.get(c)) {
            var d2 = DH.get(c).create(a.G, a);
            a.I.push(d2);
            c == "time_and_duration" && (c = new mG(a.G, a), a.I.push(c));
          } else bb("Unrecognized control panel element requested:", c);
        }
        function TH(a) {
          if (a.g.addSeekBar) a.A = UH.create(a.M, a), a.I.push(a.A);
          else {
            for (var b = t2(a.J), c = b.next(); !c.done; c = b.next()) c.value.classList.add("shaka-low-position");
            a = a.G;
            a.classList.contains("shaka-tooltips-on") && a.classList.add("shaka-tooltips-low-position");
          }
        }
        function FH(a) {
          a.H = W("div");
          a.H.classList.add("shaka-client-side-ad-container");
          kG(a.H, false);
          a.h.o(a.H, "click", function() {
            wG(a);
          });
          a.l.appendChild(a.H);
        }
        function wH(a) {
          a.h.o(a.u, "buffering", function() {
            VH(a);
          });
          VH(a);
          a.h.o(window7, "keydown", function(b) {
            WH(a, b);
          });
          a.h.o(window7, "click", function() {
            return a.Rc();
          });
          a.h.o(a, "submenuopen", function() {
            a.Rc();
          });
          a.h.o(a.C, "play", function() {
            rH(a);
          });
          a.h.o(a.C, "pause", function() {
            rH(a);
          });
          a.h.o(a.l, "mousemove", function(b) {
            RH(a, b);
          });
          a.h.o(a.l, "touchmove", function(b) {
            RH(a, b);
          }, {
            passive: true
          });
          a.h.o(a.l, "touchend", function(b) {
            RH(a, b);
          }, {
            passive: true
          });
          a.h.o(a.l, "mouseleave", function() {
            a.P || a.K.La();
          });
          a.h.o(a.l, "wheel", function(b) {
            RH(a, b);
          }, {
            passive: true
          });
          a.h.o(a.F, "caststatuschanged", function() {
            yH(a);
          });
          a.h.o(a.D, "vrstatuschanged", function() {
            a.dispatchEvent(new T("vrstatuschanged"));
          });
          a.h.o(a.l, "keydown", function(b) {
            var c = document.activeElement, d2 = c && c.classList ? c.classList.contains("shaka-volume-bar") : false, e = c && c.classList && c.classList.contains("shaka-seek-bar");
            a.i.contains(c) && RH(a, b);
            if (a.g.enableKeyboardPlaybackControls && a.u.ed()) {
              c = a.g.keyboardSeekDistance;
              var f = a.g.keyboardLargeSeekDistance;
              switch (b.key) {
                case "ArrowLeft":
                  a.A && e && !d2 && c > 0 && (b.preventDefault(), XH(a, a.A.getValue() - c));
                  break;
                case "ArrowRight":
                  a.A && e && !d2 && c > 0 && (b.preventDefault(), XH(a, a.A.getValue() + c));
                  break;
                case "PageDown":
                  a.A && e && f > 0 && (b.preventDefault(), XH(a, a.A.getValue() - f));
                  break;
                case "PageUp":
                  a.A && e && f > 0 && (b.preventDefault(), XH(a, a.A.getValue() + f));
                  break;
                case "Home":
                  a.A && XH(a, a.u.ya().start);
                  break;
                case "End":
                  a.A && XH(a, a.u.ya().end);
                  break;
                case "f":
                  a.se() && a.ng();
                  break;
                case "m":
                  a.j && a.j.isLinear() ? a.j.setMuted(!a.j.isMuted()) : a.m.muted = !a.m.muted;
                  break;
                case "p":
                  a.Df() && a.Vc();
                  break;
                case " ":
                  e && tG(a);
              }
            }
          });
          a.h.o(a.l, "keyup", function(b) {
            a.ea.delete(b.key);
          });
          a.h.o(a.oa, "ad-started", function(b) {
            a.j = b.ad;
            a.Rj();
            VH(a);
          });
          a.h.o(a.oa, "ad-stopped", function() {
            a.j = null;
            a.aj();
            VH(a);
          });
          screen.orientation && a.h.o(screen.orientation, "change", function() {
            return P(function(b) {
              return G(b, YH(a), 0);
            });
          });
        }
        function xH(a) {
          if (a.g.setupMediaSession && navigator.mediaSession) {
            var b = function(f, g) {
              try {
                navigator.mediaSession.setActionHandler(f, function(h) {
                  g(h);
                });
              } catch (h) {
              }
            }, c = function() {
              if (a.j && a.j.isLinear()) d2();
              else {
                var f = a.u.ya(), g = f.end - f.start;
                f = parseFloat((a.C.currentTime - f.start).toFixed(2));
                a.u.U() && Math.abs(g - f) < 1 && (g = Infinity);
                try {
                  navigator.mediaSession.setPositionState({
                    duration: Math.max(0, g),
                    playbackRate: a.C.playbackRate,
                    position: Math.max(0, f)
                  });
                } catch (h) {
                }
              }
            }, d2 = function() {
              try {
                navigator.mediaSession.setPositionState();
              } catch (f) {
              }
            }, e = function(f) {
              var g = a.g.keyboardSeekDistance;
              switch (f.action) {
                case "pause":
                  tG(a);
                  break;
                case "play":
                  tG(a);
                  break;
                case "seekbackward":
                  if (f.seekOffset && !isFinite(f.seekOffset)) break;
                  a.j && a.j.isLinear() || XH(a, a.A.getValue() - (f.seekOffset || g));
                  break;
                case "seekforward":
                  if (f.seekOffset && !isFinite(f.seekOffset)) break;
                  a.j && a.j.isLinear() || XH(a, a.A.getValue() + (f.seekOffset || g));
                  break;
                case "seekto":
                  if (f.seekTime && !isFinite(f.seekTime)) break;
                  a.j && a.j.isLinear() || XH(a, a.u.ya().start + f.seekTime);
                  break;
                case "stop":
                  a.u.rc();
                  break;
                case "enterpictureinpicture":
                  a.j && a.j.isLinear() || a.Vc();
              }
            };
            b("pause", e);
            b("play", e);
            b("seekbackward", e);
            b("seekforward", e);
            b("seekto", e);
            b("stop", e);
            ("documentPictureInPicture" in window7 || document.pictureInPictureEnabled) && b("enterpictureinpicture", e);
            b = function() {
              a.u.U() || a.u.ya().start != 0 ? (c(), a.h.o(a.C, "timeupdate", c)) : d2();
            };
            a.u.aa && b();
            a.h.o(a.u, "loaded", b);
            a.h.o(a.u, "unloading", function() {
              a.h.Ea(a.C, "timeupdate", c);
            });
            a.h.o(a.u, "metadata", function(f) {
              if (f = f.payload) {
                var g;
                f.key == "TIT2" && f.data && (g = f.data);
                var h;
                f.key == "APIC" && f.mimeType == "-->" && (h = f.data);
                g && (f = {
                  title: g,
                  artwork: []
                }, navigator.mediaSession.metadata && (f = navigator.mediaSession.metadata, f.title = g), navigator.mediaSession.metadata = new MediaMetadata(f));
                h && (g = a.m, h != g.poster && (g.poster = h), g = {
                  title: "",
                  artwork: [{
                    src: h
                  }]
                }, navigator.mediaSession.metadata && (g = navigator.mediaSession.metadata, g.artwork = [{
                  src: h
                }]), navigator.mediaSession.metadata = new MediaMetadata(g));
              }
            });
          }
        }
        function BH(a) {
          if (a.g.setupMediaSession && navigator.mediaSession) {
            try {
              navigator.mediaSession.setPositionState();
            } catch (b) {
            }
            a = function(b) {
              try {
                navigator.mediaSession.setActionHandler(b, null);
              } catch (c) {
              }
            };
            a("pause");
            a("play");
            a("seekbackward");
            a("seekforward");
            a("seekto");
            a("stop");
            a("enterpictureinpicture");
          }
        }
        function YH(a) {
          return P(function(b) {
            return a.C && a.C.readyState != 0 && !a.F.Qa() && a.g.enableFullscreenOnRotation && a.se() ? screen.orientation.type.includes("landscape") && !a.wc() ? G(b, OH(a), 0) : screen.orientation.type.includes("portrait") && a.wc() ? G(b, zH(a), 0) : b.B(0) : b.return();
          });
        }
        function RH(a, b) {
          b.type == "mousemove" && (a.i.classList.remove("shaka-keyboard-navigation"), rH(a));
          b.type == "touchstart" || b.type == "touchmove" || b.type == "touchend" || b.type == "keyup" ? a.P = Date.now() : a.P + 1e3 < Date.now() && (a.P = null);
          a.P && b.type == "mousemove" || (a.l.classList.remove("no-cursor"), a.Oa = true, a.O.stop(), a.Ca() || (uH(a), rH(a)), a.K.stop(), b.type != "touchend" && b.type != "wheel" && b.type != "keyup" && a.P || a.K.Y(3));
        }
        function ZH(a) {
          return window7.matchMedia("hover: hover").matches ? a.Va.some(function(b) {
            return b.matches(":hover");
          }) : false;
        }
        function tH(a) {
          var b = a.l.getElementsByClassName("shaka-text-container")[0];
          b && (a.Ca() ? b.style.bottom = a.M.clientHeight + "px" : b.style.bottom = "0px");
        }
        function rH(a) {
          var b = a.j ? a.j.isPaused() : false, c = a.C.paused && !a.S, d2 = a.i.classList.contains("shaka-keyboard-navigation");
          b || (!a.j || !a.j.isLinear()) && c || a.Oa || d2 || ZH(a) ? (uH(a), a.i.getAttribute("shown") == null && (a.i.setAttribute("shown", "true"), sH(a)), tH(a), a.aa.stop()) : a.aa.Y(a.g.fadeDelay);
          a.Hc() && a.G.classList.remove("shaka-tooltips-on");
        }
        function wG(a, b) {
          b = b === void 0 ? false : b;
          a.Z && !a.Wb() && (a.Hc() ? a.O.La() : a.g.singleClickForPlayAndPause ? tG(a) : b && a.Ca() && a.bj());
        }
        function yH(a) {
          var b = a.F.Qa();
          a.dispatchEvent(new T("caststatuschanged", (/* @__PURE__ */ new Map()).set("newStatus", b)));
          b ? a.i.getAttribute("casting") == null && (a.i.setAttribute("casting", "true"), sH(a)) : a.i.getAttribute("casting") != null && (a.i.removeAttribute("casting"), sH(a));
        }
        function VH(a) {
          a.Z && (a.j && a.j.isClientRendering() && a.j.isLinear() ? kG(a.L, false) : kG(a.L, a.u.Bf()));
        }
        p.Ca = function() {
          return this.Z ? this.i.getAttribute("shown") != null || this.i.getAttribute("casting") != null : false;
        };
        function sH(a) {
          a.Ca() ? a.dispatchEvent(new T("showingui")) : a.dispatchEvent(new T("hidingui"));
        }
        function XH(a, b) {
          a.C.currentTime = b;
          uH(a);
        }
        function uH(a) {
          if (a.A) if (a.A.setValue(a.C.currentTime), a.A.update(), a.A.isShowing()) {
            for (var b = t2(a.J), c = b.next(); !c.done; c = b.next()) c.value.classList.remove("shaka-low-position");
            b = a.G;
            b.classList.contains("shaka-tooltips-on") && b.classList.remove("shaka-tooltips-low-position");
          } else {
            b = t2(a.J);
            for (c = b.next(); !c.done; c = b.next()) c.value.classList.add("shaka-low-position");
            b = a.G;
            b.classList.contains("shaka-tooltips-on") && b.classList.add("shaka-tooltips-low-position");
          }
          a.dispatchEvent(new T("timeandseekrangeupdated"));
        }
        function WH(a, b) {
          a.ea.add(b.key);
          var c = a.Hc();
          b.key == "Tab" && (a.i.classList.add("shaka-keyboard-navigation"), rH(a), a.h.o(window7, "mousedown", function() {
            a.h.Ea(window7, "mousedown");
          }));
          b.key == "Escape" && a.O.La();
          c && a.ea.has("Tab") && $H(a, b);
        }
        function $H(a, b) {
          var c = a.J.filter(function(f) {
            return !f.classList.contains("shaka-hidden");
          });
          if (c.length) {
            var d2 = c[0];
            if (d2.childNodes.length) {
              for (c = d2.firstElementChild; c && c.classList.contains("shaka-hidden"); ) c = c.nextElementSibling;
              for (d2 = d2.lastElementChild; d2 && d2.classList.contains("shaka-hidden"); ) d2 = d2.previousElementSibling;
              var e = document.activeElement;
              a.ea.has("Shift") ? e == c && (b.preventDefault(), d2.focus()) : e == d2 && (b.preventDefault(), c.focus());
            }
          }
        }
        p.wm = function() {
          var a = new Event("mousemove", {
            bubbles: false,
            cancelable: false
          });
          RH(this, a);
        };
        p.bj = function() {
          this.K.La();
        };
        p.Lg = function() {
          return this.D.Lg();
        };
        p.Wb = function() {
          return this.D.Wb();
        };
        p.ul = function() {
          var a = this.D;
          if (a.g) {
            a = a.g;
            TG(a.h, a.F);
            var b = a.h;
            a = b[0];
            var c = b[1], d2 = b[2];
            b = b[3];
            var e = d2 * d2, f = b * b;
            var g = a * a + c * c + e + f;
            var h = a * b - c * d2;
            h > 0.499995 * g ? (g = Math.PI / 2, a = 2 * Math.atan2(c, a)) : h < -0.499995 * g ? (g = -Math.PI / 2, a = 2 * Math.atan2(c, a)) : (g = Math.asin(2 * (a * d2 - b * c)), a = Math.atan2(2 * (a * b + c * d2), 1 - 2 * (e + f)));
            a = Math.acos(Math.cos(a) * Math.cos(g)) * 180 / Math.PI;
          } else bb("Not playing VR content"), a = null;
          return a;
        };
        p.rl = function() {
          var a = this.D;
          a.g ? a = a.g.j : (bb("Not playing VR content"), a = null);
          return a;
        };
        p.vm = function(a) {
          var b = this.D;
          b.g ? (a < 0 ? (bb("Field of view should be greater than 0"), a = 0) : a > 100 && (bb("Field of view should be less than 100"), a = 100), b = b.g, b.j = a, $G(b, false)) : bb("Not playing VR content");
        };
        p.Wd = function() {
          this.D.Wd();
        };
        p.Bh = function(a) {
          this.D.Bh(a);
        };
        p.yh = function(a) {
          this.D.yh(a);
        };
        p.Ah = function(a) {
          this.D.Ah(a);
        };
        function vH() {
          var a = new Ic("en");
          a.Wa("ar", /* @__PURE__ */ new Map([["AD_DURATION", "\u0645\u062F\u0629 \u0627\u0644\u0625\u0639\u0644\u0627\u0646"], ["AD_PROGRESS", "\u0627\u0644\u0625\u0639\u0644\u0627\u0646 [AD_ON] \u0645\u0646 [NUM_ADS]"], ["AD_STATISTICS", "\u0625\u062D\u0635\u0627\u0621\u0627\u062A \u0627\u0644\u0625\u0639\u0644\u0627\u0646\u0627\u062A"], ["AD_TIME", "\u0627\u0644\u0625\u0639\u0644\u0627\u0646: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "\u062A\u0644\u0642\u0627\u0626\u064A"], ["BACK", "\u0631\u062C\u0648\u0639"], ["CAPTIONS", "\u0627\u0644\u062A\u0631\u062C\u0645\u0629 \u0648\u0627\u0644\u0634\u0631\u062D"], ["CAST", "\u0625\u0631\u0633\u0627\u0644..."], ["CHAPTERS", "\u0627\u0644\u0641\u0635\u0648\u0644"], ["DOWNLOAD_VIDEO_FRAME", "\u062D\u0641\u0638 \u0625\u0637\u0627\u0631 \u0627\u0644\u0641\u064A\u062F\u064A\u0648"], ["ENTER_LOOP_MODE", "\u062A\u0643\u0631\u0627\u0631 \u0627\u0644\u0641\u064A\u062F\u064A\u0648 \u0627\u0644\u062D\u0627\u0644\u064A"], ["ENTER_PICTURE_IN_PICTURE", '\u0627\u0644\u062F\u062E\u0648\u0644 \u0641\u064A \u0648\u0636\u0639 "\u0646\u0627\u0641\u0630\u0629 \u0636\u0645\u0646 \u0646\u0627\u0641\u0630\u0629"'], ["EXIT_FULL_SCREEN", "\u0625\u0646\u0647\u0627\u0621 \u0648\u0636\u0639 \u0645\u0644\u0621 \u0627\u0644\u0634\u0627\u0634\u0629"], ["EXIT_LOOP_MODE", "\u0625\u064A\u0642\u0627\u0641 \u062A\u0643\u0631\u0627\u0631 \u0627\u0644\u0641\u064A\u062F\u064A\u0648 \u0627\u0644\u062D\u0627\u0644\u064A"], ["EXIT_PICTURE_IN_PICTURE", '\u0627\u0644\u062E\u0631\u0648\u062C \u0645\u0646 \u0648\u0636\u0639 "\u0646\u0627\u0641\u0630\u0629 \u0636\u0645\u0646 \u0646\u0627\u0641\u0630\u0629"'], ["FAST_FORWARD", "\u062A\u0642\u062F\u064A\u0645 \u0633\u0631\u064A\u0639"], ["FULL_SCREEN", "\u0645\u0644\u0621 \u0627\u0644\u0634\u0627\u0634\u0629"], ["LANGUAGE", "\u0627\u0644\u0644\u063A\u0629"], ["LIVE", "\u0645\u0628\u0627\u0634\u0631"], ["LOOP", "\u062A\u0643\u0631\u0627\u0631"], ["MORE_SETTINGS", "\u0645\u0632\u064A\u062F \u0645\u0646 \u0627\u0644\u0625\u0639\u062F\u0627\u062F\u0627\u062A"], ["MULTIPLE_LANGUAGES", "\u0644\u063A\u0627\u062A \u0645\u062A\u0639\u062F\u062F\u0629"], ["MUTE", "\u0643\u062A\u0645 \u0627\u0644\u0635\u0648\u062A"], ["NOT_APPLICABLE", "\u063A\u064A\u0631 \u0633\u0627\u0631\u064D"], ["OFF", "\u0625\u064A\u0642\u0627\u0641"], ["ON", "\u062A\u0634\u063A\u064A\u0644"], ["PAUSE", "\u0625\u064A\u0642\u0627\u0641 \u0645\u0624\u0642\u062A"], ["PICTURE_IN_PICTURE", "\u0646\u0627\u0641\u0630\u0629 \u0636\u0645\u0646 \u0627\u0644\u0646\u0627\u0641\u0630\u0629"], ["PLAY", "\u0627\u0644\u062A\u0634\u063A\u064A\u0644"], ["PLAYBACK_RATE", "\u0633\u0631\u0639\u0629 \u0627\u0644\u062A\u0634\u063A\u064A\u0644"], ["QUALITY", "\u0627\u0644\u062C\u0648\u062F\u0629"], ["RECENTER_VR", "\u0625\u0639\u0627\u062F\u0629 \u0627\u0644\u062A\u0648\u0633\u064A\u0637"], ["REPLAY", "\u0625\u0639\u0627\u062F\u0629 \u0627\u0644\u062A\u0634\u063A\u064A\u0644"], ["RESOLUTION", "\u062F\u0631\u062C\u0629 \u0627\u0644\u062F\u0642\u0629"], ["REWIND", "\u062A\u0631\u062C\u064A\u0639"], ["SEEK", "\u0627\u0644\u0628\u062D\u062B \u0628\u0627\u0644\u062A\u0645\u0631\u064A\u0631"], ["SKIP_AD", "\u062A\u062E\u0637\u0651\u064A \u0627\u0644\u0625\u0639\u0644\u0627\u0646"], ["SKIP_TO_LIVE", "\u0627\u0644\u0627\u0646\u062A\u0642\u0627\u0644 \u0625\u0644\u0649 \u0628\u062B \u0645\u0628\u0627\u0634\u0631"], ["STATISTICS", "\u0627\u0644\u0625\u062D\u0635\u0627\u0621\u0627\u062A"], ["SUBTITLE_FORCED", "\u0639\u0631\u0636 \u0625\u062C\u0628\u0627\u0631\u064A"], ["SURROUND", "\u0635\u0648\u062A \u0645\u062D\u064A\u0637\u064A"], ["TOGGLE_STEREOSCOPIC", "\u0625\u064A\u0642\u0627\u0641 \u0627\u0644\u0639\u0631\u0636 \u0627\u0644\u0645\u062C\u0633\u0651\u0645 \u0623\u0648 \u062A\u0641\u0639\u064A\u0644\u0647"], ["UNDETERMINED_LANGUAGE", "\u063A\u064A\u0631 \u0645\u062D\u062F\u062F"], ["UNMUTE", "\u0625\u0639\u0627\u062F\u0629 \u0627\u0644\u0635\u0648\u062A"], ["UNRECOGNIZED_LANGUAGE", "\u063A\u064A\u0631 \u0645\u0639\u0631\u0648\u0641"], ["VOLUME", "\u0645\u0633\u062A\u0648\u0649 \u0627\u0644\u0635\u0648\u062A"]]));
          a.Wa("de", /* @__PURE__ */ new Map([["AD_DURATION", "Dauer der Werbeanzeige"], ["AD_PROGRESS", "Werbung\xA0[AD_ON] von\xA0[NUM_ADS]"], ["AD_STATISTICS", "Anzeigenstatistiken"], ["AD_TIME", "Werbeanzeige: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "Automatisch"], ["BACK", "Zur\xFCck"], ["CAPTIONS", "Untertitel"], ["CAST", "Streamen..."], ["CHAPTERS", "Kapitel"], ["DOWNLOAD_VIDEO_FRAME", "Videoframe speichern"], ["ENTER_LOOP_MODE", "In Endlosschleife spielen"], ["ENTER_PICTURE_IN_PICTURE", "Bild im Bild aktivieren"], ["EXIT_FULL_SCREEN", "Vollbildmodus beenden"], ["EXIT_LOOP_MODE", "Endlosschleife stoppen"], ["EXIT_PICTURE_IN_PICTURE", "Bild im Bild beenden"], ["FAST_FORWARD", "Vorspulen"], ["FULL_SCREEN", "Vollbildmodus"], ["LANGUAGE", "Sprache"], ["LIVE", "Live"], ["LOOP", "Schleife"], ["MORE_SETTINGS", "Weitere Einstellungen"], ["MULTIPLE_LANGUAGES", "Mehrere Sprachen"], ["MUTE", "Stummschalten"], ["NOT_APPLICABLE", "Nicht zutreffend"], ["OFF", "Aus"], ["ON", "Ein"], ["PAUSE", "Pause"], ["PICTURE_IN_PICTURE", "Bild im Bild"], ["PLAY", "Wiedergabe"], ["PLAYBACK_RATE", "Geschwindigkeit"], ["QUALITY", "Qualit\xE4t"], ["RECENTER_VR", "Zentrieren"], ["REPLAY", "Noch einmal wiedergeben"], ["RESOLUTION", "Aufl\xF6sung"], ["REWIND", "Zur\xFCckspulen"], ["SEEK", "Suche"], ["SKIP_AD", "\xDCberspringen"], ["SKIP_TO_LIVE", "Zum Live-Videostream wechseln"], ["STATISTICS", "Statistiken"], ["SUBTITLE_FORCED", "Erzwungen"], ["SURROUND", "Surround"], ["TOGGLE_STEREOSCOPIC", "Einstellung \u201Estereoskopisch\u201C ein\u2011/ausschalten"], ["UNDETERMINED_LANGUAGE", "Unbestimmt"], ["UNMUTE", "Stummschaltung aufheben"], ["UNRECOGNIZED_LANGUAGE", "Unbekannt"], ["VOLUME", "Lautst\xE4rke"]]));
          a.Wa("en", /* @__PURE__ */ new Map([["AD_DURATION", "Ad duration"], ["AD_PROGRESS", "Ad [AD_ON] of [NUM_ADS]"], ["AD_STATISTICS", "Ad statistics"], ["AD_TIME", "Ad: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "Auto"], ["BACK", "Back"], ["CAPTIONS", "Captions"], ["CAST", "Cast..."], ["CHAPTERS", "Chapters"], ["DOWNLOAD_VIDEO_FRAME", "Save video frame"], ["ENTER_LOOP_MODE", "Loop the current video"], ["ENTER_PICTURE_IN_PICTURE", "Enter Picture-in-Picture"], ["EXIT_FULL_SCREEN", "Exit full screen"], ["EXIT_LOOP_MODE", "Stop looping the current video"], ["EXIT_PICTURE_IN_PICTURE", "Exit Picture-in-Picture"], ["FAST_FORWARD", "Fast-forward"], ["FULL_SCREEN", "Full screen"], ["LANGUAGE", "Language"], ["LIVE", "Live"], ["LOOP", "Loop"], ["MORE_SETTINGS", "More settings"], ["MULTIPLE_LANGUAGES", "Multiple languages"], ["MUTE", "Mute"], ["NOT_APPLICABLE", "Not applicable"], ["OFF", "Off"], ["ON", "On"], ["PAUSE", "Pause"], ["PICTURE_IN_PICTURE", "Picture-in-Picture"], ["PLAY", "Play"], ["PLAYBACK_RATE", "Playback speed"], ["QUALITY", "Quality"], ["RECENTER_VR", "Recenter"], ["REPLAY", "Replay"], ["RESOLUTION", "Resolution"], ["REWIND", "Rewind"], ["SEEK", "Seek"], ["SKIP_AD", "Skip Ad"], ["SKIP_NEXT", "Next"], ["SKIP_TO_LIVE", "Skip ahead to live"], ["STATISTICS", "Statistics"], ["SUBTITLE_FORCED", "Forced"], ["SURROUND", "Surround"], ["TOGGLE_STEREOSCOPIC", "Toggle stereoscopic"], ["UNDETERMINED_LANGUAGE", "Undetermined"], ["UNMUTE", "Unmute"], ["UNRECOGNIZED_LANGUAGE", "Unrecognized"], ["VOLUME", "Volume"]]));
          a.Wa("en-GB", /* @__PURE__ */ new Map([["AD_DURATION", "Ad duration"], ["AD_PROGRESS", "Ad [AD_ON] of [NUM_ADS]"], ["AD_STATISTICS", "Ad statistics"], ["AD_TIME", "Ad: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "Auto"], ["BACK", "Back"], ["CAPTIONS", "Captions"], ["CAST", "Cast..."], ["CHAPTERS", "Chapters"], ["DOWNLOAD_VIDEO_FRAME", "Save video frame"], ["ENTER_LOOP_MODE", "Loop the current video"], ["ENTER_PICTURE_IN_PICTURE", "Enter picture-in-picture"], ["EXIT_FULL_SCREEN", "Exit full screen"], ["EXIT_LOOP_MODE", "Stop looping the current video"], ["EXIT_PICTURE_IN_PICTURE", "Exit picture-in-picture"], ["FAST_FORWARD", "Fast-forward"], ["FULL_SCREEN", "Full screen"], ["LANGUAGE", "Language"], ["LIVE", "Live"], ["LOOP", "Loop"], ["MORE_SETTINGS", "More settings"], ["MULTIPLE_LANGUAGES", "Multiple languages"], ["MUTE", "Mute"], ["NOT_APPLICABLE", "Not applicable"], ["OFF", "Off"], ["ON", "On"], ["PAUSE", "Pause"], ["PICTURE_IN_PICTURE", "Picture-in-picture"], ["PLAY", "Play"], ["PLAYBACK_RATE", "Playback speed"], ["QUALITY", "Quality"], ["RECENTER_VR", "Recentre"], ["REPLAY", "Replay"], ["RESOLUTION", "Resolution"], ["REWIND", "Rewind"], ["SEEK", "Seek"], ["SKIP_AD", "Skip ad"], ["SKIP_TO_LIVE", "Skip ahead to live"], ["STATISTICS", "Statistics"], ["SUBTITLE_FORCED", "Forced"], ["SURROUND", "Surround"], ["TOGGLE_STEREOSCOPIC", "Toggle stereoscopic"], ["UNDETERMINED_LANGUAGE", "Undetermined"], ["UNMUTE", "Unmute"], ["UNRECOGNIZED_LANGUAGE", "Unrecognised"], ["VOLUME", "volume"]]));
          a.Wa("es", /* @__PURE__ */ new Map([["AD_DURATION", "Duraci\xF3n del anuncio"], ["AD_PROGRESS", "Anuncio [AD_ON] de [NUM_ADS]"], ["AD_STATISTICS", "Estad\xEDsticas del anuncio"], ["AD_TIME", "Anuncio: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "Autom\xE1tico"], ["BACK", "Atr\xE1s"], ["CAPTIONS", "Subt\xEDtulos"], ["CAST", "Enviar..."], ["CHAPTERS", "Cap\xEDtulos"], ["DOWNLOAD_VIDEO_FRAME", "Guardar fotograma"], ["ENTER_LOOP_MODE", "Reproducir en bucle el v\xEDdeo actual"], ["ENTER_PICTURE_IN_PICTURE", "Activar el modo imagen en imagen"], ["EXIT_FULL_SCREEN", "Salir del modo de pantalla completa"], ["EXIT_LOOP_MODE", "Dejar de reproducir en bucle el v\xEDdeo actual"], ["EXIT_PICTURE_IN_PICTURE", "Salir del modo imagen en imagen"], ["FAST_FORWARD", "Avanzar r\xE1pidamente"], ["FULL_SCREEN", "Pantalla completa"], ["LANGUAGE", "Idioma"], ["LIVE", "En directo"], ["LOOP", "Reproducir en bucle"], ["MORE_SETTINGS", "M\xE1s ajustes"], ["MULTIPLE_LANGUAGES", "Varios idiomas"], ["MUTE", "Silenciar"], ["NOT_APPLICABLE", "No aplicable"], ["OFF", "Desactivado"], ["ON", "Activado"], ["PAUSE", "Pausar"], ["PICTURE_IN_PICTURE", "Imagen en imagen"], ["PLAY", "Reproducir"], ["PLAYBACK_RATE", "Velocidad de reproducci\xF3n"], ["QUALITY", "Calidad"], ["RECENTER_VR", "Volver a centrar"], ["REPLAY", "Volver a reproducir"], ["RESOLUTION", "Resoluci\xF3n"], ["REWIND", "Rebobinar"], ["SEEK", "Buscar"], ["SKIP_AD", "Saltar anuncio"], ["SKIP_NEXT", "Siguiente"], ["SKIP_TO_LIVE", "Ir al v\xEDdeo en directo"], ["STATISTICS", "Estad\xEDsticas"], ["SUBTITLE_FORCED", "Forzado"], ["SURROUND", "Envolvente"], ["TOGGLE_STEREOSCOPIC", "Activar/Desactivar estereosc\xF3pica"], ["UNDETERMINED_LANGUAGE", "Sin especificar"], ["UNMUTE", "Activar sonido"], ["UNRECOGNIZED_LANGUAGE", "No reconocida"], ["VOLUME", "Volumen"]]));
          a.Wa("es-419", /* @__PURE__ */ new Map([["AD_DURATION", "Duraci\xF3n del anuncio"], ["AD_PROGRESS", "Anuncio [AD_ON] de [NUM_ADS]"], ["AD_STATISTICS", "Estad\xEDsticas de anuncios"], ["AD_TIME", "Anuncio: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "Autom\xE1tico"], ["BACK", "Atr\xE1s"], ["CAPTIONS", "Subt\xEDtulos"], ["CAST", "Transmitir..."], ["CHAPTERS", "Cap\xEDtulos"], ["DOWNLOAD_VIDEO_FRAME", "Guardar fotograma"], ["ENTER_LOOP_MODE", "Repetir indefinidamente el video actual"], ["ENTER_PICTURE_IN_PICTURE", "Ingresar al modo de pantalla en pantalla"], ["EXIT_FULL_SCREEN", "Salir de pantalla completa"], ["EXIT_LOOP_MODE", "Detener la repetici\xF3n indefinida del video actual"], ["EXIT_PICTURE_IN_PICTURE", "Salir del modo de pantalla en pantalla"], ["FAST_FORWARD", "Avanzar"], ["FULL_SCREEN", "Pantalla completa"], ["LANGUAGE", "Idioma"], ["LIVE", "En directo"], ["LOOP", "Repetir indefinidamente"], ["MORE_SETTINGS", "M\xE1s opciones de configuraci\xF3n"], ["MULTIPLE_LANGUAGES", "Varios idiomas"], ["MUTE", "Silenciar"], ["NOT_APPLICABLE", "No aplicable"], ["OFF", "Desactivado"], ["ON", "Activado"], ["PAUSE", "Detener"], ["PICTURE_IN_PICTURE", "Pantalla en pantalla"], ["PLAY", "Reproducir"], ["PLAYBACK_RATE", "Velocidad de reproducci\xF3n"], ["QUALITY", "Calidad"], ["RECENTER_VR", "Volver a centrar"], ["REPLAY", "Volver a reproducir"], ["RESOLUTION", "Resoluci\xF3n"], ["REWIND", "Retroceder"], ["SEEK", "Buscar"], ["SKIP_AD", "Omitir anuncio"], ["SKIP_TO_LIVE", "Adelantar hasta la transmisi\xF3n en vivo"], ["STATISTICS", "Estad\xEDsticas"], ["SUBTITLE_FORCED", "Forzado"], ["SURROUND", "Sonido envolvente"], ["TOGGLE_STEREOSCOPIC", "Activar o desactivar el modo estereosc\xF3pico"], ["UNDETERMINED_LANGUAGE", "Sin especificar"], ["UNMUTE", "Dejar de silenciar"], ["UNRECOGNIZED_LANGUAGE", "No reconocida"], ["VOLUME", "Volumen"]]));
          a.Wa("fr", /* @__PURE__ */ new Map([["AD_DURATION", "Dur\xE9e de l'annonce"], ["AD_PROGRESS", "Annonce\xA0[AD_ON] sur\xA0[NUM_ADS]"], ["AD_STATISTICS", "Statistiques sur les annonces"], ["AD_TIME", "Annonce\xA0: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "Automatique"], ["BACK", "Retour"], ["CAPTIONS", "Sous-titres"], ["CAST", "Caster\u2026"], ["CHAPTERS", "Chapitres"], ["DOWNLOAD_VIDEO_FRAME", "T\xE9l\xE9charger l'image de la vid\xE9o"], ["ENTER_LOOP_MODE", "Lire en boucle la vid\xE9o en cours"], ["ENTER_PICTURE_IN_PICTURE", "Utiliser le mode Picture-in-Picture"], ["EXIT_FULL_SCREEN", "Quitter le mode plein \xE9cran"], ["EXIT_LOOP_MODE", "Arr\xEAter la lecture en boucle de la vid\xE9o en cours"], ["EXIT_PICTURE_IN_PICTURE", "Quitter le mode\xA0PIP (Picture-in-picture)"], ["FAST_FORWARD", "Avance rapide"], ["FULL_SCREEN", "Plein \xE9cran"], ["LANGUAGE", "Langue"], ["LIVE", "En direct"], ["LOOP", "R\xE9p\xE9ter"], ["MORE_SETTINGS", "Plus de param\xE8tres"], ["MULTIPLE_LANGUAGES", "Plusieurs langues"], ["MUTE", "Couper le son"], ["NOT_APPLICABLE", "Non applicable"], ["OFF", "D\xE9sactiv\xE9e"], ["ON", "Activ\xE9e"], ["PAUSE", "Pause"], ["PICTURE_IN_PICTURE", "Picture-in-Picture"], ["PLAY", "Visionner"], ["PLAYBACK_RATE", "Vitesse de lecture"], ["QUALITY", "Qualit\xE9"], ["RECENTER_VR", "Recentrer"], ["REPLAY", "Revoir"], ["RESOLUTION", "R\xE9solution"], ["REWIND", "Retour arri\xE8re"], ["SEEK", "Chercher"], ["SKIP_AD", "Passer l'annonce"], ["SKIP_NEXT", "Suivante"], ["SKIP_TO_LIVE", "Acc\xE9der \xE0 la partie la plus r\xE9cente du direct"], ["STATISTICS", "Statistiques"], ["SUBTITLE_FORCED", "Forc\xE9"], ["SURROUND", "Surround"], ["TOGGLE_STEREOSCOPIC", "Activer/D\xE9sactiver le mode st\xE9r\xE9oscopique"], ["UNDETERMINED_LANGUAGE", "Langue ind\xE9termin\xE9e"], ["UNMUTE", "R\xE9activer le son"], ["UNRECOGNIZED_LANGUAGE", "Non reconnu"], ["VOLUME", "Volume"]]));
          a.Wa("it", /* @__PURE__ */ new Map([["AD_DURATION", "Durata dell'annuncio"], ["AD_PROGRESS", "Annuncio [AD_ON] di [NUM_ADS]"], ["AD_STATISTICS", "Statistiche sugli annunci"], ["AD_TIME", "Annuncio: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "Automatica"], ["BACK", "Indietro"], ["CAPTIONS", "Sottotitoli"], ["CAST", "Trasmetti..."], ["CHAPTERS", "Capitoli"], ["DOWNLOAD_VIDEO_FRAME", "Salva fotogramma"], ["ENTER_LOOP_MODE", "Riproduci in loop il video corrente"], ["ENTER_PICTURE_IN_PICTURE", "Attiva Picture in picture"], ["EXIT_FULL_SCREEN", "Esci da schermo intero"], ["EXIT_LOOP_MODE", "Interrompi riproduzione in loop del video corrente"], ["EXIT_PICTURE_IN_PICTURE", "Esci da Picture in picture"], ["FAST_FORWARD", "Avanti veloce"], ["FULL_SCREEN", "Schermo intero"], ["LANGUAGE", "Lingua"], ["LIVE", "Dal vivo"], ["LOOP", "Riproduci in loop"], ["MORE_SETTINGS", "Altre impostazioni"], ["MULTIPLE_LANGUAGES", "Pi\xF9 lingue"], ["MUTE", "Disattiva audio"], ["NOT_APPLICABLE", "Non applicabile"], ["OFF", "Disattivo"], ["ON", "Attivo"], ["PAUSE", "Metti in pausa"], ["PICTURE_IN_PICTURE", "Picture in picture"], ["PLAY", "Riproduci"], ["PLAYBACK_RATE", "Velocit\xE0 di riproduzione"], ["QUALITY", "Qualit\xE0"], ["RECENTER_VR", "Ricentra"], ["REPLAY", "Riproduci di nuovo"], ["RESOLUTION", "Risoluzione"], ["REWIND", "Riavvolgi"], ["SEEK", "Cerca"], ["SKIP_AD", "Salta annuncio"], ["SKIP_TO_LIVE", "Passa alla trasmissione dal vivo"], ["STATISTICS", "Statistiche"], ["SUBTITLE_FORCED", "Forzata"], ["SURROUND", "Surround"], ["TOGGLE_STEREOSCOPIC", "Pulsante di attivazione/disattivazione stereoscopico"], ["UNDETERMINED_LANGUAGE", "Indeterminata"], ["UNMUTE", "Riattiva audio"], ["UNRECOGNIZED_LANGUAGE", "Non riconosciuto"], ["VOLUME", "Volume"]]));
          a.Wa("ja", /* @__PURE__ */ new Map([["AD_DURATION", "\u5E83\u544A\u518D\u751F\u6642\u9593"], ["AD_PROGRESS", "[AD_ON] \u756A\u76EE\u306E\u5E83\u544A\uFF08\u5168 [NUM_ADS] \u500B\uFF09"], ["AD_STATISTICS", "\u5E83\u544A\u306E\u7D71\u8A08\u60C5\u5831"], ["AD_TIME", "\u5E83\u544A: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "\u81EA\u52D5"], ["BACK", "\u623B\u308B"], ["CAPTIONS", "\u5B57\u5E55"], ["CAST", "\u30AD\u30E3\u30B9\u30C8..."], ["CHAPTERS", "\u7AE0"], ["DOWNLOAD_VIDEO_FRAME", "\u52D5\u753B\u30D5\u30EC\u30FC\u30E0\u3092\u4FDD\u5B58"], ["ENTER_LOOP_MODE", "\u73FE\u5728\u306E\u52D5\u753B\u3092\u30EB\u30FC\u30D7\u518D\u751F"], ["ENTER_PICTURE_IN_PICTURE", "\u30D4\u30AF\u30C1\u30E3\u30FC \u30A4\u30F3 \u30D4\u30AF\u30C1\u30E3\u30FC\u3092\u958B\u59CB"], ["EXIT_FULL_SCREEN", "\u5168\u753B\u9762\u8868\u793A\u3092\u7D42\u4E86"], ["EXIT_LOOP_MODE", "\u73FE\u5728\u306E\u52D5\u753B\u306E\u30EB\u30FC\u30D7\u518D\u751F\u3092\u505C\u6B62"], ["EXIT_PICTURE_IN_PICTURE", "\u30D4\u30AF\u30C1\u30E3\u30FC \u30A4\u30F3 \u30D4\u30AF\u30C1\u30E3\u30FC\u3092\u7D42\u4E86"], ["FAST_FORWARD", "\u65E9\u9001\u308A"], ["FULL_SCREEN", "\u5168\u753B\u9762\u8868\u793A"], ["LANGUAGE", "\u8A00\u8A9E"], ["LIVE", "\u30E9\u30A4\u30D6"], ["LOOP", "\u30EB\u30FC\u30D7"], ["MORE_SETTINGS", "\u8A73\u7D30\u8A2D\u5B9A"], ["MULTIPLE_LANGUAGES", "\u591A\u8A00\u8A9E"], ["MUTE", "\u30DF\u30E5\u30FC\u30C8"], ["NOT_APPLICABLE", "\u8A72\u5F53\u306A\u3057"], ["OFF", "\u30AA\u30D5"], ["ON", "\u30AA\u30F3"], ["PAUSE", "\u4E00\u6642\u505C\u6B62"], ["PICTURE_IN_PICTURE", "\u30D4\u30AF\u30C1\u30E3\u30FC \u30A4\u30F3 \u30D4\u30AF\u30C1\u30E3\u30FC"], ["PLAY", "\u518D\u751F"], ["PLAYBACK_RATE", "\u518D\u751F\u901F\u5EA6"], ["QUALITY", "\u54C1\u8CEA"], ["RECENTER_VR", "\u4E2D\u5FC3\u3092\u518D\u8A2D\u5B9A"], ["REPLAY", "\u3082\u3046\u4E00\u5EA6\u518D\u751F"], ["RESOLUTION", "\u89E3\u50CF\u5EA6"], ["REWIND", "\u5DFB\u304D\u623B\u3057"], ["SEEK", "\u30B7\u30FC\u30AF\u518D\u751F"], ["SKIP_AD", "\u5E83\u544A\u3092\u30B9\u30AD\u30C3\u30D7"], ["SKIP_TO_LIVE", "\u30E9\u30A4\u30D6\u914D\u4FE1\u307E\u3067\u30B9\u30AD\u30C3\u30D7"], ["STATISTICS", "\u7D71\u8A08\u60C5\u5831"], ["SUBTITLE_FORCED", "\u5F37\u5236"], ["SURROUND", "\u30B5\u30E9\u30A6\u30F3\u30C9"], ["TOGGLE_STEREOSCOPIC", "\u7ACB\u4F53\u753B\u50CF\u3092\u5207\u308A\u66FF\u3048\u308B"], ["UNDETERMINED_LANGUAGE", "\u4E0D\u660E"], ["UNMUTE", "\u30DF\u30E5\u30FC\u30C8\u3092\u89E3\u9664"], ["UNRECOGNIZED_LANGUAGE", "\u4E0D\u660E"], ["VOLUME", "\u97F3\u91CF"]]));
          a.Wa("ko", /* @__PURE__ */ new Map([["AD_DURATION", "\uAD11\uACE0 \uAE30\uAC04"], ["AD_PROGRESS", "\uAD11\uACE0 [AD_ON]/[NUM_ADS]"], ["AD_STATISTICS", "\uAD11\uACE0 \uD1B5\uACC4"], ["AD_TIME", "\uAD11\uACE0: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "\uC790\uB3D9"], ["BACK", "\uB4A4\uB85C"], ["CAPTIONS", "\uC790\uB9C9"], ["CAST", "\uC804\uC1A1..."], ["CHAPTERS", "\uC7A5"], ["DOWNLOAD_VIDEO_FRAME", "\uB3D9\uC601\uC0C1 \uD504\uB808\uC784 \uC800\uC7A5"], ["ENTER_LOOP_MODE", "\uD604\uC7AC \uB3D9\uC601\uC0C1 \uBC18\uBCF5 \uC7AC\uC0DD"], ["ENTER_PICTURE_IN_PICTURE", "PIP \uBAA8\uB4DC \uC2DC\uC791"], ["EXIT_FULL_SCREEN", "\uC804\uCCB4\uD654\uBA74 \uB2EB\uAE30"], ["EXIT_LOOP_MODE", "\uD604\uC7AC \uB3D9\uC601\uC0C1 \uBC18\uBCF5 \uC7AC\uC0DD \uC911\uC9C0"], ["EXIT_PICTURE_IN_PICTURE", "PIP \uBAA8\uB4DC \uC885\uB8CC"], ["FAST_FORWARD", "\uBE68\uB9AC \uAC10\uAE30"], ["FULL_SCREEN", "\uC804\uCCB4\uD654\uBA74"], ["LANGUAGE", "\uC5B8\uC5B4"], ["LIVE", "\uC2E4\uC2DC\uAC04"], ["LOOP", "\uBC18\uBCF5 \uC7AC\uC0DD"], ["MORE_SETTINGS", "\uC124\uC815 \uB354\uBCF4\uAE30"], ["MULTIPLE_LANGUAGES", "\uC5EC\uB7EC \uC5B8\uC5B4"], ["MUTE", "\uC74C\uC18C\uAC70"], ["NOT_APPLICABLE", "\uD574\uB2F9 \uC0AC\uD56D \uC5C6\uC74C"], ["OFF", "\uC0AC\uC6A9 \uC548\uD568"], ["ON", "\uC0AC\uC6A9"], ["PAUSE", "\uC77C\uC2DC\uC911\uC9C0"], ["PICTURE_IN_PICTURE", "PIP \uBAA8\uB4DC"], ["PLAY", "\uC7AC\uC0DD"], ["PLAYBACK_RATE", "\uC7AC\uC0DD \uC18D\uB3C4"], ["QUALITY", "\uD488\uC9C8"], ["RECENTER_VR", "\uC911\uC2EC \uC7AC\uC124\uC815"], ["REPLAY", "\uB2E4\uC2DC\uBCF4\uAE30"], ["RESOLUTION", "\uD574\uC0C1\uB3C4"], ["REWIND", "\uB418\uAC10\uAE30"], ["SEEK", "\uCC3E\uAE30"], ["SKIP_AD", "\uAD11\uACE0 \uAC74\uB108\uB6F0\uAE30"], ["SKIP_TO_LIVE", "\uB77C\uC774\uBE0C \uB3D9\uC601\uC0C1\uC73C\uB85C \uAC74\uB108\uB6F0\uAE30"], ["STATISTICS", "\uD1B5\uACC4"], ["SUBTITLE_FORCED", "\uAC15\uC81C"], ["SURROUND", "\uC11C\uB77C\uC6B4\uB4DC"], ["TOGGLE_STEREOSCOPIC", "\uC785\uCCB4 \uBCF4\uAE30 \uC804\uD658"], ["UNDETERMINED_LANGUAGE", "\uBBF8\uC815"], ["UNMUTE", "\uC74C\uC18C\uAC70 \uD574\uC81C"], ["UNRECOGNIZED_LANGUAGE", "\uC54C \uC218 \uC5C6\uC74C"], ["VOLUME", "\uBCFC\uB968"]]));
          a.Wa("nl", /* @__PURE__ */ new Map([["AD_DURATION", "Advertentieduur"], ["AD_PROGRESS", "Advertentie [AD_ON] van [NUM_ADS]"], ["AD_STATISTICS", "Advertentiestatistieken"], ["AD_TIME", "Advertentie: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "Automatisch"], ["BACK", "Terug"], ["CAPTIONS", "Ondertiteling"], ["CAST", "Casten..."], ["CHAPTERS", "Hoofdstukken"], ["DOWNLOAD_VIDEO_FRAME", "Videoframe opslaan"], ["ENTER_LOOP_MODE", "De huidige video lussen"], ["ENTER_PICTURE_IN_PICTURE", "Scherm-in-scherm openen"], ["EXIT_FULL_SCREEN", "Volledig scherm sluiten"], ["EXIT_LOOP_MODE", "De huidige video niet meer lussen"], ["EXIT_PICTURE_IN_PICTURE", "Scherm-in-scherm afsluiten"], ["FAST_FORWARD", "Vooruitspoelen"], ["FULL_SCREEN", "Volledig scherm"], ["LANGUAGE", "Taal"], ["LIVE", "Live"], ["LOOP", "Lussen"], ["MORE_SETTINGS", "Meer instellingen"], ["MULTIPLE_LANGUAGES", "Meerdere talen"], ["MUTE", "Geluid uitzetten"], ["NOT_APPLICABLE", "Niet van toepassing"], ["OFF", "Uit"], ["ON", "Aan"], ["PAUSE", "Onderbreken"], ["PICTURE_IN_PICTURE", "Scherm-in-scherm"], ["PLAY", "Afspelen"], ["PLAYBACK_RATE", "Afspeelsnelheid"], ["QUALITY", "Kwaliteit"], ["RECENTER_VR", "Opnieuw centreren"], ["REPLAY", "Opnieuw afspelen"], ["RESOLUTION", "Resolutie"], ["REWIND", "Terugspoelen"], ["SEEK", "Zoeken"], ["SKIP_AD", "Advertentie overslaan"], ["SKIP_TO_LIVE", "Doorgaan naar live"], ["STATISTICS", "Statistieken"], ["SUBTITLE_FORCED", "Afgedwongen"], ["SURROUND", "Surround"], ["TOGGLE_STEREOSCOPIC", "Stereoscopisch aan-/uitzetten"], ["UNDETERMINED_LANGUAGE", "Onbepaald"], ["UNMUTE", "Geluid aanzetten"], ["UNRECOGNIZED_LANGUAGE", "Onbekend"], ["VOLUME", "Volume"]]));
          a.Wa("pl", /* @__PURE__ */ new Map([["AD_DURATION", "Czas trwania reklamy"], ["AD_PROGRESS", "Reklama\xA0[AD_ON] z\xA0[NUM_ADS]"], ["AD_STATISTICS", "Statystyki reklam"], ["AD_TIME", "Reklama: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "Automatycznie"], ["BACK", "Wstecz"], ["CAPTIONS", "Napisy"], ["CAST", "Przesy\u0142aj..."], ["CHAPTERS", "Rozdzia\u0142y"], ["DOWNLOAD_VIDEO_FRAME", "Zapisz klatk\u0119 filmu"], ["ENTER_LOOP_MODE", "Odtwarzaj bie\u017C\u0105cy film w\xA0p\u0119tli"], ["ENTER_PICTURE_IN_PICTURE", "W\u0142\u0105cz tryb obrazu w\xA0obrazie"], ["EXIT_FULL_SCREEN", "Zamknij pe\u0142ny ekran"], ["EXIT_LOOP_MODE", "Wy\u0142\u0105cz odtwarzanie bie\u017C\u0105cego filmu w\xA0p\u0119tli"], ["EXIT_PICTURE_IN_PICTURE", "Wy\u0142\u0105cz tryb obrazu w\xA0obrazie"], ["FAST_FORWARD", "Przewi\u0144 do przodu"], ["FULL_SCREEN", "Pe\u0142ny ekran"], ["LANGUAGE", "J\u0119zyk"], ["LIVE", "Na \u017Cywo"], ["LOOP", "Odtwarzaj w\xA0p\u0119tli"], ["MORE_SETTINGS", "Wi\u0119cej ustawie\u0144"], ["MULTIPLE_LANGUAGES", "Wiele j\u0119zyk\xF3w"], ["MUTE", "Wycisz"], ["NOT_APPLICABLE", "Nie dotyczy"], ["OFF", "Wy\u0142\u0105czone"], ["ON", "W\u0142\u0105czone"], ["PAUSE", "Wstrzymaj"], ["PICTURE_IN_PICTURE", "Obraz w\xA0obrazie"], ["PLAY", "Odtw\xF3rz"], ["PLAYBACK_RATE", "Szybko\u015B\u0107 odtwarzania"], ["QUALITY", "Jako\u015B\u0107"], ["RECENTER_VR", "Wy\u015Brodkuj"], ["REPLAY", "Odtw\xF3rz ponownie"], ["RESOLUTION", "Rozdzielczo\u015B\u0107"], ["REWIND", "Przewi\u0144 do ty\u0142u"], ["SEEK", "Szukaj"], ["SKIP_AD", "Pomi\u0144 reklam\u0119"], ["SKIP_NEXT", "Dalej"], ["SKIP_TO_LIVE", "Przejd\u017A do transmisji na \u017Cywo"], ["STATISTICS", "Statystyki"], ["SUBTITLE_FORCED", "Wymuszone"], ["SURROUND", "Przestrzenny"], ["TOGGLE_STEREOSCOPIC", "Prze\u0142\u0105cz tryb stereoskopowy"], ["UNDETERMINED_LANGUAGE", "Nie okre\u015Blono"], ["UNMUTE", "Wy\u0142\u0105cz wyciszenie"], ["UNRECOGNIZED_LANGUAGE", "Nierozpoznany"], ["VOLUME", "G\u0142o\u015Bno\u015B\u0107"]]));
          a.Wa("pt-BR", /* @__PURE__ */ new Map([["AD_DURATION", "Dura\xE7\xE3o do an\xFAncio"], ["AD_PROGRESS", "An\xFAncio [AD_ON] de [NUM_ADS]"], ["AD_STATISTICS", "Estat\xEDsticas de an\xFAncios"], ["AD_TIME", "An\xFAncio: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "Autom\xE1tica"], ["BACK", "Voltar"], ["CAPTIONS", "Legendas"], ["CAST", "Transmitir..."], ["CHAPTERS", "Cap\xEDtulos"], ["DOWNLOAD_VIDEO_FRAME", "Salvar frame do v\xEDdeo"], ["ENTER_LOOP_MODE", "Repetir o v\xEDdeo atual"], ["ENTER_PICTURE_IN_PICTURE", "Entrar no modo picture-in-picture"], ["EXIT_FULL_SCREEN", "Sair do modo tela cheia"], ["EXIT_LOOP_MODE", "Parar repeti\xE7\xE3o do v\xEDdeo atual"], ["EXIT_PICTURE_IN_PICTURE", "Sair de picture-in-picture"], ["FAST_FORWARD", "Avan\xE7ar"], ["FULL_SCREEN", "Tela cheia"], ["LANGUAGE", "Idioma"], ["LIVE", "Ao vivo"], ["LOOP", "Repetir"], ["MORE_SETTINGS", "Mais defini\xE7\xF5es"], ["MULTIPLE_LANGUAGES", "V\xE1rios idiomas"], ["MUTE", "Desativar som"], ["NOT_APPLICABLE", "N\xE3o relevante"], ["OFF", "Desativado"], ["ON", "Ativado"], ["PAUSE", "Pausar"], ["PICTURE_IN_PICTURE", "Picture-in-picture"], ["PLAY", "Reproduzir"], ["PLAYBACK_RATE", "Velocidade da reprodu\xE7\xE3o"], ["QUALITY", "Qualidade"], ["RECENTER_VR", "Centralizar"], ["REPLAY", "Repetir"], ["RESOLUTION", "Resolu\xE7\xE3o"], ["REWIND", "Voltar"], ["SEEK", "Procurar"], ["SKIP_AD", "Pular an\xFAncio"], ["SKIP_TO_LIVE", "Pular para transmiss\xE3o ao vivo"], ["STATISTICS", "Estat\xEDsticas"], ["SUBTITLE_FORCED", "Exibi\xE7\xE3o for\xE7ada"], ["SURROUND", "Surround"], ["TOGGLE_STEREOSCOPIC", "Alternar imagem estereosc\xF3pica"], ["UNDETERMINED_LANGUAGE", "Indeterminado"], ["UNMUTE", "Ativar som"], ["UNRECOGNIZED_LANGUAGE", "N\xE3o reconhecido"], ["VOLUME", "Volume"]]));
          a.Wa("ru", /* @__PURE__ */ new Map([["AD_DURATION", "\u041F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C \u0440\u0435\u043A\u043B\u0430\u043C\u044B"], ["AD_PROGRESS", "\u0420\u0435\u043A\u043B\u0430\u043C\u0430 [AD_ON] \u0438\u0437 [NUM_ADS]"], ["AD_STATISTICS", "\u0421\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0430 \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u0438\u0439"], ["AD_TIME", "\u0420\u0435\u043A\u043B\u0430\u043C\u0430: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "\u0410\u0432\u0442\u043E"], ["BACK", "\u041D\u0430\u0437\u0430\u0434"], ["CAPTIONS", "\u0421\u0443\u0431\u0442\u0438\u0442\u0440\u044B"], ["CAST", "\u0422\u0440\u0430\u043D\u0441\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C..."], ["CHAPTERS", "\u042D\u043F\u0438\u0437\u043E\u0434\u044B"], ["DOWNLOAD_VIDEO_FRAME", "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u043A\u0430\u0434\u0440 \u0432\u0438\u0434\u0435\u043E"], ["ENTER_LOOP_MODE", "\u0417\u0430\u0446\u0438\u043A\u043B\u0438\u0442\u044C \u0442\u0435\u043A\u0443\u0449\u0435\u0435 \u0432\u0438\u0434\u0435\u043E"], ["ENTER_PICTURE_IN_PICTURE", '\u041F\u0435\u0440\u0435\u0439\u0442\u0438 \u0432 \u0440\u0435\u0436\u0438\u043C "\u041A\u0430\u0440\u0442\u0438\u043D\u043A\u0430 \u0432 \u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0435"'], ["EXIT_FULL_SCREEN", "\u041E\u0431\u044B\u0447\u043D\u044B\u0439 \u0440\u0435\u0436\u0438\u043C"], ["EXIT_LOOP_MODE", "\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C \u0437\u0430\u0446\u0438\u043A\u043B\u0438\u0432\u0430\u043D\u0438\u0435 \u0442\u0435\u043A\u0443\u0449\u0435\u0433\u043E \u0432\u0438\u0434\u0435\u043E"], ["EXIT_PICTURE_IN_PICTURE", '\u0412\u044B\u0439\u0442\u0438 \u0438\u0437 \u0440\u0435\u0436\u0438\u043C\u0430 "\u041A\u0430\u0440\u0442\u0438\u043D\u043A\u0430 \u0432 \u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0435"'], ["FAST_FORWARD", "\u041F\u0435\u0440\u0435\u043C\u043E\u0442\u043A\u0430 \u0432\u043F\u0435\u0440\u0435\u0434"], ["FULL_SCREEN", "\u041F\u043E\u043B\u043D\u043E\u044D\u043A\u0440\u0430\u043D\u043D\u044B\u0439 \u0440\u0435\u0436\u0438\u043C"], ["LANGUAGE", "\u042F\u0437\u044B\u043A"], ["LIVE", "\u041F\u0440\u044F\u043C\u043E\u0439 \u044D\u0444\u0438\u0440"], ["LOOP", "\u0417\u0430\u0446\u0438\u043A\u043B\u0438\u0442\u044C"], ["MORE_SETTINGS", "\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438"], ["MULTIPLE_LANGUAGES", "\u041D\u0435\u0441\u043A\u043E\u043B\u044C\u043A\u043E \u044F\u0437\u044B\u043A\u043E\u0432"], ["MUTE", "\u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0437\u0432\u0443\u043A"], ["NOT_APPLICABLE", "\u041D\u0435\u043F\u0440\u0438\u043C\u0435\u043D\u0438\u043C\u043E"], ["OFF", "\u0412\u044B\u043A\u043B."], ["ON", "\u0412\u043A\u043B."], ["PAUSE", "\u041F\u0430\u0443\u0437\u0430"], ["PICTURE_IN_PICTURE", "\u041A\u0430\u0440\u0442\u0438\u043D\u043A\u0430 \u0432 \u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0435"], ["PLAY", "\u0412\u043E\u0441\u043F\u0440\u043E\u0438\u0437\u0432\u0435\u0441\u0442\u0438"], ["PLAYBACK_RATE", "\u0421\u043A\u043E\u0440\u043E\u0441\u0442\u044C \u0432\u043E\u0441\u043F\u0440\u043E\u0438\u0437\u0432\u0435\u0434\u0435\u043D\u0438\u044F"], ["QUALITY", "\u041A\u0430\u0447\u0435\u0441\u0442\u0432\u043E"], ["RECENTER_VR", "\u0426\u0435\u043D\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0437\u0430\u043D\u043E\u0432\u043E"], ["REPLAY", "\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C"], ["RESOLUTION", "\u0420\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u0435"], ["REWIND", "\u041F\u0435\u0440\u0435\u043C\u043E\u0442\u0430\u0442\u044C \u043D\u0430\u0437\u0430\u0434"], ["SEEK", "\u041F\u0435\u0440\u0435\u043C\u043E\u0442\u043A\u0430"], ["SKIP_AD", "\u041F\u0440\u043E\u043F\u0443\u0441\u0442\u0438\u0442\u044C"], ["SKIP_TO_LIVE", "\u041F\u0440\u043E\u043F\u0443\u0441\u0442\u0438\u0442\u044C \u0438 \u043F\u0435\u0440\u0435\u0439\u0442\u0438 \u043A \u043F\u0440\u044F\u043C\u043E\u0439 \u0442\u0440\u0430\u043D\u0441\u043B\u044F\u0446\u0438\u0438"], ["STATISTICS", "\u0421\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0430"], ["SUBTITLE_FORCED", "\u0421\u0443\u0431\u0442\u0438\u0442\u0440\u044B \u043F\u0440\u0438\u043D\u0443\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E"], ["SURROUND", "\u041E\u0431\u044A\u0435\u043C\u043D\u044B\u0439 \u0437\u0432\u0443\u043A"], ["TOGGLE_STEREOSCOPIC", "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0438\u043B\u0438 \u043E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0441\u0442\u0435\u0440\u0435\u043E\u0441\u043A\u043E\u043F\u0438\u0447\u0435\u0441\u043A\u0438\u0439 \u0440\u0435\u0436\u0438\u043C"], ["UNDETERMINED_LANGUAGE", "\u041D\u0435 \u0443\u043A\u0430\u0437\u0430\u043D\u043E"], ["UNMUTE", "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0437\u0432\u0443\u043A"], ["UNRECOGNIZED_LANGUAGE", "\u041D\u0435 \u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043E"], ["VOLUME", "\u0413\u0440\u043E\u043C\u043A\u043E\u0441\u0442\u044C"]]));
          a.Wa("th", /* @__PURE__ */ new Map([["AD_DURATION", "\u0E23\u0E30\u0E22\u0E30\u0E40\u0E27\u0E25\u0E32\u0E42\u0E06\u0E29\u0E13\u0E32"], ["AD_PROGRESS", "\u0E42\u0E06\u0E29\u0E13\u0E32 [AD_ON] \u0E08\u0E32\u0E01 [NUM_ADS] \u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"], ["AD_STATISTICS", "\u0E2A\u0E16\u0E34\u0E15\u0E34\u0E42\u0E06\u0E29\u0E13\u0E32"], ["AD_TIME", "\u0E42\u0E06\u0E29\u0E13\u0E32: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "\u0E2D\u0E31\u0E15\u0E42\u0E19\u0E21\u0E31\u0E15\u0E34"], ["BACK", "\u0E01\u0E25\u0E31\u0E1A"], ["CAPTIONS", "\u0E04\u0E33\u0E1A\u0E23\u0E23\u0E22\u0E32\u0E22\u0E41\u0E17\u0E19\u0E40\u0E2A\u0E35\u0E22\u0E07"], ["CAST", "\u0E41\u0E04\u0E2A\u0E15\u0E4C..."], ["CHAPTERS", "\u0E1A\u0E17"], ["DOWNLOAD_VIDEO_FRAME", "\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E40\u0E1F\u0E23\u0E21\u0E27\u0E34\u0E14\u0E35\u0E42\u0E2D"], ["ENTER_LOOP_MODE", "\u0E27\u0E19\u0E0B\u0E49\u0E33\u0E27\u0E34\u0E14\u0E35\u0E42\u0E2D\u0E1B\u0E31\u0E08\u0E08\u0E38\u0E1A\u0E31\u0E19"], ["ENTER_PICTURE_IN_PICTURE", "\u0E40\u0E02\u0E49\u0E32\u0E2A\u0E39\u0E48\u0E01\u0E32\u0E23\u0E41\u0E2A\u0E14\u0E07\u0E20\u0E32\u0E1E\u0E0B\u0E49\u0E2D\u0E19\u0E20\u0E32\u0E1E"], ["EXIT_FULL_SCREEN", "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E01\u0E32\u0E23\u0E41\u0E2A\u0E14\u0E07\u0E41\u0E1A\u0E1A\u0E40\u0E15\u0E47\u0E21\u0E2B\u0E19\u0E49\u0E32\u0E08\u0E2D"], ["EXIT_LOOP_MODE", "\u0E2B\u0E22\u0E38\u0E14\u0E27\u0E19\u0E0B\u0E49\u0E33\u0E27\u0E34\u0E14\u0E35\u0E42\u0E2D\u0E1B\u0E31\u0E08\u0E08\u0E38\u0E1A\u0E31\u0E19"], ["EXIT_PICTURE_IN_PICTURE", "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E01\u0E32\u0E23\u0E41\u0E2A\u0E14\u0E07\u0E20\u0E32\u0E1E\u0E0B\u0E49\u0E2D\u0E19\u0E20\u0E32\u0E1E"], ["FAST_FORWARD", "\u0E01\u0E23\u0E2D\u0E44\u0E1B\u0E02\u0E49\u0E32\u0E07\u0E2B\u0E19\u0E49\u0E32"], ["FULL_SCREEN", "\u0E40\u0E15\u0E47\u0E21\u0E2B\u0E19\u0E49\u0E32\u0E08\u0E2D"], ["LANGUAGE", "\u0E20\u0E32\u0E29\u0E32"], ["LIVE", "\u0E2A\u0E14"], ["LOOP", "\u0E25\u0E39\u0E1B"], ["MORE_SETTINGS", "\u0E01\u0E32\u0E23\u0E15\u0E31\u0E49\u0E07\u0E04\u0E48\u0E32\u0E40\u0E1E\u0E34\u0E48\u0E21\u0E40\u0E15\u0E34\u0E21"], ["MULTIPLE_LANGUAGES", "\u0E2B\u0E25\u0E32\u0E22\u0E20\u0E32\u0E29\u0E32"], ["MUTE", "\u0E1B\u0E34\u0E14\u0E40\u0E2A\u0E35\u0E22\u0E07"], ["NOT_APPLICABLE", "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E35\u0E48\u0E22\u0E27\u0E02\u0E49\u0E2D\u0E07"], ["OFF", "\u0E1B\u0E34\u0E14"], ["ON", "\u0E40\u0E1B\u0E34\u0E14"], ["PAUSE", "\u0E2B\u0E22\u0E38\u0E14\u0E0A\u0E31\u0E48\u0E27\u0E04\u0E23\u0E32\u0E27"], ["PICTURE_IN_PICTURE", "\u0E01\u0E32\u0E23\u0E41\u0E2A\u0E14\u0E07\u0E20\u0E32\u0E1E\u0E0B\u0E49\u0E2D\u0E19\u0E20\u0E32\u0E1E"], ["PLAY", "\u0E40\u0E25\u0E48\u0E19"], ["PLAYBACK_RATE", "\u0E04\u0E27\u0E32\u0E21\u0E40\u0E23\u0E47\u0E27\u0E43\u0E19\u0E01\u0E32\u0E23\u0E40\u0E25\u0E48\u0E19"], ["QUALITY", "\u0E04\u0E38\u0E13\u0E20\u0E32\u0E1E"], ["RECENTER_VR", "\u0E08\u0E31\u0E14\u0E01\u0E36\u0E48\u0E07\u0E01\u0E25\u0E32\u0E07\u0E43\u0E2B\u0E21\u0E48"], ["REPLAY", "\u0E40\u0E25\u0E48\u0E19\u0E0B\u0E49\u0E33"], ["RESOLUTION", "\u0E04\u0E27\u0E32\u0E21\u0E25\u0E30\u0E40\u0E2D\u0E35\u0E22\u0E14"], ["REWIND", "\u0E01\u0E23\u0E2D\u0E01\u0E25\u0E31\u0E1A"], ["SEEK", "\u0E04\u0E49\u0E19\u0E2B\u0E32"], ["SKIP_AD", "\u0E02\u0E49\u0E32\u0E21\u0E42\u0E06\u0E29\u0E13\u0E32"], ["SKIP_TO_LIVE", "\u0E02\u0E49\u0E32\u0E21\u0E44\u0E1B\u0E17\u0E35\u0E48\u0E01\u0E32\u0E23\u0E16\u0E48\u0E32\u0E22\u0E17\u0E2D\u0E14\u0E2A\u0E14"], ["STATISTICS", "\u0E2A\u0E16\u0E34\u0E15\u0E34"], ["SUBTITLE_FORCED", "\u0E1A\u0E31\u0E07\u0E04\u0E31\u0E1A"], ["SURROUND", "\u0E40\u0E0B\u0E2D\u0E23\u0E4C\u0E23\u0E32\u0E27\u0E14\u0E4C"], ["TOGGLE_STEREOSCOPIC", "\u0E40\u0E1B\u0E34\u0E14/\u0E1B\u0E34\u0E14\u0E1F\u0E35\u0E40\u0E08\u0E2D\u0E23\u0E4C\u0E2A\u0E32\u0E21\u0E21\u0E34\u0E15\u0E34"], ["UNDETERMINED_LANGUAGE", "\u0E44\u0E21\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14"], ["UNMUTE", "\u0E40\u0E1B\u0E34\u0E14\u0E40\u0E2A\u0E35\u0E22\u0E07"], ["UNRECOGNIZED_LANGUAGE", "\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01"], ["VOLUME", "\u0E23\u0E30\u0E14\u0E31\u0E1A\u0E40\u0E2A\u0E35\u0E22\u0E07"]]));
          a.Wa("tr", /* @__PURE__ */ new Map([["AD_DURATION", "Reklam s\xFCresi"], ["AD_PROGRESS", "[AD_ON]/[NUM_ADS] reklam"], ["AD_STATISTICS", "Reklam istatistikleri"], ["AD_TIME", "Reklam: [AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "Otomatik"], ["BACK", "Geri"], ["CAPTIONS", "Altyaz\u0131lar"], ["CAST", "Yay\u0131nla..."], ["CHAPTERS", "B\xF6l\xFCmler"], ["DOWNLOAD_VIDEO_FRAME", "Video karesini kaydet"], ["ENTER_LOOP_MODE", "Mevcut videoyu d\xF6ng\xFCye al"], ["ENTER_PICTURE_IN_PICTURE", "Pencere i\xE7inde Pencere moduna gir"], ["EXIT_FULL_SCREEN", "Tam ekrandan \xE7\u0131k"], ["EXIT_LOOP_MODE", "Mevcut videonun d\xF6ng\xFCs\xFCn\xFC durdur"], ["EXIT_PICTURE_IN_PICTURE", "Pencere \u0130\xE7inde Pencereden \xC7\u0131k"], ["FAST_FORWARD", "\u0130leri sar"], ["FULL_SCREEN", "Tam ekran"], ["LANGUAGE", "Dil"], ["LIVE", "Canl\u0131"], ["LOOP", "D\xF6ng\xFC"], ["MORE_SETTINGS", "Daha fazla ayar"], ["MULTIPLE_LANGUAGES", "Birden \xE7ok dil"], ["MUTE", "Sesi kapat"], ["NOT_APPLICABLE", "Ge\xE7erli de\u011Fil"], ["OFF", "Kapal\u0131"], ["ON", "A\xE7\u0131k"], ["PAUSE", "Duraklat"], ["PICTURE_IN_PICTURE", "Pencere \u0130\xE7inde Pencere"], ["PLAY", "Oynat"], ["PLAYBACK_RATE", "\xC7alma h\u0131z\u0131"], ["QUALITY", "Kalite"], ["RECENTER_VR", "Ortala"], ["REPLAY", "Tekrar Oynat"], ["RESOLUTION", "\xC7\xF6z\xFCn\xFCrl\xFCk"], ["REWIND", "Geri sar"], ["SEEK", "Ara"], ["SKIP_AD", "Reklam\u0131 Atla"], ["SKIP_TO_LIVE", "Canl\u0131 yay\u0131na atla"], ["STATISTICS", "\u0130statistikler"], ["SUBTITLE_FORCED", "Zorunlu"], ["SURROUND", "Surround"], ["TOGGLE_STEREOSCOPIC", "Stereoskopik modu a\xE7/kapat"], ["UNDETERMINED_LANGUAGE", "Belirsiz"], ["UNMUTE", "Sesi a\xE7"], ["UNRECOGNIZED_LANGUAGE", "Tan\u0131nmayan"], ["VOLUME", "Ses"]]));
          a.Wa("zh", /* @__PURE__ */ new Map([["AD_DURATION", "\u5E7F\u544A\u6301\u7EED\u65F6\u95F4"], ["AD_PROGRESS", "\u5E7F\u544A [AD_ON]/[NUM_ADS]"], ["AD_STATISTICS", "\u5E7F\u544A\u7EDF\u8BA1\u4FE1\u606F"], ["AD_TIME", "\u5E7F\u544A\uFF1A[AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "\u81EA\u52A8"], ["BACK", "\u8FD4\u56DE"], ["CAPTIONS", "\u5B57\u5E55"], ["CAST", "\u6295\u653E\u2026"], ["CHAPTERS", "\u7AE0\u8282"], ["DOWNLOAD_VIDEO_FRAME", "\u4FDD\u5B58\u89C6\u9891\u5E27"], ["ENTER_LOOP_MODE", "\u5FAA\u73AF\u64AD\u653E\u5F53\u524D\u89C6\u9891"], ["ENTER_PICTURE_IN_PICTURE", "\u8FDB\u5165\u201C\u753B\u4E2D\u753B\u201D\u6A21\u5F0F"], ["EXIT_FULL_SCREEN", "\u9000\u51FA\u5168\u5C4F\u6A21\u5F0F"], ["EXIT_LOOP_MODE", "\u505C\u6B62\u5FAA\u73AF\u64AD\u653E\u5F53\u524D\u89C6\u9891"], ["EXIT_PICTURE_IN_PICTURE", "\u9000\u51FA\u201C\u753B\u4E2D\u753B\u201D\u6A21\u5F0F"], ["FAST_FORWARD", "\u5FEB\u8FDB"], ["FULL_SCREEN", "\u5168\u5C4F"], ["LANGUAGE", "\u8BED\u8A00"], ["LIVE", "\u76F4\u64AD"], ["LOOP", "\u5FAA\u73AF\u64AD\u653E"], ["MORE_SETTINGS", "\u66F4\u591A\u8BBE\u7F6E"], ["MULTIPLE_LANGUAGES", "\u591A\u79CD\u8BED\u8A00"], ["MUTE", "\u9759\u97F3"], ["NOT_APPLICABLE", "\u4E0D\u9002\u7528"], ["OFF", "\u5173\u95ED"], ["ON", "\u5F00\u542F"], ["PAUSE", "\u6682\u505C"], ["PICTURE_IN_PICTURE", "\u753B\u4E2D\u753B"], ["PLAY", "\u64AD\u653E"], ["PLAYBACK_RATE", "\u64AD\u653E\u901F\u5EA6"], ["QUALITY", "\u753B\u8D28"], ["RECENTER_VR", "\u91CD\u65B0\u7F6E\u4E2D"], ["REPLAY", "\u91CD\u653E"], ["RESOLUTION", "\u5206\u8FA8\u7387"], ["REWIND", "\u5FEB\u9000"], ["SEEK", "\u8FDB\u5EA6"], ["SKIP_AD", "\u8DF3\u8FC7\u5E7F\u544A"], ["SKIP_TO_LIVE", "\u8DF3\u81F3\u5F53\u524D\u76F4\u64AD"], ["STATISTICS", "\u7EDF\u8BA1\u4FE1\u606F"], ["SUBTITLE_FORCED", "\u5DF2\u5F3A\u5236\u663E\u793A"], ["SURROUND", "\u73AF\u7ED5\u58F0"], ["TOGGLE_STEREOSCOPIC", "\u5207\u6362\u7ACB\u4F53\u58F0"], ["UNDETERMINED_LANGUAGE", "\u672A\u786E\u5B9A"], ["UNMUTE", "\u53D6\u6D88\u9759\u97F3"], ["UNRECOGNIZED_LANGUAGE", "\u65E0\u6CD5\u8BC6\u522B"], ["VOLUME", "\u97F3\u91CF"]]));
          a.Wa("zh-TW", /* @__PURE__ */ new Map([["AD_DURATION", "\u5EE3\u544A\u9577\u5EA6"], ["AD_PROGRESS", "\u5EE3\u544A [AD_ON]/[NUM_ADS]"], ["AD_STATISTICS", "\u5EE3\u544A\u7D71\u8A08\u8CC7\u6599"], ["AD_TIME", "\u5EE3\u544A\uFF1A[AD_TIME]"], ["AIRPLAY", "AirPlay"], ["AUTO_QUALITY", "\u81EA\u52D5"], ["BACK", "\u8FD4\u56DE"], ["CAPTIONS", "\u5B57\u5E55"], ["CAST", "\u6295\u653E..."], ["CHAPTERS", "\u7AE0\u7BC0"], ["DOWNLOAD_VIDEO_FRAME", "\u5132\u5B58\u5F71\u7247\u5F71\u683C"], ["ENTER_LOOP_MODE", "\u5FAA\u74B0\u64AD\u653E\u76EE\u524D\u7684\u5F71\u7247"], ["ENTER_PICTURE_IN_PICTURE", "\u9032\u5165\u5B50\u6BCD\u756B\u9762"], ["EXIT_FULL_SCREEN", "\u9000\u51FA\u5168\u87A2\u5E55\u6A21\u5F0F"], ["EXIT_LOOP_MODE", "\u505C\u6B62\u5FAA\u74B0\u64AD\u653E\u76EE\u524D\u7684\u5F71\u7247"], ["EXIT_PICTURE_IN_PICTURE", "\u96E2\u958B\u5B50\u6BCD\u756B\u9762"], ["FAST_FORWARD", "\u5FEB\u8F49"], ["FULL_SCREEN", "\u5168\u87A2\u5E55"], ["LANGUAGE", "\u8A9E\u8A00"], ["LIVE", "\u76F4\u64AD"], ["LOOP", "\u5FAA\u74B0\u64AD\u653E"], ["MORE_SETTINGS", "\u986F\u793A\u66F4\u591A\u8A2D\u5B9A"], ["MULTIPLE_LANGUAGES", "\u591A\u7A2E\u8A9E\u8A00"], ["MUTE", "\u975C\u97F3"], ["NOT_APPLICABLE", "\u4E0D\u9069\u7528"], ["OFF", "\u95DC\u9589"], ["ON", "\u958B\u555F"], ["PAUSE", "\u66AB\u505C"], ["PICTURE_IN_PICTURE", "\u5B50\u6BCD\u756B\u9762"], ["PLAY", "\u64AD\u653E"], ["PLAYBACK_RATE", "\u64AD\u653E\u901F\u5EA6"], ["QUALITY", "\u97F3\u8CEA"], ["RECENTER_VR", "\u91CD\u65B0\u7F6E\u4E2D"], ["REPLAY", "\u91CD\u64AD"], ["RESOLUTION", "\u89E3\u6790\u5EA6"], ["REWIND", "\u5012\u8F49"], ["SEEK", "\u641C\u5C0B"], ["SKIP_AD", "\u7565\u904E\u5EE3\u544A"], ["SKIP_TO_LIVE", "\u8DF3\u81F3\u5F53\u524D\u76F4\u64AD"], ["STATISTICS", "\u7D71\u8A08\u8CC7\u6599"], ["SUBTITLE_FORCED", "\u5F37\u5236\u986F\u793A"], ["SURROUND", "\u74B0\u5834\u97F3\u6548"], ["TOGGLE_STEREOSCOPIC", "\u5207\u63DB\u7ACB\u9AD4\u5F71\u50CF"], ["UNDETERMINED_LANGUAGE", "\u4E0D\u660E"], ["UNMUTE", "\u53D6\u6D88\u975C\u97F3"], ["UNRECOGNIZED_LANGUAGE", "\u7121\u6CD5\u8FA8\u8B58"], ["VOLUME", "\u97F3\u91CF"]]));
          a.Li(navigator.languages || []);
          return a;
        }
        S("shaka.ui.Controls", Z);
        Z.prototype.incrementRoll = Z.prototype.Ah;
        Z.prototype.incrementPitch = Z.prototype.yh;
        Z.prototype.incrementYaw = Z.prototype.Bh;
        Z.prototype.toggleStereoscopicMode = Z.prototype.Wd;
        Z.prototype.setVRFieldOfView = Z.prototype.vm;
        Z.prototype.getVRFieldOfView = Z.prototype.rl;
        Z.prototype.getVRNorth = Z.prototype.ul;
        Z.prototype.isPlayingVR = Z.prototype.Wb;
        Z.prototype.canPlayVR = Z.prototype.Lg;
        Z.prototype.hideUI = Z.prototype.bj;
        Z.prototype.showUI = Z.prototype.wm;
        Z.prototype.isOpaque = Z.prototype.Ca;
        Z.prototype.hideAdUI = Z.prototype.aj;
        Z.prototype.showAdUI = Z.prototype.Rj;
        Z.prototype.togglePiP = Z.prototype.Vc;
        Z.prototype.isPiPEnabled = Z.prototype.Id;
        Z.prototype.isPiPAllowed = Z.prototype.Df;
        Z.prototype.toggleFullScreen = Z.prototype.ng;
        Z.prototype.isFullScreenEnabled = Z.prototype.wc;
        Z.prototype.isFullScreenSupported = Z.prototype.se;
        Z.prototype.hideSettingsMenus = Z.prototype.Rc;
        Z.prototype.anySettingsMenusAreOpen = Z.prototype.Hc;
        Z.prototype.setLastTouchEventTime = Z.prototype.Mj;
        Z.prototype.getDisplayTime = Z.prototype.oh;
        Z.prototype.isCastAllowed = Z.prototype.Bl;
        Z.prototype.setSeeking = Z.prototype.ii;
        Z.prototype.isSeeking = Z.prototype.Hl;
        Z.prototype.getConfig = Z.prototype.Gk;
        Z.prototype.getClientSideAdContainer = Z.prototype.Fk;
        Z.prototype.getServerSideAdContainer = Z.prototype.il;
        Z.prototype.getControlsContainer = Z.prototype.Jk;
        Z.prototype.getLocalPlayer = Z.prototype.Sk;
        Z.prototype.getPlayer = Z.prototype.Vb;
        Z.prototype.getLocalVideo = Z.prototype.Tk;
        Z.prototype.getVideo = Z.prototype.Pc;
        Z.prototype.getVideoContainer = Z.prototype.wl;
        Z.prototype.getLocalization = Z.prototype.Uk;
        Z.prototype.getCastProxy = Z.prototype.Ck;
        Z.prototype.getAd = Z.prototype.getAd;
        Z.prototype.setEnabledNativeControls = Z.prototype.Lj;
        Z.prototype.setEnabledShakaControls = Z.prototype.di;
        Z.prototype.configure = Z.prototype.configure;
        Z.prototype.loadComplete = Z.prototype.Kl;
        Z.prototype.allowCast = Z.prototype.jk;
        Z.registerSeekBar = function(a) {
          UH = a;
        };
        Z.registerElement = CH;
        Z.prototype.destroy = Z.prototype.destroy;
        var DH = /* @__PURE__ */ new Map(), UH = new LG();
        function aI(a, b) {
          function c() {
            return bI(d2);
          }
          fG.call(this, a, b);
          var d2 = this;
          this.m = this.controls.g;
          this.l = this.controls.i;
          this.u = this.controls.l;
          this.j = [];
          cI(this);
          this.g = W("div");
          this.g.classList.add("shaka-overflow-menu");
          this.g.classList.add("shaka-no-propagation");
          this.g.classList.add("shaka-show-controls-on-mouse-over");
          this.g.classList.add("shaka-hidden");
          this.l.appendChild(this.g);
          dI(this);
          this.eventManager.o(this.localization, "locale-updated", function() {
            eI(d2);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            eI(d2);
          });
          this.eventManager.o(this.adManager, "ad-started", function() {
            d2.ad && d2.ad.isLinear() && kG(d2.h, false);
          });
          this.eventManager.o(this.adManager, "ad-stopped", function() {
            kG(d2.h, true);
          });
          this.eventManager.o(this.controls, "submenuopen", function() {
            kG(d2.g, false);
          });
          this.eventManager.o(this.g, "touchstart", function(e) {
            d2.controls.Mj(Date.now());
            e.stopPropagation();
          });
          this.eventManager.o(this.h, "click", function() {
            d2.controls.Ca() && fI(d2);
          });
          eI(this);
          this.ad && this.ad.isLinear() && kG(this.h, false);
          this.i = null;
          window7.ResizeObserver ? (this.i = new ResizeObserver(c), this.i.observe(this.controls.l)) : this.eventManager.o(window7, "resize", c);
        }
        ma(aI, fG);
        aI.prototype.release = function() {
          this.l = null;
          for (var a = t2(this.j), b = a.next(); !b.done; b = a.next()) b.value.release();
          this.j = [];
          this.i && (this.i.disconnect(), this.i = null);
          fG.prototype.release.call(this);
        };
        function gI(a, b) {
          hI.set(a, b);
        }
        function cI(a) {
          a.h = Oj();
          a.h.classList.add("shaka-overflow-menu-button");
          a.h.classList.add("shaka-no-propagation");
          a.h.classList.add("material-icons-round");
          a.h.classList.add("shaka-tooltip");
          a.h.textContent = "settings";
          var b = W("span");
          b.classList.add("shaka-overflow-quality-mark");
          b.style.display = "none";
          a.h.appendChild(b);
          a.parent.appendChild(a.h);
        }
        function dI(a) {
          for (var b = t2(a.m.overflowMenuButtons), c = b.next(); !c.done; c = b.next()) c = c.value, hI.get(c) ? (c = hI.get(c), a.j.push(c.create(a.g, a.controls))) : bb("Unrecognized overflow menu element requested:", c);
        }
        function fI(a) {
          if (a.controls.Hc()) a.controls.Rc();
          else {
            kG(a.g, true);
            rH(a.controls);
            var b = function(c) {
              return c.classList.contains("shaka-hidden") == 0;
            };
            ob(a.g.childNodes, b) && pb(a.g.childNodes, b)[0].focus();
            bI(a);
          }
        }
        function eI(a) {
          a.h.ariaLabel = a.localization.resolve("MORE_SETTINGS");
        }
        function bI(a) {
          var b = a.g.getBoundingClientRect(), c = window7.getComputedStyle(a.g), d2 = parseFloat(c.paddingTop);
          c = parseFloat(c.paddingBottom);
          var e = a.u.getBoundingClientRect();
          a.g.style.maxHeight = b.bottom - e.top - d2 - c + "px";
        }
        S("shaka.ui.OverflowMenu", aI);
        aI.registerElement = gI;
        function iI() {
        }
        iI.prototype.create = function(a, b) {
          return new aI(a, b);
        };
        CH("overflow_menu", new iI());
        var hI = /* @__PURE__ */ new Map();
        function jI(a, b) {
          function c(e) {
            return d2.i[e];
          }
          fG.call(this, a, b);
          var d2 = this;
          this.h = Oj();
          this.h.classList.add("shaka-ad-statistics-button");
          this.j = W("i");
          this.j.classList.add("material-icons-round");
          this.j.textContent = "insert_chart_outlined";
          this.h.appendChild(this.j);
          a = W("label");
          a.classList.add("shaka-overflow-button-label");
          a.classList.add("shaka-simple-overflow-button-label-inline");
          this.A = W("span");
          a.appendChild(this.A);
          this.m = W("span");
          this.m.classList.add("shaka-current-selection-span");
          a.appendChild(this.m);
          this.h.appendChild(a);
          this.parent.appendChild(this.h);
          this.g = W("div");
          this.g.classList.add("shaka-no-propagation");
          this.g.classList.add("shaka-show-controls-on-mouse-over");
          this.g.classList.add("shaka-ad-statistics-container");
          this.g.classList.add("shaka-hidden");
          this.controls.i.appendChild(this.g);
          this.D = [];
          this.i = this.adManager.getStats();
          kG(this.h, this.i.started > 0);
          this.u = /* @__PURE__ */ new Map();
          this.C = (/* @__PURE__ */ new Map()).set("loadTimes", function(e) {
            var f = 0;
            e = t2(d2.i[e]);
            for (var g = e.next(); !g.done; g = e.next()) f += parseFloat(g.value);
            return f;
          }).set("averageLoadTime", c).set("started", c).set("overlayAds", c).set("playedCompletely", c).set("skipped", c).set("errors", c);
          this.l = new Cf(function() {
            d2.i = d2.adManager.getStats();
            for (var e = t2(d2.D), f = e.next(); !f.done; f = e.next()) f = f.value, d2.u.get(f).textContent = d2.C.get(f)(f);
          });
          kI(this);
          lI(this);
          this.eventManager.o(this.localization, "locale-updated", function() {
            kI(d2);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            kI(d2);
          });
          this.eventManager.o(this.h, "click", function() {
            d2.controls.Ca() && (mI(d2), kI(d2));
          });
          this.eventManager.o(this.player, "loading", function() {
            kG(d2.h, false);
          });
          this.eventManager.o(this.adManager, "ad-started", function() {
            kG(d2.h, true);
          });
        }
        ma(jI, fG);
        function mI(a) {
          a.g.classList.contains("shaka-hidden") ? (a.j.textContent = "insert_chart", a.l.za(0.1), kG(a.g, true)) : (a.j.textContent = "insert_chart_outlined", a.l.stop(), kG(a.g, false));
        }
        function kI(a) {
          a.A.textContent = a.localization.resolve("AD_STATISTICS");
          a.h.ariaLabel = a.localization.resolve("AD_STATISTICS");
          a.m.textContent = a.localization.resolve(a.g.classList.contains("shaka-hidden") ? "OFF" : "ON");
        }
        function nI(a, b) {
          var c = W("div"), d2 = W("label");
          d2.textContent = b + ":";
          c.appendChild(d2);
          d2 = W("span");
          d2.textContent = a.C.get(b)(b);
          c.appendChild(d2);
          a.u.set(b, d2);
          return c;
        }
        function lI(a) {
          var b = W("div");
          b.classList.add("shaka-no-propagation");
          b.classList.add("shaka-statistics-close");
          var c = W("i");
          c.classList.add("material-icons");
          c.classList.add("notranslate");
          c.classList.add("material-icons-round");
          c.textContent = "close";
          b.appendChild(c);
          a.g.appendChild(b);
          a.eventManager.o(c, "click", function() {
            mI(a);
          });
          b = t2(a.controls.g.adStatisticsList);
          for (c = b.next(); !c.done; c = b.next()) c = c.value, c in a.i ? (a.g.appendChild(nI(a, c)), a.D.push(c)) : bb("Unrecognized ad statistic element:", c);
        }
        jI.prototype.release = function() {
          this.l.stop();
          this.l = null;
          fG.prototype.release.call(this);
        };
        S("shaka.ui.AdStatisticsButton", jI);
        function oI() {
        }
        oI.prototype.create = function(a, b) {
          return new jI(a, b);
        };
        gI("ad_statistics", new oI());
        pG("ad_statistics", new oI());
        function pI(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.g = Oj();
          this.g.classList.add("shaka-airplay-button");
          this.g.classList.add("shaka-tooltip");
          this.g.ariaPressed = "false";
          this.h = W("i");
          this.h.classList.add("material-icons-round");
          this.h.textContent = "airplay";
          this.g.appendChild(this.h);
          window7.WebKitPlaybackTargetAvailabilityEvent || this.g.classList.add("shaka-hidden");
          a = W("label");
          a.classList.add("shaka-overflow-button-label");
          a.classList.add("shaka-overflow-menu-only");
          this.j = W("span");
          a.appendChild(this.j);
          this.i = W("span");
          this.i.classList.add("shaka-current-selection-span");
          a.appendChild(this.i);
          this.g.appendChild(a);
          this.parent.appendChild(this.g);
          qI(this);
          rI(this);
          this.eventManager.o(this.localization, "locale-updated", function() {
            qI(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            qI(c);
          });
          this.eventManager.o(this.g, "click", function() {
            c.controls.Ca() && c.controls.Pc().webkitShowPlaybackTargetPicker();
          });
          a = this.controls.Pc();
          this.eventManager.o(a, "webkitplaybacktargetavailabilitychanged", function(d2) {
            var e = c.player.m == ar;
            kG(c.g, d2.availability == "available" && e);
          });
          this.eventManager.o(a, "webkitcurrentplaybacktargetiswirelesschanged", function() {
            rI(c);
          });
        }
        ma(pI, fG);
        function rI(a) {
          var b = a.controls.Pc();
          a.g.ariaPressed = b && b.webkitCurrentPlaybackTargetIsWireless ? "true" : "false";
        }
        function qI(a) {
          a.g.ariaLabel = a.localization.resolve("AIRPLAY");
          a.j.textContent = a.localization.resolve("AIRPLAY");
        }
        S("shaka.ui.AirPlayButton", pI);
        function sI() {
        }
        sI.prototype.create = function(a, b) {
          return new pI(a, b);
        };
        gI("airplay", new sI());
        CH("airplay", new sI());
        function tI(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.g = document.createElement("canvas");
          this.g.style.position = "absolute";
          this.g.style.top = "0";
          this.g.style.left = "0";
          this.g.style.pointerEvents = "none";
          this.parent.appendChild(this.g);
          uI(this);
          this.i = this.h = null;
          window7.ResizeObserver ? (this.i = new ResizeObserver(function() {
            return uI(c);
          }), this.i.observe(this.parent)) : window7.addEventListener("resize", function() {
            return uI(c);
          });
        }
        ma(tI, fG);
        function vI(a) {
          return (a = a.g.getContext("2d")) ? a : null;
        }
        function uI(a) {
          a.g.width = a.parent.offsetWidth;
          a.g.height = a.parent.offsetHeight;
        }
        tI.prototype.ig = function(a, b) {
          a = {
            type: "static",
            text: a,
            position: "top-right",
            color: "rgba(255, 255, 255, 0.7)",
            size: 20,
            alpha: 0.7,
            interval: 2e3,
            skip: 500,
            displayDuration: 2e3,
            transitionDuration: 0.5
          };
          b = Object.assign({}, a, b || a);
          if (b.type === "static") {
            if (a = vI(this)) {
              a.clearRect(0, 0, this.g.width, this.g.height);
              a.globalAlpha = b.alpha;
              a.fillStyle = b.color;
              a.font = b.size + "px Arial";
              var c = a.measureText(b.text);
              switch (b.position) {
                case "top-left":
                  c = 20;
                  var d2 = b.size + 20;
                  break;
                case "top-right":
                  c = this.g.width - c.width - 20;
                  d2 = b.size + 20;
                  break;
                case "bottom-left":
                  c = 20;
                  d2 = this.g.height - 20;
                  break;
                case "bottom-right":
                  c = this.g.width - c.width - 20;
                  d2 = this.g.height - 20;
                  break;
                default:
                  c = (this.g.width - c.width) / 2, d2 = (this.g.height + b.size) / 2;
              }
              a.fillText(b.text, c, d2);
            }
          } else b.type === "dynamic" && wI(this, b);
        };
        function wI(a, b) {
          function c() {
            if (a.h) {
              e.clearRect(0, 0, a.g.width, a.g.height);
              switch (h) {
                case "fadeIn":
                  g = Math.min(b.alpha, g + l);
                  g >= b.alpha && (h = "display");
                  break;
                case "display":
                  --k2 <= 0 && (h = "fadeOut");
                  break;
                case "fadeOut":
                  g = Math.max(0, g - l), g <= 0 && (h = "transition", f = d2(), k2 = Math.round(b.displayDuration * 60), h = "fadeIn");
              }
              g > 0 && (e.globalAlpha = g, e.fillStyle = b.color, e.font = b.size + "px Arial", e.fillText(b.text, f.left, f.top));
              a.h && (a.h = requestAnimationFrame(c));
            }
          }
          function d2() {
            e.font = b.size + "px Arial";
            var n = e.measureText(b.text).width, q = b.size;
            n = [{
              left: 20,
              top: q + 20
            }, {
              left: a.g.width - n - 20,
              top: q + 20
            }, {
              left: 20,
              top: a.g.height - 20
            }, {
              left: a.g.width - n - 20,
              top: a.g.height - 20
            }, {
              left: (a.g.width - n) / 2,
              top: (a.g.height + q) / 2
            }];
            q = n[m];
            m = (m + 1) % n.length;
            return q;
          }
          var e = a.g.getContext("2d"), f = {
            left: 0,
            top: 0
          }, g = 0, h = "fadeIn", k2 = Math.round(b.displayDuration * 60), l = 1 / (Math.round(b.transitionDuration * 60) / 2), m = 0;
          f = d2();
          a.h = requestAnimationFrame(c);
        }
        tI.prototype.$f = function() {
          this.h && (cancelAnimationFrame(this.h), this.h = null);
          var a = vI(this);
          a && a.clearRect(0, 0, this.g.width, this.g.height);
        };
        tI.prototype.release = function() {
          var a = this;
          this.g && this.g.parentNode && this.g.parentNode.removeChild(this.g);
          this.i ? (this.i.disconnect(), this.i = null) : window7.removeEventListener("resize", function() {
            return uI(a);
          });
          fG.prototype.release.call(this);
        };
        S("shaka.ui.Watermark", tI);
        tI.prototype.removeWatermark = tI.prototype.$f;
        tI.prototype.setTextWatermark = tI.prototype.ig;
        function xI(a, b, c, d2) {
          d2 = d2 === void 0 ? null : d2;
          this.j = a;
          this.l = b;
          this.h = yI(this);
          var e = "", f = false;
          b.dataset && b.dataset.shakaPlayerCastReceiverId ? (f = b.dataset, e = f.shakaPlayerCastReceiverId, f = f.shakaPlayerCastAndroidReceiverCompatible === "true") : c.dataset && c.dataset.shakaPlayerCastReceiverId && (f = c.dataset, e = f.shakaPlayerCastReceiverId, f = f.shakaPlayerCastAndroidReceiverCompatible === "true");
          e.length && (this.h.castReceiverAppId = e, this.h.castAndroidReceiverCompatible = f);
          b.dataset.shakaPlayerContainer = "";
          b.ui = this;
          this.Fh() && b.classList.add("shaka-mobile");
          this.g = new Z(a, b, c, d2, this.h);
          c.controls || a.ji(b);
          b.ui = this;
          c.ui = this;
          this.i = null;
        }
        p = xI.prototype;
        p.destroy = function(a) {
          a = a === void 0 ? false : a;
          var b = this;
          return P(function(c) {
            if (c.g == 1) return b.g ? G(c, b.g.destroy(a), 2) : c.B(2);
            if (c.g != 4) return b.g = null, b.j ? G(c, b.j.destroy(), 4) : c.B(4);
            b.j = null;
            b.i = null;
            H(c);
          });
        };
        p.Fh = function() {
          return Sb().Ka() == "MOBILE";
        };
        p.Gh = function() {
          return Sb().Ka() == "TV";
        };
        p.getConfiguration = function() {
          var a = yI(this);
          An(a, this.h, yI(this), {}, "");
          return a;
        };
        p.configure = function(a, b) {
          arguments.length == 2 && typeof a == "string" && (a = Bn(a, b));
          var c = Object.assign({}, this.h);
          An(c, a, yI(this), {}, "");
          var d2 = Dn(c, this.h);
          if (Object.keys(d2).length && (this.h = c, this.g.configure(this.h), this.g.dispatchEvent(new T("uiupdated")), (c = this.h.castSenderUrl) && this.h.castReceiverAppId && window7.chrome && !chrome.cast && !this.Gh())) {
            d2 = false;
            for (var e = t2(document.getElementsByTagName("script")), f = e.next(); !f.done; f = e.next()) if (f.value.src === c) {
              d2 = true;
              break;
            }
            d2 || (d2 = document.createElement("script"), d2.src = c, d2.defer = true, document.head.appendChild(d2));
          }
        };
        p.Ik = function() {
          return this.g;
        };
        p.tm = function(a) {
          this.g.di(a);
        };
        p.ig = function(a, b) {
          a && !this.i && this.l && this.g && (this.i = new tI(this.l, this.g));
          this.i && this.i.ig(a, b);
        };
        p.$f = function() {
          this.i && this.i.$f();
        };
        function yI(a) {
          var b = "play_pause skip_next mute volume time_and_duration spacer overflow_menu".split(" ");
          window7.chrome && b.push("cast");
          "remote" in HTMLMediaElement.prototype ? b.push("remote") : window7.WebKitPlaybackTargetAvailabilityEvent && b.push("airplay");
          b.push("fullscreen");
          b = {
            controlPanelElements: b,
            overflowMenuButtons: "captions quality language chapter picture_in_picture playback_rate recenter_vr toggle_stereoscopic save_video_frame".split(" "),
            statisticsList: "width height currentCodecs corruptedFrames decodedFrames droppedFrames drmTimeSeconds licenseTime liveLatency loadLatency bufferingTime manifestTimeSeconds estimatedBandwidth streamBandwidth maxSegmentDuration pauseTime playTime completionPercent manifestSizeBytes bytesDownloaded nonFatalErrorCount manifestPeriodCount manifestGapCount".split(" "),
            adStatisticsList: "loadTimes averageLoadTime started overlayAds playedCompletely skipped errors".split(" "),
            contextMenuElements: ["loop", "picture_in_picture", "save_video_frame", "statistics", "ad_statistics"],
            playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2],
            fastForwardRates: [2, 4, 8, 1],
            rewindRates: [-1, -2, -4, -8],
            addSeekBar: true,
            addBigPlayButton: false,
            customContextMenu: false,
            castReceiverAppId: "",
            castAndroidReceiverCompatible: false,
            clearBufferOnQualityChange: true,
            showUnbufferedStart: false,
            seekBarColors: {
              base: "rgba(255, 255, 255, 0.3)",
              buffered: "rgba(255, 255, 255, 0.54)",
              played: "rgb(255, 255, 255)",
              adBreaks: "rgb(255, 204, 0)"
            },
            volumeBarColors: {
              base: "rgba(255, 255, 255, 0.54)",
              level: "rgb(255, 255, 255)"
            },
            qualityMarks: {
              720: "",
              1080: "HD",
              1440: "2K",
              2160: "4K",
              4320: "8K"
            },
            trackLabelFormat: zI,
            textTrackLabelFormat: zI,
            fadeDelay: 0,
            closeMenusDelay: 2,
            doubleClickForFullscreen: true,
            singleClickForPlayAndPause: true,
            enableKeyboardPlaybackControls: true,
            enableFullscreenOnRotation: false,
            forceLandscapeOnFullscreen: false,
            enableTooltips: true,
            keyboardSeekDistance: 5,
            keyboardLargeSeekDistance: 60,
            fullScreenElement: a.l,
            preferDocumentPictureInPicture: true,
            showAudioChannelCountVariants: true,
            seekOnTaps: false,
            tapSeekDistance: 10,
            refreshTickInSeconds: 0.125,
            displayInVrMode: false,
            defaultVrProjectionMode: "equirectangular",
            setupMediaSession: true,
            preferVideoFullScreenInVisionOS: false,
            showAudioCodec: true,
            showVideoCodec: true,
            castSenderUrl: "/cast_sender.js"
          };
          if (a.Fh()) {
            b.addBigPlayButton = true;
            b.singleClickForPlayAndPause = false;
            b.seekOnTaps = true;
            b.enableTooltips = false;
            b.doubleClickForFullscreen = false;
            a = Sb();
            b.enableFullscreenOnRotation = a.Ga() !== "WEBKIT";
            b.forceLandscapeOnFullscreen = true;
            var c = ["play_pause", "skip_next", "volume"];
            b.controlPanelElements = b.controlPanelElements.filter(function(e) {
              return !c.includes(e);
            });
            b.overflowMenuButtons = b.overflowMenuButtons.filter(function(e) {
              return !c.includes(e);
            });
            b.contextMenuElements = b.contextMenuElements.filter(function(e) {
              return !c.includes(e);
            });
          } else if (a.Gh()) {
            b.addBigPlayButton = true;
            b.singleClickForPlayAndPause = false;
            b.enableTooltips = false;
            b.doubleClickForFullscreen = false;
            var d2 = "play_pause cast remote airplay volume save_video_frame".split(" ");
            b.controlPanelElements = b.controlPanelElements.filter(function(e) {
              return !d2.includes(e);
            });
            b.overflowMenuButtons = b.overflowMenuButtons.filter(function(e) {
              return !d2.includes(e);
            });
            b.contextMenuElements = b.contextMenuElements.filter(function(e) {
              return !d2.includes(e);
            });
          }
          return b;
        }
        function AI() {
          var a, b, c, d2, e, f, g, h, k2, l, m, n, q, r2, u, w, v, y, z, A, C, D;
          return P(function(F) {
            switch (F.g) {
              case 1:
                uC();
                if (!xq()) return BI("shaka-ui-load-failed", CI), F.return();
                a = document.querySelectorAll("[data-shaka-player-container]");
                b = document.querySelectorAll("[data-shaka-player]");
                c = document.querySelectorAll("[data-shaka-player-canvas]");
                d2 = document.querySelectorAll("[data-shaka-player-vr-canvas]");
                if (!b.length && !a.length) {
                  F.B(2);
                  break;
                }
                if (b.length && !a.length) {
                  e = t2(b);
                  for (f = e.next(); !f.done; f = e.next()) g = f.value, g.ui || (h = document.createElement("div"), k2 = g.parentElement, k2.replaceChild(h, g), h.appendChild(g), l = DI(h, c, d2), m = l.hj, n = l.fk, EI(h, g, m, n));
                  F.B(2);
                  break;
                }
                q = t2(a);
                r2 = q.next();
              case 4:
                if (r2.done) {
                  F.B(2);
                  break;
                }
                u = r2.value;
                if (u.ui) {
                  F.B(5);
                  break;
                }
                w = null;
                v = t2(b);
                for (y = v.next(); !y.done; y = v.next()) if (z = y.value, z.parentElement == u) {
                  w = z;
                  break;
                }
                w || (w = document.createElement("video"), w.setAttribute("playsinline", ""), u.appendChild(w));
                A = DI(u, c, d2);
                C = A.hj;
                D = A.fk;
                sa(F, 7);
                return G(F, EI(u, w, C, D), 9);
              case 9:
                ua(F, 5);
                break;
              case 7:
                return va(F), BI("shaka-ui-load-failed", FI), F.return();
              case 5:
                r2 = q.next();
                F.B(4);
                break;
              case 2:
                BI("shaka-ui-loaded"), H(F);
            }
          });
        }
        function BI(a, b) {
          var c = null;
          b != void 0 && (c = {
            reasonCode: b
          });
          a = new CustomEvent(a, {
            detail: c
          });
          document.dispatchEvent(a);
        }
        function EI(a, b, c, d2) {
          var e, f, g, h, k2, l, m, n, q, r2;
          return P(function(u) {
            switch (u.g) {
              case 1:
                e = new Y();
                f = new xI(e, a, b, d2 ? d2 : null);
                e.Gi(c);
                b.controls && f.g.Lj(true);
                g = [];
                if (h = b.getAttribute("src")) g.push(h), b.removeAttribute("src");
                k2 = t2(b.getElementsByTagName("source"));
                for (l = k2.next(); !l.done; l = k2.next()) m = l.value, g.push(m.src), b.removeChild(m);
                return G(u, e.bc(b), 2);
              case 2:
                n = t2(g), q = n.next();
              case 3:
                if (q.done) {
                  u.B(0);
                  break;
                }
                r2 = q.value;
                sa(u, 6);
                return G(u, f.g.Vb().load(r2), 8);
              case 8:
                u.B(0);
                break;
              case 6:
                va(u);
              case 4:
                q = n.next(), u.B(3);
            }
          });
        }
        function DI(a, b, c) {
          var d2 = null;
          b = t2(b);
          for (var e = b.next(); !e.done; e = b.next()) if (e = e.value, e.parentElement == a) {
            d2 = e;
            break;
          }
          d2 || (d2 = document.createElement("canvas"), d2.classList.add("shaka-canvas-container"), a.appendChild(d2));
          b = null;
          c = t2(c);
          for (e = c.next(); !e.done; e = c.next()) if (e = e.value, e.parentElement == a) {
            b = e;
            break;
          }
          return {
            hj: d2,
            fk: b
          };
        }
        S("shaka.ui.Overlay", xI);
        xI.prototype.removeWatermark = xI.prototype.$f;
        xI.prototype.setTextWatermark = xI.prototype.ig;
        xI.prototype.setEnabled = xI.prototype.tm;
        xI.prototype.getControls = xI.prototype.Ik;
        xI.prototype.configure = xI.prototype.configure;
        xI.prototype.getConfiguration = xI.prototype.getConfiguration;
        xI.prototype.isSmartTV = xI.prototype.Gh;
        xI.prototype.isMobile = xI.prototype.Fh;
        xI.prototype.destroy = xI.prototype.destroy;
        var zI = 0;
        xI.TrackLabelFormat = {
          LANGUAGE: zI,
          ROLE: 1,
          LANGUAGE_ROLE: 2,
          LABEL: 3
        };
        var CI = 0, FI = 1;
        xI.FailReasonCode = {
          NO_BROWSER_SUPPORT: CI,
          PLAYER_FAILED_TO_LOAD: FI
        };
        document.readyState == "complete" ? P(function(a) {
          if (a.g == 1) return G(a, Promise.resolve(), 2);
          AI();
          H(a);
        }) : window7.addEventListener("load", AI);
        function GI(a, b, c, d2, e, f, g, h) {
          function k2(J) {
            var K = "";
            J == "aac" ? K = "AAC" : J === "ac-3" ? K = "Dolby" : J === "ec-3" ? K = "DD+" : J === "ac-4" ? K = "Dolby AC-4" : J === "opus" ? K = "Opus" : J === "flac" && (K = "fLaC");
            return K ? " " + K : K;
          }
          function l(J) {
            var K = "";
            J >= 5 && (K = " " + e.resolve("SURROUND"));
            return K;
          }
          function m(J, K, L, M, N, O) {
            K = [J, K, O];
            g && M != null && K.push(M);
            h && n(J) && N && K.push(N);
            L && f == 3 && K.push(L);
            return K.join(": ");
          }
          function n(J) {
            return r2.has(J) && r2.get(J).size > 1;
          }
          for (var q = a.find(function(J) {
            return J.active == 1;
          }), r2 = /* @__PURE__ */ new Map(), u = t2(a), w = u.next(); !w.done; w = u.next()) w = w.value, w.codecs && (r2.has(w.language) || r2.set(w.language, /* @__PURE__ */ new Set()), r2.get(w.language).add(kf(w.codecs)));
          u = gG(b);
          Sj(b);
          b.appendChild(u);
          u = /* @__PURE__ */ new Set();
          q = q ? m(q.language, q.roles.join(", "), q.label, q.channelsCount, q.codecs && kf(q.codecs), q.spatialAudio) : "";
          a = t2(a);
          var v = a.next();
          for (w = {}; !v.done; w = {
            ac: void 0
          }, v = a.next()) {
            w.ac = v.value;
            v = w.ac.language;
            var y = w.ac.roles.join(", "), z = w.ac.label, A = w.ac.channelsCount, C = w.ac.codecs && kf(w.ac.codecs), D = w.ac.spatialAudio, F = m(v, y, z, A, C, D);
            if (!u.has(F)) {
              u.add(F);
              var B = Oj();
              B.addEventListener("click", /* @__PURE__ */ function(J) {
                return function() {
                  c(J.ac);
                };
              }(w));
              var E = W("span");
              B.appendChild(E);
              E.textContent = HI(v, e);
              var I = "";
              h && g && D && (C == "ec-3" || C == "ac-4") ? I += " Dolby Atmos" : (h && n(v) && (I += k2(C)), g && (I += l(A)));
              switch (f) {
                case zI:
                  E.textContent += I;
                  break;
                case 1:
                  E.textContent += I;
                  y ? E.textContent = y : (bb("Track #" + JSON.stringify(w.ac) + " does not have a role, but the UI is configured to only show role."), E.textContent = "?");
                  break;
                case 2:
                  E.textContent += I;
                  y && (E.textContent += ": " + y);
                  break;
                case 3:
                  z ? E.textContent = z : (bb("Track #" + JSON.stringify(w.ac) + " does not have a label, but the UI is configured to only show labels."), E.textContent = "?");
              }
              F == q && (B.appendChild(jG()), E.classList.add("shaka-chosen-item"), B.ariaSelected = "true", d2.textContent = E.textContent);
              b.appendChild(B);
            }
          }
        }
        function II(a, b, c, d2, e, f, g) {
          function h(A, C, D) {
            A = [A, C];
            D && g == 3 && A.push(D);
            return A.join(": ");
          }
          var k2 = a.find(function(A) {
            return A.active == 1;
          }), l = gG(b);
          Sj(b);
          b.appendChild(l);
          l = /* @__PURE__ */ new Set();
          k2 = k2 ? h(k2.language, k2.roles.join(", "), k2.label) : "";
          a = t2(a);
          for (var m = a.next(), n = {}; !m.done; n = {
            Wc: void 0
          }, m = a.next()) {
            n.Wc = m.value;
            m = n.Wc.language;
            var q = n.Wc.forced, r2 = f.resolve("SUBTITLE_FORCED"), u = n.Wc.roles.join(", "), w = n.Wc.label, v = h(m, u, w);
            if (!l.has(v)) {
              l.add(v);
              var y = Oj();
              y.addEventListener("click", /* @__PURE__ */ function(A) {
                return function() {
                  c(A.Wc);
                };
              }(n));
              var z = W("span");
              y.appendChild(z);
              z.textContent = HI(m, f);
              switch (g) {
                case zI:
                  q && (z.textContent += " (" + r2 + ")");
                  break;
                case 1:
                  u ? z.textContent = u : (bb("Track #" + n.Wc.id + " does not have a role, but the UI is configured to only show role."), z.textContent = "?");
                  q && (z.textContent += " (" + r2 + ")");
                  break;
                case 2:
                  u && (z.textContent += ": " + u);
                  q && (z.textContent += " (" + r2 + ")");
                  break;
                case 3:
                  w ? z.textContent = w : (bb("Track #" + n.Wc.id + " does not have a label, but the UI is configured to only show labels."), z.textContent = "?");
              }
              d2 && v == k2 && (y.appendChild(jG()), z.classList.add("shaka-chosen-item"), y.ariaSelected = "true", e.textContent = z.textContent);
              b.appendChild(y);
            }
          }
        }
        function HI(a, b) {
          if (!a && !b) return "";
          switch (a) {
            case "mul":
              return b.resolve("MULTIPLE_LANGUAGES");
            case "und":
              return b.resolve("UNDETERMINED_LANGUAGE");
            case "zxx":
              return b.resolve("NOT_APPLICABLE");
          }
          var c = Ec(a);
          return a in Lo ? Lo[a] : c in Lo ? Lo[c] + " (" + a + ")" : b.resolve("UNRECOGNIZED_LANGUAGE") + " (" + a + ")";
        }
        ;
        function JI(a, b, c) {
          function d2() {
            return KI(e);
          }
          fG.call(this, a, b);
          var e = this;
          this.m = this.controls.l;
          LI(this, c);
          MI(this);
          NI(this);
          this.eventManager.o(this.button, "click", function() {
            e.controls.Ca() && (e.menu.classList.contains("shaka-hidden") ? (e.controls.dispatchEvent(new T("submenuopen")), kG(e.menu, true), iG(e.menu), KI(e)) : kG(e.menu, false));
          });
          this.j = null;
          window7.ResizeObserver ? (this.j = new ResizeObserver(d2), this.j.observe(this.controls.l)) : this.eventManager.o(window7, "resize", d2);
        }
        ma(JI, fG);
        JI.prototype.release = function() {
          this.j && (this.j.disconnect(), this.j = null);
          fG.prototype.release.call(this);
        };
        function LI(a, b) {
          a.button = Oj();
          a.button.classList.add("shaka-overflow-button");
          a.icon = W("i");
          a.icon.classList.add("material-icons-round");
          a.icon.textContent = b;
          a.button.appendChild(a.icon);
          b = W("label");
          b.classList.add("shaka-overflow-button-label");
          b.classList.add("shaka-overflow-menu-only");
          b.classList.add("shaka-overflow-button-label-inline");
          a.nameSpan = W("span");
          b.appendChild(a.nameSpan);
          a.currentSelection = W("span");
          a.currentSelection.classList.add("shaka-current-selection-span");
          b.appendChild(a.currentSelection);
          a.button.appendChild(b);
          a.parent.appendChild(a.button);
        }
        function MI(a) {
          a.menu = W("div");
          a.menu.classList.add("shaka-no-propagation");
          a.menu.classList.add("shaka-show-controls-on-mouse-over");
          a.menu.classList.add("shaka-settings-menu");
          a.menu.classList.add("shaka-hidden");
          a.backButton = Oj();
          a.backButton.classList.add("shaka-back-to-overflow-button");
          a.menu.appendChild(a.backButton);
          a.eventManager.o(a.backButton, "click", function() {
            a.controls.Rc();
          });
          var b = W("i");
          b.classList.add("material-icons-round");
          b.textContent = "close";
          a.backButton.appendChild(b);
          a.backSpan = W("span");
          a.backButton.appendChild(a.backSpan);
          a.controls.i.appendChild(a.menu);
        }
        function NI(a) {
          a.parent.classList.contains("shaka-overflow-menu") && (a.backButton.firstChild.textContent = "navigate_before", a.eventManager.o(a.menu, "click", function() {
            function b(c) {
              return c.classList.contains("shaka-hidden") == 0;
            }
            kG(a.menu, false);
            kG(a.parent, true);
            ob(a.parent.childNodes, b) && pb(a.parent.childNodes, b)[0].focus();
            rH(a.controls);
            KI(a);
          }));
        }
        function KI(a) {
          var b = a.menu.getBoundingClientRect(), c = window7.getComputedStyle(a.menu), d2 = parseFloat(c.paddingTop);
          c = parseFloat(c.paddingBottom);
          var e = a.m.getBoundingClientRect();
          a.menu.style.maxHeight = b.bottom - e.top - d2 - c + "px";
        }
        S("shaka.ui.SettingsMenu", JI);
        function OI(a, b) {
          JI.call(this, a, b, "language");
          var c = this;
          this.button.classList.add("shaka-language-button");
          this.button.classList.add("shaka-tooltip-status");
          this.menu.classList.add("shaka-audio-languages");
          this.eventManager.o(this.localization, "locale-updated", function() {
            PI(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            PI(c);
          });
          this.eventManager.o(this.player, "loading", function() {
            QI(c);
          });
          this.eventManager.o(this.player, "loaded", function() {
            QI(c);
          });
          this.eventManager.o(this.player, "unloading", function() {
            QI(c);
          });
          this.eventManager.o(this.player, "audiotrackschanged", function() {
            QI(c);
          });
          PI(this);
          QI(this);
        }
        ma(OI, JI);
        function QI(a) {
          var b = a.player.getAudioTracks() || [];
          GI(b, a.menu, function(c) {
            a.player.Gj(c);
            a.player.configure("preferredAudioLanguage", c.language);
            c.label && a.player.configure("preferredAudioLabel", c.label);
            c.channelsCount && a.player.configure("preferredAudioChannelCount", c.channelsCount);
            a.player.configure("preferSpatialAudio", c.spatialAudio);
          }, a.currentSelection, a.localization, a.controls.g.trackLabelFormat, a.controls.g.showAudioChannelCountVariants, a.controls.g.showAudioCodec);
          iG(a.menu);
          a.controls.dispatchEvent(new T("languageselectionupdated"));
          a.button.setAttribute("shaka-status", a.currentSelection.innerText);
          kG(a.button, a.menu.getElementsByTagName("button").length > 2);
        }
        function PI(a) {
          a.backButton.ariaLabel = a.localization.resolve("BACK");
          a.button.ariaLabel = a.localization.resolve("LANGUAGE");
          a.nameSpan.textContent = a.localization.resolve("LANGUAGE");
          a.backSpan.textContent = a.localization.resolve("LANGUAGE");
        }
        S("shaka.ui.AudioLanguageSelection", OI);
        function RI() {
        }
        RI.prototype.create = function(a, b) {
          return new OI(a, b);
        };
        gI("language", new RI());
        CH("language", new RI());
        function SI(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.h = this.controls.F;
          this.g = Oj();
          this.g.classList.add("shaka-cast-button");
          this.g.classList.add("shaka-tooltip");
          this.g.ariaPressed = "false";
          this.i = W("i");
          this.i.classList.add("material-icons-round");
          this.i.textContent = "cast";
          this.g.appendChild(this.i);
          a = W("label");
          a.classList.add("shaka-overflow-button-label");
          a.classList.add("shaka-overflow-menu-only");
          a.classList.add("shaka-simple-overflow-button-label-inline");
          this.l = W("span");
          a.appendChild(this.l);
          this.j = W("span");
          this.j.classList.add("shaka-current-selection-span");
          a.appendChild(this.j);
          this.g.appendChild(a);
          this.parent.appendChild(this.g);
          TI(this);
          UI(this);
          this.eventManager.o(this.localization, "locale-updated", function() {
            TI(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            TI(c);
          });
          this.eventManager.o(this.g, "click", function() {
            c.controls.Ca() && VI(c);
          });
          this.eventManager.o(this.controls, "caststatuschanged", function() {
            UI(c);
          });
        }
        ma(SI, fG);
        function VI(a) {
          var b;
          P(function(c) {
            if (c.g == 1) {
              if (a.h.Qa()) return a.h.Vj(), c.B(0);
              sa(c, 3);
              a.g.disabled = true;
              return G(c, a.h.cast(), 5);
            }
            if (c.g != 3) return a.g.disabled = false, ua(c, 0);
            b = va(c);
            a.g.disabled = false;
            b.code != 8004 && a.controls.dispatchEvent(new T("error", (/* @__PURE__ */ new Map()).set("detail", b)));
            H(c);
          });
        }
        function UI(a) {
          var b = a.h.Kg() && a.controls.sa, c = a.h.Qa();
          kG(a.g, b);
          a.i.textContent = c ? "cast_connected" : "cast";
          b && (a.g.ariaPressed = c ? "true" : "false");
          WI(a);
        }
        function WI(a) {
          a.j.textContent = a.h.Qa() ? a.h.Yf() : a.localization.resolve("OFF");
        }
        function TI(a) {
          a.g.ariaLabel = a.localization.resolve("CAST");
          a.l.textContent = a.localization.resolve("CAST");
          WI(a);
        }
        S("shaka.ui.CastButton", SI);
        function XI() {
        }
        XI.prototype.create = function(a, b) {
          return new SI(a, b);
        };
        gI("cast", new XI());
        CH("cast", new XI());
        function YI(a, b) {
          JI.call(this, a, b, "bookmarks");
          var c = this;
          this.button.classList.add("shaka-chapter-button");
          this.menu.classList.add("shaka-chapters");
          this.button.classList.add("shaka-tooltip-status");
          this.g = [];
          this.h = "und";
          this.eventManager.o(this.localization, "locale-updated", function() {
            ZI(c);
            $I(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            ZI(c);
            $I(c);
          });
          this.eventManager.o(this.player, "unloading", function() {
            aJ(c);
            c.h = "und";
            c.g = [];
          });
          this.eventManager.o(this.player, "trackschanged", function() {
            $I(c);
          });
          ZI(this);
          $I(this);
        }
        ma(YI, JI);
        function ZI(a) {
          a.backButton.ariaLabel = a.localization.resolve("BACK");
          a.button.ariaLabel = a.localization.resolve("CHAPTERS");
          a.nameSpan.textContent = a.localization.resolve("CHAPTERS");
          a.backSpan.textContent = a.localization.resolve("CHAPTERS");
        }
        function aJ(a) {
          var b = gG(a.menu);
          Sj(a.menu);
          a.menu.appendChild(b);
          kG(a.button, false);
        }
        function $I(a) {
          var b, c, d2, e, f, g, h, k2, l, m, n, q, r2, u;
          P(function(w) {
            switch (w.g) {
              case 1:
                b = function(v, y) {
                  return !v && !y || v.id === y.id && v.title === y.title && v.startTime === y.startTime && v.endTime === y.endTime;
                }, c = "und", d2 = [], e = a.localization.g, f = t2(Array.from(e)), g = f.next();
              case 2:
                if (g.done) {
                  w.B(4);
                  break;
                }
                c = h = g.value;
                if (!a.player) {
                  w.B(5);
                  break;
                }
                return G(w, a.player.nh(c), 6);
              case 6:
                d2 = w.h || [];
              case 5:
                if (d2.length) {
                  w.B(4);
                  break;
                }
                g = f.next();
                w.B(2);
                break;
              case 4:
                if (d2.length) {
                  w.B(7);
                  break;
                }
                c = "und";
                if (!a.player) {
                  w.B(7);
                  break;
                }
                return G(w, a.player.nh(c), 9);
              case 9:
                d2 = w.h || [];
              case 7:
                k2 = c !== a.h;
                l = a.g.length !== d2.length || !a.g.some(function(v, y) {
                  y = d2.at(y);
                  return b(v, y) || d2.some(function(z) {
                    return b(v, z);
                  });
                });
                a.h = c;
                a.g = d2;
                if (!d2.length) aJ(a);
                else if (k2 || l) {
                  m = t2(a.g);
                  n = m.next();
                  for (q = {}; !n.done; q = {
                    Mg: void 0
                  }, n = m.next()) q.Mg = n.value, r2 = Oj(), u = W("span"), u.classList.add("shaka-chapter"), u.textContent = q.Mg.title, r2.appendChild(u), a.eventManager.o(r2, "click", /* @__PURE__ */ function(v) {
                    return function() {
                      a.controls.Ca() && (a.video.currentTime = v.Mg.startTime);
                    };
                  }(q)), a.menu.appendChild(r2);
                  kG(a.button, true);
                  iG(a.menu);
                }
                H(w);
            }
          });
        }
        S("shaka.ui.ChapterSelection", YI);
        function bJ() {
        }
        bJ.prototype.create = function(a, b) {
          return new YI(a, b);
        };
        gI("chapter", new bJ());
        CH("chapter", new bJ());
        function cJ(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.g = Oj();
          this.g.classList.add("material-icons-round");
          this.g.classList.add("shaka-fast-forward-button");
          this.g.classList.add("shaka-tooltip-status");
          this.g.setAttribute("shaka-status", "1x");
          this.g.textContent = "fast_forward";
          this.parent.appendChild(this.g);
          dJ(this);
          this.h = this.controls.g.fastForwardRates;
          this.eventManager.o(this.localization, "locale-updated", function() {
            dJ(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            dJ(c);
          });
          this.eventManager.o(this.g, "click", function() {
            if (c.controls.Ca() && c.video.duration) {
              var d2 = c.h.indexOf(c.player.Ya()) + 1;
              d2 = d2 != c.h.length ? c.h[d2] : c.h[0];
              c.video.paused && c.video.play();
              c.player.Xc(d2);
              c.g.setAttribute("shaka-status", d2 + "x");
            }
          });
          this.eventManager.o(this.player, "ratechange", function() {
            c.g.setAttribute("shaka-status", c.player.Ya() + "x");
          });
        }
        ma(cJ, fG);
        function dJ(a) {
          a.g.ariaLabel = a.localization.resolve("FAST_FORWARD");
        }
        S("shaka.ui.FastForwardButton", cJ);
        function eJ() {
        }
        eJ.prototype.create = function(a, b) {
          return new cJ(a, b);
        };
        CH("fast_forward", new eJ());
        function fJ(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.h = this.controls.m;
          this.g = Oj();
          this.g.classList.add("shaka-fullscreen-button");
          this.g.classList.add("material-icons-round");
          this.g.classList.add("shaka-tooltip");
          gJ(this);
          this.g.textContent = "fullscreen";
          this.parent.appendChild(this.g);
          hJ(this);
          this.eventManager.o(this.localization, "locale-updated", function() {
            hJ(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            hJ(c);
          });
          this.eventManager.o(this.g, "click", function() {
            return P(function(d2) {
              return c.controls.Ca() ? G(d2, c.controls.ng(), 0) : d2.return();
            });
          });
          this.eventManager.o(document, "fullscreenchange", function() {
            c.g.textContent = c.controls.wc() ? "fullscreen_exit" : "fullscreen";
            hJ(c);
          });
          this.eventManager.o(this.h, "loadedmetadata", function() {
            gJ(c);
          });
          this.eventManager.o(this.h, "loadeddata", function() {
            gJ(c);
          });
          this.eventManager.o(this.adManager, "ad-started", function() {
            gJ(c);
          });
          this.eventManager.o(this.adManager, "ad-stopped", function() {
            gJ(c);
          });
        }
        ma(fJ, fG);
        function gJ(a) {
          a.controls.se() ? a.g.classList.remove("shaka-hidden") : a.g.classList.add("shaka-hidden");
        }
        function hJ(a) {
          var b = a.controls.wc() ? "EXIT_FULL_SCREEN" : "FULL_SCREEN";
          a.g.ariaLabel = a.localization.resolve(b);
        }
        S("shaka.ui.FullscreenButton", fJ);
        function iJ() {
        }
        iJ.prototype.create = function(a, b) {
          return new fJ(a, b);
        };
        CH("fullscreen", new iJ());
        function jJ(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.g = Oj();
          this.g.classList.add("shaka-loop-button");
          this.g.classList.add("shaka-tooltip");
          this.i = W("i");
          this.i.classList.add("material-icons-round");
          this.i.textContent = "repeat";
          this.g.appendChild(this.i);
          a = W("label");
          a.classList.add("shaka-overflow-button-label");
          a.classList.add("shaka-overflow-menu-only");
          a.classList.add("shaka-simple-overflow-button-label-inline");
          this.l = W("span");
          this.l.textContent = this.localization.resolve("LOOP");
          a.appendChild(this.l);
          this.j = W("span");
          this.j.classList.add("shaka-current-selection-span");
          a.appendChild(this.j);
          this.g.appendChild(a);
          kJ(this);
          this.parent.appendChild(this.g);
          this.eventManager.o(this.localization, "locale-updated", function() {
            kJ(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            kJ(c);
          });
          this.eventManager.o(this.g, "click", function() {
            c.controls.Ca() && (c.video.loop = !c.video.loop, c.h.La(), c.h.za(1));
          });
          this.m = this.video.loop;
          this.h = new Cf(function() {
            c.m != c.video.loop && (kJ(c), c.m = c.video.loop);
          });
          this.h.za(1);
          this.eventManager.o(this.player, "unloading", function() {
            lJ(c);
          });
          this.eventManager.o(this.player, "loaded", function() {
            lJ(c);
          });
          this.eventManager.o(this.player, "manifestupdated", function() {
            lJ(c);
          });
          this.eventManager.o(this.video, "durationchange", function() {
            lJ(c);
          });
        }
        ma(jJ, fG);
        jJ.prototype.release = function() {
          this.h.stop();
          this.h = null;
          fG.prototype.release.call(this);
        };
        function kJ(a) {
          a.l.textContent = a.localization.resolve("LOOP");
          a.j.textContent = a.localization.resolve(a.video.loop ? "ON" : "OFF");
          a.i.textContent = a.video.loop ? "repeat_on" : "repeat";
          a.g.ariaLabel = a.localization.resolve(a.video.loop ? "EXIT_LOOP_MODE" : "ENTER_LOOP_MODE");
        }
        function lJ(a) {
          kG(a.g, !a.player.U());
        }
        S("shaka.ui.LoopButton", jJ);
        function mJ() {
        }
        mJ.prototype.create = function(a, b) {
          return new jJ(a, b);
        };
        gI("loop", new mJ());
        CH("loop", new mJ());
        pG("loop", new mJ());
        function nJ(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.g = Oj();
          this.g.classList.add("shaka-mute-button");
          this.g.classList.add("shaka-tooltip");
          this.h = W("i");
          this.h.classList.add("material-icons-round");
          this.h.textContent = "volume_up";
          this.g.appendChild(this.h);
          a = W("label");
          a.classList.add("shaka-overflow-button-label");
          a.classList.add("shaka-overflow-menu-only");
          this.i = W("span");
          this.i.textContent = this.localization.resolve("MUTE");
          a.appendChild(this.i);
          this.j = W("span");
          this.j.classList.add("shaka-current-selection-span");
          a.appendChild(this.j);
          this.g.appendChild(a);
          this.parent.appendChild(this.g);
          oJ(this);
          pJ(this);
          this.eventManager.o(this.localization, "locale-updated", function() {
            oJ(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            oJ(c);
          });
          this.eventManager.o(this.g, "click", function() {
            c.controls.Ca() && (c.ad && c.ad.isLinear() ? c.ad.setMuted(!c.ad.isMuted()) : c.video.muted || c.video.volume != 0 ? c.video.muted = !c.video.muted : c.video.volume = 1);
          });
          this.eventManager.o(this.video, "volumechange", function() {
            oJ(c);
            pJ(c);
          });
          this.eventManager.o(this.player, "loading", function() {
            oJ(c);
            pJ(c);
          });
          this.eventManager.o(this.player, "loaded", function() {
            qJ(c);
          });
          this.eventManager.o(this.player, "unloading", function() {
            qJ(c);
          });
          this.eventManager.o(this.player, "trackschanged", function() {
            qJ(c);
          });
          this.eventManager.o(this.controls, "caststatuschanged", function() {
            oJ(c);
            pJ(c);
          });
          this.eventManager.o(this.adManager, "ad-volume-changed", function() {
            oJ(c);
            pJ(c);
          });
          this.eventManager.o(this.adManager, "ad-muted", function() {
            oJ(c);
            pJ(c);
          });
          this.eventManager.o(this.adManager, "ad-started", function() {
            qJ(c);
          });
          this.eventManager.o(this.adManager, "ad-stopped", function() {
            c.ad = null;
            oJ(c);
            pJ(c);
            qJ(c);
          });
          qJ(this);
        }
        ma(nJ, fG);
        function oJ(a) {
          var b = a.ad ? a.ad.isMuted() ? "UNMUTE" : "MUTE" : a.video.muted || a.video.volume == 0 ? "UNMUTE" : "MUTE";
          a.g.ariaLabel = a.localization.resolve(b);
          a.i.textContent = a.localization.resolve(b);
        }
        function pJ(a) {
          var b = a.ad ? a.ad.isMuted() ? "volume_off" : "volume_up" : a.video.muted || a.video.volume == 0 ? "volume_off" : "volume_up";
          a.h.textContent = b;
        }
        function qJ(a) {
          var b = true;
          a.ad && a.ad.isLinear() ? b = true : a.player.Hh() && (b = false);
          kG(a.g, b);
        }
        S("shaka.ui.MuteButton", nJ);
        function rJ() {
        }
        rJ.prototype.create = function(a, b) {
          return new nJ(a, b);
        };
        gI("mute", new rJ());
        CH("mute", new rJ());
        pG("mute", new rJ());
        function sJ(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.l = this.controls.m;
          this.g = Oj();
          this.g.classList.add("shaka-pip-button");
          this.g.classList.add("shaka-tooltip");
          this.i = W("i");
          this.i.classList.add("material-icons-round");
          this.i.textContent = "picture_in_picture_alt";
          this.g.appendChild(this.i);
          a = W("label");
          a.classList.add("shaka-overflow-button-label");
          a.classList.add("shaka-overflow-menu-only");
          a.classList.add("shaka-simple-overflow-button-label-inline");
          this.j = W("span");
          this.j.textContent = this.localization.resolve("PICTURE_IN_PICTURE");
          a.appendChild(this.j);
          this.h = W("span");
          this.h.classList.add("shaka-current-selection-span");
          a.appendChild(this.h);
          this.g.appendChild(a);
          tJ(this);
          this.parent.appendChild(this.g);
          this.controls.Df() || kG(this.g, false);
          this.eventManager.o(this.localization, "locale-updated", function() {
            tJ(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            tJ(c);
          });
          this.eventManager.o(this.g, "click", function() {
            c.controls.Ca() && c.controls.Vc();
          });
          this.eventManager.o(this.l, "enterpictureinpicture", function() {
            uJ(c);
          });
          this.eventManager.o(this.l, "leavepictureinpicture", function() {
            vJ(c);
          });
          this.eventManager.o(this.controls, "caststatuschanged", function() {
            wJ(c);
          });
          this.eventManager.o(this.player, "trackschanged", function() {
            wJ(c);
          });
          "documentPictureInPicture" in window7 && this.eventManager.o(window7.documentPictureInPicture, "enter", function(d2) {
            uJ(c);
            c.eventManager.qa(d2.window, "pagehide", function() {
              vJ(c);
            });
          });
        }
        ma(sJ, fG);
        function uJ(a) {
          a.i.textContent = "branding_watermark";
          a.g.ariaLabel = a.localization.resolve("EXIT_PICTURE_IN_PICTURE");
          a.h.textContent = a.localization.resolve("ON");
        }
        function vJ(a) {
          a.i.textContent = "picture_in_picture_alt";
          a.g.ariaLabel = a.localization.resolve("ENTER_PICTURE_IN_PICTURE");
          a.h.textContent = a.localization.resolve("OFF");
        }
        function tJ(a) {
          a.j.textContent = a.localization.resolve("PICTURE_IN_PICTURE");
          var b = a.controls.Id();
          a.g.ariaLabel = a.localization.resolve(b ? "EXIT_PICTURE_IN_PICTURE" : "ENTER_PICTURE_IN_PICTURE");
          a.h.textContent = a.localization.resolve(b ? "ON" : "OFF");
        }
        function wJ(a) {
          P(function(b) {
            if (!a.controls.Df()) return kG(a.g, false), a.controls.Id() ? G(b, a.controls.Vc(), 0) : b.B(0);
            if (!a.player || !a.player.Hd()) return kG(a.g, true), b.B(0);
            kG(a.g, false);
            return a.controls.Id() ? G(b, a.controls.Vc(), 0) : b.B(0);
          });
        }
        S("shaka.ui.PipButton", sJ);
        function xJ() {
        }
        xJ.prototype.create = function(a, b) {
          return new sJ(a, b);
        };
        gI("picture_in_picture", new xJ());
        CH("picture_in_picture", new xJ());
        pG("picture_in_picture", new xJ());
        function yJ(a, b) {
          JI.call(this, a, b, "slow_motion_video");
          var c = this;
          this.button.classList.add("shaka-playbackrate-button");
          this.menu.classList.add("shaka-playback-rates");
          this.button.classList.add("shaka-tooltip-status");
          Array.from(a.classList).includes("shaka-overflow-menu") || (this.g = W("span"), this.g.classList.add("shaka-overflow-playback-rate-mark"), this.button.appendChild(this.g));
          this.eventManager.o(this.localization, "locale-updated", function() {
            zJ(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            zJ(c);
          });
          this.eventManager.o(this.player, "loaded", function() {
            AJ(c);
          });
          this.eventManager.o(this.player, "ratechange", function() {
            AJ(c);
          });
          zJ(this);
          BJ(this);
          AJ(this);
        }
        ma(yJ, JI);
        function zJ(a) {
          a.backButton.ariaLabel = a.localization.resolve("BACK");
          a.button.ariaLabel = a.localization.resolve("PLAYBACK_RATE");
          a.nameSpan.textContent = a.localization.resolve("PLAYBACK_RATE");
          a.backSpan.textContent = a.localization.resolve("PLAYBACK_RATE");
        }
        function AJ(a) {
          var b = a.player.Ya(), c = hG(a.menu, "material-icons-round shaka-chosen-item");
          if (c) {
            var d2 = c.parentElement;
            d2.removeAttribute("aria-selected");
            d2.getElementsByTagName("span")[0].classList.remove("shaka-chosen-item");
            d2.removeChild(c);
          }
          if (c = Array.from(a.menu.querySelectorAll("span")).find(function(e) {
            return e.textContent == b + "x";
          })) d2 = c.parentElement, d2.appendChild(jG()), d2.ariaSelected = "true", c.classList.add("shaka-chosen-item");
          a.currentSelection.textContent = b + "x";
          a.button.setAttribute("shaka-status", b + "x");
          a.g && (a.g.textContent = b + "x");
        }
        function BJ(a) {
          for (var b = t2(a.controls.g.playbackRates), c = b.next(), d2 = {}; !c.done; d2 = {
            Xf: void 0
          }, c = b.next()) {
            d2.Xf = c.value;
            c = Oj();
            var e = W("span");
            e.textContent = d2.Xf + "x";
            c.appendChild(e);
            a.eventManager.o(c, "click", /* @__PURE__ */ function(f) {
              return function() {
                f.Xf == a.video.defaultPlaybackRate ? a.player.zd() : a.player.Xc(f.Xf, false);
              };
            }(d2));
            a.menu.appendChild(c);
          }
          iG(a.menu);
        }
        S("shaka.ui.PlaybackRateSelection", yJ);
        function CJ() {
        }
        CJ.prototype.create = function(a, b) {
          return new yJ(a, b);
        };
        gI("playback_rate", new CJ());
        CH("playback_rate", new CJ());
        function DJ(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.g = Oj();
          this.g.classList.add("shaka-current-time");
          EJ(this, "0:00");
          this.parent.appendChild(this.g);
          this.eventManager.o(this.g, "click", function() {
            c.controls.Ca() && c.player.U() && (c.video.currentTime = c.player.ya().end);
          });
          this.eventManager.o(this.player, "loading", function() {
            kG(c.g, true);
          });
          this.eventManager.o(this.controls, "timeandseekrangeupdated", function() {
            var d2 = c.controls.S, e = c.controls.oh(), f = c.player.ya(), g = f.end - f.start;
            isFinite(g) ? c.player.U() ? (e = Math.max(0, Math.floor(f.end - e)), g = g >= 3600, e >= 1 || d2 ? (EJ(c, "- " + lG(e, g)), c.g.disabled = false) : (EJ(c, c.localization.resolve("LIVE")), c.g.disabled = true)) : (d2 = g >= 3600, e = lG(Math.max(0, e - f.start), d2), g && (e += " / " + lG(g, d2)), EJ(c, e), c.g.disabled = true) : (EJ(c, c.localization.resolve("LIVE")), c.g.disabled = true);
          });
          this.eventManager.o(this.player, "trackschanged", function() {
            c.player.U() && (c.g.ariaLabel = c.localization.resolve("SKIP_TO_LIVE"));
          });
          this.eventManager.o(this.adManager, "ad-started", function() {
            kG(c.g, !c.ad.isLinear());
          });
          this.eventManager.o(this.adManager, "ad-stopped", function() {
            kG(c.g, true);
          });
        }
        ma(DJ, fG);
        function EJ(a, b) {
          b != a.g.textContent && (a.g.textContent = b);
        }
        S("shaka.ui.PresentationTimeTracker", DJ);
        function FJ() {
        }
        FJ.prototype.create = function(a, b) {
          return new DJ(a, b);
        };
        CH("time_and_duration", new FJ());
        function GJ(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.g = Oj();
          this.g.classList.add("shaka-recenter-vr-button");
          this.g.classList.add("shaka-tooltip");
          this.g.ariaPressed = "false";
          this.h = W("i");
          this.h.classList.add("material-icons-round");
          this.h.textContent = "control_camera";
          this.g.appendChild(this.h);
          a = W("label");
          a.classList.add("shaka-overflow-button-label");
          a.classList.add("shaka-overflow-menu-only");
          this.j = W("span");
          a.appendChild(this.j);
          this.i = W("span");
          this.i.classList.add("shaka-current-selection-span");
          a.appendChild(this.i);
          this.g.appendChild(a);
          this.parent.appendChild(this.g);
          HJ(this);
          this.eventManager.o(this.localization, "locale-updated", function() {
            HJ(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            HJ(c);
          });
          var d2 = this.controls.D;
          this.eventManager.o(this.g, "click", function() {
            c.controls.Ca() && (d2.g ? iH(d2.g) : bb("Not playing VR content"));
          });
          this.eventManager.o(d2, "vrstatuschanged", function() {
            kG(c.g, c.controls.Wb());
          });
          kG(this.g, this.controls.Wb());
        }
        ma(GJ, fG);
        function HJ(a) {
          a.g.ariaLabel = a.localization.resolve("RECENTER_VR");
          a.j.textContent = a.localization.resolve("RECENTER_VR");
        }
        S("shaka.ui.RecenterVRButton", GJ);
        function IJ() {
        }
        IJ.prototype.create = function(a, b) {
          return new GJ(a, b);
        };
        gI("recenter_vr", new IJ());
        CH("recenter_vr", new IJ());
        function JJ(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.j = Sb().kg();
          this.g = Oj();
          this.g.classList.add("shaka-remote-button");
          this.g.classList.add("shaka-tooltip");
          this.g.ariaPressed = "false";
          this.i = W("i");
          this.i.classList.add("material-icons-round");
          this.i.textContent = this.j ? "airplay" : "cast";
          this.g.appendChild(this.i);
          a = W("label");
          a.classList.add("shaka-overflow-button-label");
          a.classList.add("shaka-overflow-menu-only");
          this.m = W("span");
          a.appendChild(this.m);
          this.l = W("span");
          this.l.classList.add("shaka-current-selection-span");
          a.appendChild(this.l);
          this.g.appendChild(a);
          this.parent.appendChild(this.g);
          this.h = -1;
          KJ(this);
          kG(this.g, false);
          this.video.remote ? (this.eventManager.o(this.localization, "locale-updated", function() {
            KJ(c);
          }), this.eventManager.o(this.localization, "locale-changed", function() {
            KJ(c);
          }), this.eventManager.o(this.controls, "caststatuschanged", function() {
            LJ(c);
          }), this.eventManager.o(this.g, "click", function() {
            c.controls.Ca() && c.video.remote.prompt().catch(function() {
            });
          }), this.eventManager.o(this.video.remote, "connect", function() {
            LJ(c);
            MJ(c);
          }), this.eventManager.o(this.video.remote, "connecting", function() {
            LJ(c);
            MJ(c);
          }), this.eventManager.o(this.video.remote, "disconnect", function() {
            LJ(c);
            MJ(c);
          }), this.eventManager.o(this.player, "loaded", function() {
            LJ(c);
          }), LJ(this, true), MJ(this)) : this.g.classList.add("shaka-hidden");
        }
        ma(JJ, fG);
        JJ.prototype.release = function() {
          this.video.remote && this.h != -1 && this.video.remote.cancelWatchAvailability(this.h).catch(function() {
          });
          fG.prototype.release.call(this);
        };
        function LJ(a, b) {
          b = b === void 0 ? false : b;
          var c, d2;
          P(function(e) {
            switch (e.g) {
              case 1:
                if (a.controls.F.Kg() && a.controls.sa || !a.video.remote) {
                  kG(a.g, false);
                  a.h != -1 && (a.video.remote.cancelWatchAvailability(a.h), a.h = -1);
                  e.B(0);
                  break;
                }
                if (a.video.remote.state == "disconnected" || b) {
                  c = function(f) {
                    if (a.player) {
                      var g = a.video.disableRemotePlayback, h = true;
                      Sb().kg() && a.player.m == Xq && a.player.rh() != "HLS" && (h = false);
                      kG(a.g, h && f && !g);
                    } else kG(a.g, false);
                  };
                  sa(e, 7);
                  if (a.h == -1) {
                    e.B(9);
                    break;
                  }
                  return G(e, a.video.remote.cancelWatchAvailability(a.h), 10);
                }
                kG(a.g, true);
                if (a.h == -1) {
                  e.B(0);
                  break;
                }
                return G(e, a.video.remote.cancelWatchAvailability(a.h), 6);
              case 6:
                a.h = -1;
                e.B(0);
                break;
              case 10:
                a.h = -1;
              case 9:
                ua(e, 8);
                break;
              case 7:
                va(e);
              case 8:
                return sa(e, 11), G(e, a.video.remote.watchAvailability(c), 13);
              case 13:
                d2 = e.h;
                a.h = d2;
                ua(e, 0);
                break;
              case 11:
                va(e), c(true), H(e);
            }
          });
        }
        function KJ(a) {
          var b = a.j ? a.localization.resolve("AIRPLAY") : a.localization.resolve("CAST");
          a.g.ariaLabel = b;
          a.m.textContent = b;
        }
        function MJ(a) {
          a.j || (a.i.textContent = a.video.remote.state == "disconnected" ? "cast" : "cast_connected");
        }
        S("shaka.ui.RemoteButton", JJ);
        function NJ() {
        }
        NJ.prototype.create = function(a, b) {
          return new JJ(a, b);
        };
        gI("remote", new NJ());
        CH("remote", new NJ());
        function XJ(a, b) {
          JI.call(this, a, b, "tune");
          var c = this;
          this.button.classList.add("shaka-resolution-button");
          this.button.classList.add("shaka-tooltip-status");
          this.menu.classList.add("shaka-resolutions");
          this.h = W("span");
          this.h.classList.add("shaka-current-auto-quality");
          this.h.style.display = "none";
          this.i = W("sup");
          this.i.classList.add("shaka-current-quality-mark");
          this.i.style.display = "none";
          Array.from(a.classList).includes("shaka-overflow-menu") ? this.parent.parentElement && (this.g = Rj(this.parent.parentElement)) : (this.g = W("span"), this.g.classList.add("shaka-overflow-playback-rate-mark"), this.button.appendChild(this.g));
          a = W("span");
          this.button.childNodes[1].appendChild(a);
          a.appendChild(this.currentSelection);
          a.appendChild(this.h);
          a.appendChild(this.i);
          this.eventManager.o(this.localization, "locale-updated", function() {
            YJ(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            YJ(c);
          });
          this.eventManager.o(this.player, "loading", function() {
            ZJ(c);
            $J(c);
          });
          this.eventManager.o(this.player, "loaded", function() {
            ZJ(c);
            $J(c);
          });
          this.eventManager.o(this.player, "unloading", function() {
            ZJ(c);
            $J(c);
          });
          this.eventManager.o(this.player, "variantchanged", function() {
            ZJ(c);
            $J(c);
          });
          this.eventManager.o(this.player, "trackschanged", function() {
            ZJ(c);
            $J(c);
          });
          this.eventManager.o(this.player, "abrstatuschanged", function() {
            ZJ(c);
            $J(c);
          });
          this.eventManager.o(this.player, "adaptation", function() {
            ZJ(c);
            $J(c);
          });
          ZJ(this);
        }
        ma(XJ, JI);
        function $J(a) {
          var b = a.player.getConfiguration().abr.enabled;
          if (a.player.Hd()) {
            a.i.textContent = "";
            a.i.style.display = "none";
            a.g && (a.g.textContent = "", a.g.style.display = "none");
            var c = a.player.rb() || [], d2 = c.find(function(e) {
              return e.active;
            });
            d2 && (b ? (a.h.textContent = d2.bandwidth ? aK(a, d2, c) : "Unknown", a.h.style.display = "") : a.h.style.display = "none");
          } else c = a.player.getVideoTracks() || [], (d2 = c.find(function(e) {
            return e.active;
          })) ? (b ? (a.h.textContent = d2.height && d2.width ? bK(a, d2, c) : d2.bandwidth ? Math.round(d2.bandwidth / 1e3) + " kbits/s" : "Unknown", a.h.style.display = "") : a.h.style.display = "none", b = cK(a, d2.width, d2.height), a.i.textContent = b, a.i.style.display = b !== "" ? "" : "none", a.g && (a.g.textContent = b, a.g.style.display = b !== "" ? "" : "none")) : a.g && (b = a.player.getStats(), b = cK(a, b.width, b.height), a.g.textContent = b, a.g.style.display = b !== "" ? "" : "none");
        }
        function cK(a, b, c) {
          if (!b || !c) return "";
          c > b && (c = t2([c, b]), b = c.next().value, c = c.next().value);
          b / c > 16 / 9 && (c = Math.round(b * 9 / 16));
          a = a.controls.g.qualityMarks;
          return c >= 8640 ? c + "p" : c >= 4320 ? a["4320"] : c >= 2160 ? a["2160"] : c >= 1440 ? a["1440"] : c >= 1080 ? a["1080"] : c >= 720 ? a["720"] : "";
        }
        function ZJ(a) {
          var b = gG(a.menu);
          Sj(a.menu);
          a.menu.appendChild(b);
          b = 0;
          b = a.player.Hd() ? dK(a) : eK(a);
          var c = Oj();
          c.classList.add("shaka-enable-abr-button");
          a.eventManager.o(c, "click", function() {
            a.player.configure({
              abr: {
                enabled: true
              }
            });
            ZJ(a);
          });
          a.l = W("span");
          a.l.textContent = a.localization.resolve("AUTO_QUALITY");
          c.appendChild(a.l);
          a.player.getConfiguration().abr.enabled && (c.ariaSelected = "true", c.appendChild(jG()), a.l.classList.add("shaka-chosen-item"), a.currentSelection.textContent = a.localization.resolve("AUTO_QUALITY"));
          a.button.setAttribute("shaka-status", a.currentSelection.textContent);
          a.menu.appendChild(c);
          iG(a.menu);
          a.controls.dispatchEvent(new T("resolutionselectionupdated"));
          YJ(a);
          kG(a.button, b > 0);
        }
        function dK(a) {
          var b = [];
          a.player.m == ar || a.player.Da() || (b = a.player.rb() || []);
          var c = b.find(function(k2) {
            return k2.active;
          });
          c && (b = b.filter(function(k2) {
            if (k2.language != c.language || a.controls.g.showAudioChannelCountVariants && k2.channelsCount && c.channelsCount && k2.channelsCount != c.channelsCount) return false;
            var l = a.controls.g.trackLabelFormat;
            return (l == 1 || l == 2) && JSON.stringify(k2.audioRoles) != JSON.stringify(c.audioRoles) || l == 3 && k2.label != c.label || !k2.bandwidth ? false : true;
          }));
          b = b.filter(function(k2, l) {
            return b.findIndex(function(m) {
              return m.bandwidth == k2.bandwidth;
            }) == l;
          });
          b.sort(function(k2, l) {
            return l.bandwidth - k2.bandwidth;
          });
          for (var d2 = a.player.getConfiguration().abr.enabled, e = t2(b), f = e.next(), g = {}; !f.done; g = {
            Ie: void 0
          }, f = e.next()) {
            g.Ie = f.value;
            f = Oj();
            f.classList.add("explicit-resolution");
            a.eventManager.o(f, "click", /* @__PURE__ */ function(k2) {
              return function() {
                var l = k2.Ie;
                a.player.configure({
                  abr: {
                    enabled: false
                  }
                });
                a.player.De(l, a.controls.g.clearBufferOnQualityChange);
              };
            }(g));
            var h = W("span");
            h.textContent = g.Ie.bandwidth ? aK(a, g.Ie, b) : "Unknown";
            f.appendChild(h);
            d2 || g.Ie != c || (f.ariaSelected = "true", f.appendChild(jG()), h.classList.add("shaka-chosen-item"), a.currentSelection.textContent = h.textContent);
            a.menu.appendChild(f);
          }
          return b.length;
        }
        function eK(a) {
          var b = a.player.getVideoTracks() || [], c = b.find(function(m) {
            return m.active;
          });
          b = b.filter(function(m, n) {
            return b.findIndex(function(q) {
              var r2 = q.height == m.height && q.bandwidth == m.bandwidth && q.frameRate == m.frameRate && q.hdr == m.hdr && q.videoLayout == m.videoLayout;
              r2 && a.controls.g.showVideoCodec && q.codecs && m.codecs && (r2 = kf(q.codecs) == kf(m.codecs));
              return r2;
            }) == n;
          });
          b.sort(function(m, n) {
            return n.height == m.height || m.height == null || n.height == null ? n.bandwidth - m.bandwidth : n.height - m.height;
          });
          for (var d2 = a.player.getConfiguration().abr.enabled, e = t2(b), f = e.next(), g = {}; !f.done; g = {
            nc: void 0
          }, f = e.next()) {
            g.nc = f.value;
            f = Oj();
            f.classList.add("explicit-resolution");
            a.eventManager.o(f, "click", /* @__PURE__ */ function(m) {
              return function() {
                var n = m.nc;
                a.player.configure({
                  abr: {
                    enabled: false
                  }
                });
                a.player.Hj(n, a.controls.g.clearBufferOnQualityChange);
              };
            }(g));
            var h = W("span");
            h.textContent = g.nc.height && g.nc.width ? bK(a, g.nc, b) : g.nc.bandwidth ? Math.round(g.nc.bandwidth / 1e3) + " kbits/s" : "Unknown";
            f.appendChild(h);
            var k2 = cK(a, g.nc.width, g.nc.height);
            if (k2 !== "") {
              var l = W("sup");
              l.classList.add("shaka-quality-mark");
              l.textContent = k2;
              f.appendChild(l);
            }
            d2 || g.nc != c || (f.ariaSelected = "true", f.appendChild(jG()), h.classList.add("shaka-chosen-item"), a.currentSelection.textContent = h.textContent);
            a.menu.appendChild(f);
          }
          return b.length;
        }
        function bK(a, b, c) {
          function d2(l, m) {
            return l != m && l.height == m.height && l.hdr == m.hdr && Math.round(l.frameRate || 0) == Math.round(m.frameRate || 0);
          }
          var e = b.height || 0, f = b.width || 0;
          e > f && (e = t2([e, f]), f = e.next().value, e = e.next().value);
          var g = e;
          f / e > 16 / 9 && (g = Math.round(f * 9 / 16));
          f = g + "p";
          e = /* @__PURE__ */ new Set();
          g = t2(c);
          for (var h = g.next(); !h.done; h = g.next()) h = h.value, h.frameRate && e.add(Math.round(h.frameRate));
          e.size > 1 && (e = b.frameRate) && (e >= 50 || e <= 20) && (f += Math.round(b.frameRate));
          if (b.hdr == "PQ" || b.hdr == "HLG") f += " HDR";
          (b.videoLayout || "").includes("CH-STEREO") && (f += " 3D");
          if (c.some(function(l) {
            return d2(b, l);
          }) && (c.some(function(l) {
            return d2(b, l) && l.bandwidth == b.bandwidth;
          }) || (f += " (" + Math.round(b.bandwidth / 1e3) + " kbits/s)"), a.controls.g.showVideoCodec)) {
            var k2 = function(l) {
              var m = "";
              l && (l = kf(l), m = l.startsWith("dovi-") ? "Dolby Vision" : l.toUpperCase());
              return m ? " " + m : m;
            };
            c.some(function(l) {
              return d2(b, l) && k2(l.codecs) != k2(b.codecs);
            }) && (f += k2(b.codecs));
          }
          return f;
        }
        function aK(a, b, c) {
          var d2 = Math.round(b.bandwidth / 1e3) + " kbits/s";
          if (a.controls.g.showAudioCodec) {
            var e = function(f) {
              var g = "";
              f && (g = kf(f).toUpperCase());
              return g ? " " + g : g;
            };
            c.some(function(f) {
              return e(f.codecs) != e(b.codecs);
            }) && (d2 += e(b.codecs));
          }
          return d2;
        }
        function YJ(a) {
          var b = a.player.Hd() ? "QUALITY" : "RESOLUTION";
          a.button.ariaLabel = a.localization.resolve(b);
          a.backButton.ariaLabel = a.localization.resolve(b);
          a.backSpan.textContent = a.localization.resolve(b);
          a.nameSpan.textContent = a.localization.resolve(b);
          a.l.textContent = a.localization.resolve("AUTO_QUALITY");
          a.player.getConfiguration().abr.enabled && (a.currentSelection.textContent = a.localization.resolve("AUTO_QUALITY"));
        }
        S("shaka.ui.ResolutionSelection", XJ);
        function fK() {
        }
        fK.prototype.create = function(a, b) {
          return new XJ(a, b);
        };
        gI("quality", new fK());
        CH("quality", new fK());
        function gK(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.g = Oj();
          this.g.classList.add("material-icons-round");
          this.g.classList.add("shaka-rewind-button");
          this.g.classList.add("shaka-tooltip-status");
          this.g.setAttribute("shaka-status", this.localization.resolve("OFF"));
          this.g.textContent = "fast_rewind";
          this.parent.appendChild(this.g);
          hK(this);
          this.h = this.controls.g.rewindRates;
          this.eventManager.o(this.localization, "locale-updated", function() {
            hK(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            hK(c);
          });
          this.eventManager.o(this.g, "click", function() {
            if (c.controls.Ca() && c.video.duration) {
              var d2 = c.h.indexOf(c.player.Ya()) + 1;
              d2 = d2 != c.h.length ? c.h[d2] : c.h[0];
              c.video.paused && c.video.play();
              c.player.Xc(d2);
              c.g.setAttribute("shaka-status", d2 + "x");
            }
          });
          this.eventManager.o(this.player, "ratechange", function() {
            c.g.setAttribute("shaka-status", c.player.Ya() + "x");
          });
        }
        ma(gK, fG);
        function hK(a) {
          a.g.ariaLabel = a.localization.resolve("REWIND");
        }
        S("shaka.ui.RewindButton", gK);
        function iK() {
        }
        iK.prototype.create = function(a, b) {
          return new gK(a, b);
        };
        CH("rewind", new iK());
        function jK(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.l = this.controls.F;
          this.g = Oj();
          this.g.classList.add("shaka-save.video-frame-button");
          this.g.classList.add("shaka-tooltip");
          this.h = W("i");
          this.h.classList.add("material-icons-round");
          this.h.textContent = "download";
          this.g.appendChild(this.h);
          a = W("label");
          a.classList.add("shaka-overflow-button-label");
          a.classList.add("shaka-overflow-menu-only");
          this.i = W("span");
          this.i.textContent = this.localization.resolve("DOWNLOAD_VIDEO_FRAME");
          a.appendChild(this.i);
          this.j = W("span");
          this.j.classList.add("shaka-current-selection-span");
          a.appendChild(this.j);
          this.g.appendChild(a);
          kK(this);
          this.parent.appendChild(this.g);
          this.eventManager.o(this.localization, "locale-updated", function() {
            kK(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            kK(c);
          });
          this.eventManager.o(this.g, "click", function() {
            var d2 = document.createElement("canvas"), e = d2.getContext("2d"), f = c.controls.m;
            d2.width = f.videoWidth;
            d2.height = f.videoHeight;
            e.drawImage(f, 0, 0, d2.width, d2.height);
            d2 = d2.toDataURL("image/png");
            e = document.createElement("a");
            e.href = d2;
            e.download = "videoframe_" + f.currentTime.toFixed(3) + ".png";
            e.click();
          });
          this.eventManager.o(this.controls.D, "vrstatuschanged", function() {
            lK(c);
          });
          this.eventManager.o(this.adManager, "ad-started", function() {
            lK(c);
          });
          this.eventManager.o(this.adManager, "ad-stopped", function() {
            lK(c);
          });
          this.eventManager.o(this.player, "unloading", function() {
            lK(c);
          });
          this.eventManager.o(this.player, "loaded", function() {
            lK(c);
          });
          this.eventManager.o(this.video, "play", function() {
            lK(c);
          });
          this.eventManager.o(this.video, "pause", function() {
            lK(c);
          });
          this.eventManager.o(this.video, "seeking", function() {
            lK(c);
          });
          this.eventManager.o(this.controls, "caststatuschanged", function() {
            lK(c);
          });
          lK(this);
        }
        ma(jK, fG);
        function lK(a) {
          var b = true;
          a.controls.Wb() && (b = false);
          b && a.l.Qa() && (b = false);
          b && (a.player.drmInfo() || a.player.Hd()) && (b = false);
          b && a.ad && (b = false);
          b && a.video.remote && a.video.remote.state != "disconnected" && (b = false);
          kG(a.g, b);
        }
        function kK(a) {
          a.g.ariaLabel = a.localization.resolve("DOWNLOAD_VIDEO_FRAME");
          a.i.textContent = a.localization.resolve("DOWNLOAD_VIDEO_FRAME");
        }
        S("shaka.ui.SaveVideoFrameButton", jK);
        function mK() {
        }
        mK.prototype.create = function(a, b) {
          return new jK(a, b);
        };
        gI("save_video_frame", new mK());
        pG("save_video_frame", new mK());
        function nK(a, b) {
          fG.call(this, a, b);
          var c = this;
          if (this.h = this.player.uh()) this.g = Oj(), this.g.classList.add("shaka-skip-next-button"), this.g.classList.add("material-icons-round"), this.g.classList.add("shaka-tooltip"), this.g.textContent = "skip_next", this.parent.appendChild(this.g), oK(this), pK(this), this.eventManager.o(this.localization, "locale-updated", function() {
            oK(c);
          }), this.eventManager.o(this.localization, "locale-changed", function() {
            oK(c);
          }), this.eventManager.o(this.g, "click", function() {
            c.controls.Ca() && c.h.playItem(c.h.getCurrentItemIndex() + 1);
          }), this.eventManager.o(this.h, "currentitemchanged", function() {
            pK(c);
          }), this.eventManager.o(this.h, "itemsinserted", function() {
            pK(c);
          }), this.eventManager.o(this.h, "itemsremoved", function() {
            pK(c);
          }), this.eventManager.o(this.player, "loading", function() {
            pK(c);
          });
        }
        ma(nK, fG);
        function oK(a) {
          a.g.ariaLabel = a.localization.resolve("SKIP_NEXT");
        }
        function pK(a) {
          var b = a.h.getItems().length;
          b = b > 1 && a.h.getCurrentItemIndex() + 1 < b;
          kG(a.g, b);
        }
        S("shaka.ui.SkipNextButton", nK);
        function qK() {
        }
        qK.prototype.create = function(a, b) {
          return new nK(a, b);
        };
        CH("skip_next", new qK());
        function rK(a, b) {
          rG.call(this, a, b);
          this.button.classList.add("shaka-small-play-button");
          this.button.classList.add("material-icons-round");
          this.button.classList.add("shaka-tooltip");
        }
        ma(rK, rG);
        S("shaka.ui.SmallPlayButton", rK);
        function sK() {
        }
        sK.prototype.create = function(a, b) {
          return new rK(a, b);
        };
        CH("play_pause", new sK());
        function tK(a, b) {
          fG.call(this, a, b);
          a = W("div");
          a.classList.add("shaka-spacer");
          a.ariaHidden = "true";
          this.parent.appendChild(a);
        }
        ma(tK, fG);
        S("shaka.ui.Spacer", tK);
        function uK() {
        }
        uK.prototype.create = function(a, b) {
          return new tK(a, b);
        };
        CH("spacer", new uK());
        function vK(a, b) {
          function c(m) {
            m = parseInt(l.g[m], 10);
            return m > 2e9 ? (m / 1e9).toFixed(2) + "GB" : m > 1e6 ? (m / 1e6).toFixed(2) + "MB" : m > 1e3 ? (m / 1e3).toFixed(2) + "KB" : m + "B";
          }
          function d2(m) {
            return l.g[m] + " (gaps)";
          }
          function e(m) {
            return lG(l.g[m], false) + " (m)";
          }
          function f(m) {
            return Math.round(l.g[m] / 1e3) + " (kbits/s)";
          }
          function g(m) {
            return l.g[m].toFixed(2) + " (s)";
          }
          function h(m) {
            return l.g[m] + " (frames)";
          }
          function k2(m) {
            return l.g[m] + " (px)";
          }
          fG.call(this, a, b);
          var l = this;
          this.i = Oj();
          this.i.classList.add("shaka-statistics-button");
          this.j = W("i");
          this.j.classList.add("material-icons-round");
          this.j.textContent = "insert_chart_outlined";
          this.i.appendChild(this.j);
          a = W("label");
          a.classList.add("shaka-overflow-button-label");
          a.classList.add("shaka-simple-overflow-button-label-inline");
          this.A = W("span");
          a.appendChild(this.A);
          this.m = W("span");
          this.m.classList.add("shaka-current-selection-span");
          a.appendChild(this.m);
          this.i.appendChild(a);
          this.parent.appendChild(this.i);
          this.h = W("div");
          this.h.classList.add("shaka-no-propagation");
          this.h.classList.add("shaka-show-controls-on-mouse-over");
          this.h.classList.add("shaka-statistics-container");
          this.h.classList.add("shaka-hidden");
          this.controls.i.appendChild(this.h);
          this.D = [];
          this.F = ["stateHistory", "switchHistory"];
          this.g = this.player.getStats();
          this.u = /* @__PURE__ */ new Map();
          this.C = (/* @__PURE__ */ new Map()).set("width", k2).set("height", k2).set("currentCodecs", function(m) {
            return l.g[m];
          }).set("completionPercent", function(m) {
            return l.g[m] + " (%)";
          }).set("bufferingTime", g).set("drmTimeSeconds", g).set("licenseTime", g).set("liveLatency", g).set("loadLatency", g).set("manifestTimeSeconds", g).set("estimatedBandwidth", f).set("streamBandwidth", f).set("maxSegmentDuration", g).set("pauseTime", e).set("playTime", e).set("corruptedFrames", h).set("decodedFrames", h).set("droppedFrames", h).set("stallsDetected", function(m) {
            return l.g[m] + " (stalls)";
          }).set("gapsJumped", d2).set("manifestSizeBytes", c).set("bytesDownloaded", c).set("nonFatalErrorCount", function(m) {
            return l.g[m] + " (errors)";
          }).set("manifestPeriodCount", function(m) {
            return l.g[m] + " (periods)";
          }).set("manifestGapCount", d2);
          this.l = new Cf(function() {
            l.g = l.player.getStats();
            for (var m = t2(l.D), n = m.next(); !n.done; n = m.next()) {
              var q = n.value;
              n = l.u.get(q);
              n.textContent = l.C.get(q)(q);
              n && n.parentElement && (q = l.g[q], typeof q == "string" ? kG(n.parentElement, q != "") : kG(n.parentElement, !isNaN(q)));
            }
          });
          wK(this);
          xK(this);
          this.eventManager.o(this.localization, "locale-updated", function() {
            wK(l);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            wK(l);
          });
          this.eventManager.o(this.i, "click", function() {
            yK(l);
            wK(l);
          });
        }
        ma(vK, fG);
        function yK(a) {
          a.h.classList.contains("shaka-hidden") ? (a.j.textContent = "insert_chart", a.l.za(0.1), kG(a.h, true)) : (a.j.textContent = "insert_chart_outlined", a.l.stop(), kG(a.h, false));
        }
        function wK(a) {
          a.A.textContent = a.localization.resolve("STATISTICS");
          a.i.ariaLabel = a.localization.resolve("STATISTICS");
          a.m.textContent = a.localization.resolve(a.h.classList.contains("shaka-hidden") ? "OFF" : "ON");
        }
        function zK(a, b) {
          var c = W("div"), d2 = W("label");
          d2.textContent = b + ":";
          c.appendChild(d2);
          d2 = W("span");
          d2.textContent = a.C.get(b)(b);
          c.appendChild(d2);
          a.u.set(b, d2);
          return c;
        }
        function xK(a) {
          var b = W("div");
          b.classList.add("shaka-no-propagation");
          b.classList.add("shaka-statistics-close");
          var c = W("i");
          c.classList.add("material-icons");
          c.classList.add("notranslate");
          c.classList.add("material-icons-round");
          c.textContent = "close";
          b.appendChild(c);
          a.h.appendChild(b);
          a.eventManager.o(c, "click", function() {
            yK(a);
          });
          b = t2(a.controls.g.statisticsList);
          for (c = b.next(); !c.done; c = b.next()) if (c = c.value, c in a.g && !a.F.includes(c)) {
            var d2 = zK(a, c);
            a.h.appendChild(d2);
            a.D.push(c);
          } else bb("Unrecognized statistic element:", c);
        }
        vK.prototype.release = function() {
          this.l.stop();
          this.l = null;
          fG.prototype.release.call(this);
        };
        S("shaka.ui.StatisticsButton", vK);
        function AK() {
        }
        AK.prototype.create = function(a, b) {
          return new vK(a, b);
        };
        gI("statistics", new AK());
        pG("statistics", new AK());
        function BK(a, b) {
          JI.call(this, a, b, "closed_caption");
          var c = this;
          this.button.classList.add("shaka-caption-button");
          this.button.classList.add("shaka-tooltip-status");
          this.menu.classList.add("shaka-text-languages");
          this.player && this.player.ld() ? this.button.ariaPressed = "true" : this.button.ariaPressed = "false";
          CK(this);
          this.eventManager.o(this.localization, "locale-updated", function() {
            DK(c);
            EK(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            DK(c);
            EK(c);
          });
          this.eventManager.o(this.player, "loading", function() {
            FK(c);
            EK(c);
          });
          this.eventManager.o(this.player, "loaded", function() {
            FK(c);
            EK(c);
          });
          this.eventManager.o(this.player, "unloading", function() {
            FK(c);
            EK(c);
          });
          this.eventManager.o(this.player, "texttrackvisibility", function() {
            FK(c);
            EK(c);
          });
          this.eventManager.o(this.player, "textchanged", function() {
            EK(c);
          });
          this.eventManager.o(this.player, "trackschanged", function() {
            EK(c);
          });
          FK(this);
          DK(this);
          EK(this);
        }
        ma(BK, JI);
        function CK(a) {
          var b = Oj();
          b.ariaSelected = "true";
          a.menu.appendChild(b);
          b.appendChild(jG());
          a.g = W("span");
          b.appendChild(a.g);
        }
        function FK(a) {
          a.player.ld() ? (a.icon.textContent = "closed_caption", a.button.ariaPressed = "true") : (a.icon.textContent = "closed_caption_disabled", a.button.ariaPressed = "false");
          a.controls.dispatchEvent(new T("captionselectionupdated"));
        }
        function EK(a) {
          var b = a.player.vc() || [];
          II(b, a.menu, function(d2) {
            return GK(a, d2);
          }, a.player.ld(), a.currentSelection, a.localization, a.controls.g.textTrackLabelFormat);
          var c = Oj();
          c.classList.add("shaka-turn-captions-off-button");
          a.eventManager.o(c, "click", function() {
            a.player.Fe(false);
            EK(a);
          });
          c.appendChild(a.g);
          a.menu.appendChild(c);
          a.player.ld() ? a.g.classList.remove("shaka-chosen-item") : (c.ariaSelected = "true", c.appendChild(jG()), a.g.classList.add("shaka-chosen-item"), a.currentSelection.textContent = a.localization.resolve("OFF"));
          a.button.setAttribute("shaka-status", a.currentSelection.textContent);
          iG(a.menu);
          a.controls.dispatchEvent(new T("captionselectionupdated"));
          kG(a.button, b.length > 0);
        }
        function GK(a, b) {
          return P(function(c) {
            if (c.g == 1) return a.player.fg(b), G(c, a.player.Fe(true), 2);
            a.player.configure("preferredTextLanguage", b.language);
            a.player.configure("preferForcedSubs", b.forced);
            H(c);
          });
        }
        function DK(a) {
          a.button.ariaLabel = a.localization.resolve("CAPTIONS");
          a.backButton.ariaLabel = a.localization.resolve("BACK");
          a.nameSpan.textContent = a.localization.resolve("CAPTIONS");
          a.backSpan.textContent = a.localization.resolve("CAPTIONS");
          a.g.textContent = a.localization.resolve("OFF");
        }
        S("shaka.ui.TextSelection", BK);
        function HK() {
        }
        HK.prototype.create = function(a, b) {
          return new BK(a, b);
        };
        gI("captions", new HK());
        CH("captions", new HK());
        function IK(a, b) {
          fG.call(this, a, b);
          var c = this;
          this.g = Oj();
          this.g.classList.add("shaka-toggle-stereoscopic-button");
          this.g.classList.add("shaka-tooltip");
          this.g.ariaPressed = "false";
          this.h = W("i");
          this.h.classList.add("material-icons-round");
          this.h.textContent = "3d_rotation";
          this.g.appendChild(this.h);
          a = W("label");
          a.classList.add("shaka-overflow-button-label");
          a.classList.add("shaka-overflow-menu-only");
          this.j = W("span");
          a.appendChild(this.j);
          this.i = W("span");
          this.i.classList.add("shaka-current-selection-span");
          a.appendChild(this.i);
          this.g.appendChild(a);
          this.parent.appendChild(this.g);
          JK(this);
          this.eventManager.o(this.localization, "locale-updated", function() {
            JK(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            JK(c);
          });
          var d2 = this.controls.D;
          this.eventManager.o(this.g, "click", function() {
            c.controls.Ca() && d2.Wd();
          });
          this.eventManager.o(d2, "vrstatuschanged", function() {
            kG(c.g, c.controls.Wb());
          });
          kG(this.g, this.controls.Wb());
        }
        ma(IK, fG);
        function JK(a) {
          a.g.ariaLabel = a.localization.resolve("TOGGLE_STEREOSCOPIC");
          a.j.textContent = a.localization.resolve("TOGGLE_STEREOSCOPIC");
        }
        S("shaka.ui.ToggleStereoscopicButton", IK);
        function KK() {
        }
        KK.prototype.create = function(a, b) {
          return new IK(a, b);
        };
        gI("toggle_stereoscopic", new KK());
        CH("toggle_stereoscopic", new KK());
        function LK(a, b) {
          zG.call(this, a, b, ["shaka-volume-bar-container"], ["shaka-volume-bar"]);
          var c = this;
          this.g = this.controls.g;
          this.setRange(0, 100);
          this.eventManager.o(this.video, "volumechange", function() {
            return MK(c);
          });
          this.eventManager.o(this.player, "loading", function() {
            return MK(c);
          });
          this.eventManager.o(this.player, "loaded", function() {
            return NK(c);
          });
          this.eventManager.o(this.player, "unloading", function() {
            return NK(c);
          });
          this.eventManager.o(this.player, "trackschanged", function() {
            return NK(c);
          });
          this.eventManager.o(this.controls, "caststatuschanged", function() {
            return MK(c);
          });
          this.eventManager.o(this.adManager, "ad-volume-changed", function() {
            return OK(c);
          });
          this.eventManager.o(this.adManager, "ad-muted", function() {
            return OK(c);
          });
          this.eventManager.o(this.adManager, "ad-started", function() {
            return NK(c);
          });
          this.eventManager.o(this.adManager, "ad-stopped", function() {
            NK(c);
            MK(c);
          });
          this.eventManager.o(this.localization, "locale-updated", function() {
            return PK(c);
          });
          this.eventManager.o(this.localization, "locale-changed", function() {
            return PK(c);
          });
          MK(this);
          PK(this);
          if (this.ad) this.onChange();
          NK(this);
        }
        ma(LK, zG);
        LK.prototype.onChange = function() {
          this.ad && this.ad.isLinear() ? this.ad.setVolume(this.getValue() / 100) : (this.video.volume = this.getValue() / 100, this.video.volume > 0 && (this.video.muted = false));
        };
        function MK(a) {
          a.video.muted ? a.setValue(0) : a.setValue(a.video.volume * 100);
          QK(a);
        }
        function OK(a) {
          var b = a.ad.getVolume();
          a.setValue(b * 100);
          QK(a);
        }
        function QK(a) {
          var b = a.g.volumeBarColors, c = ["to right"];
          c.push(b.level + a.getValue() + "%");
          c.push(b.base + a.getValue() + "%");
          c.push(b.base + "100%");
          a.container.style.background = "linear-gradient(" + c.join(",") + ")";
        }
        function PK(a) {
          a.bar.ariaLabel = a.localization.resolve("VOLUME");
        }
        function NK(a) {
          var b = true;
          a.ad && a.ad.isLinear() ? b = true : a.player.Hh() && (b = false);
          kG(a.container, b);
        }
        S("shaka.ui.VolumeBar", LK);
        function RK() {
        }
        RK.prototype.create = function(a, b) {
          return new LK(a, b);
        };
        CH("volume", new RK());
      }).call(exportTo, innerGlobal, innerGlobal, void 0);
      if (typeof exports != "undefined") for (var k in exportTo.shaka) exports[k] = exportTo.shaka[k];
      else if (typeof define == "function" && define.amd) define(function() {
        return exportTo.shaka;
      });
      else innerGlobal.shaka = exportTo.shaka;
    })();
  }
});

// node_modules/.pnpm/global@4.4.0/node_modules/global/window.js
var require_window = __commonJS({
  "node_modules/.pnpm/global@4.4.0/node_modules/global/window.js"(exports, module) {
    var win;
    if (typeof window !== "undefined") {
      win = window;
    } else if (typeof global !== "undefined") {
      win = global;
    } else if (typeof self !== "undefined") {
      win = self;
    } else {
      win = {};
    }
    module.exports = win;
  }
});

// node_modules/.pnpm/dom-walk@0.1.2/node_modules/dom-walk/index.js
var require_dom_walk = __commonJS({
  "node_modules/.pnpm/dom-walk@0.1.2/node_modules/dom-walk/index.js"(exports, module) {
    var slice = Array.prototype.slice;
    module.exports = iterativelyWalk;
    function iterativelyWalk(nodes, cb) {
      if (!("length" in nodes)) {
        nodes = [nodes];
      }
      nodes = slice.call(nodes);
      while (nodes.length) {
        var node = nodes.shift(), ret = cb(node);
        if (ret) {
          return ret;
        }
        if (node.childNodes && node.childNodes.length) {
          nodes = slice.call(node.childNodes).concat(nodes);
        }
      }
    }
  }
});

// node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/dom-comment.js
var require_dom_comment = __commonJS({
  "node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/dom-comment.js"(exports, module) {
    module.exports = Comment;
    function Comment(data, owner) {
      if (!(this instanceof Comment)) {
        return new Comment(data, owner);
      }
      this.data = data;
      this.nodeValue = data;
      this.length = data.length;
      this.ownerDocument = owner || null;
    }
    Comment.prototype.nodeType = 8;
    Comment.prototype.nodeName = "#comment";
    Comment.prototype.toString = function _Comment_toString() {
      return "[object Comment]";
    };
  }
});

// node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/dom-text.js
var require_dom_text = __commonJS({
  "node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/dom-text.js"(exports, module) {
    module.exports = DOMText;
    function DOMText(value, owner) {
      if (!(this instanceof DOMText)) {
        return new DOMText(value);
      }
      this.data = value || "";
      this.length = this.data.length;
      this.ownerDocument = owner || null;
    }
    DOMText.prototype.type = "DOMTextNode";
    DOMText.prototype.nodeType = 3;
    DOMText.prototype.nodeName = "#text";
    DOMText.prototype.toString = function _Text_toString() {
      return this.data;
    };
    DOMText.prototype.replaceData = function replaceData(index, length, value) {
      var current = this.data;
      var left = current.substring(0, index);
      var right = current.substring(index + length, current.length);
      this.data = left + value + right;
      this.length = this.data.length;
    };
  }
});

// node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/event/dispatch-event.js
var require_dispatch_event = __commonJS({
  "node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/event/dispatch-event.js"(exports, module) {
    module.exports = dispatchEvent;
    function dispatchEvent(ev) {
      var elem = this;
      var type2 = ev.type;
      if (!ev.target) {
        ev.target = elem;
      }
      if (!elem.listeners) {
        elem.listeners = {};
      }
      var listeners = elem.listeners[type2];
      if (listeners) {
        return listeners.forEach(function(listener) {
          ev.currentTarget = elem;
          if (typeof listener === "function") {
            listener(ev);
          } else {
            listener.handleEvent(ev);
          }
        });
      }
      if (elem.parentNode) {
        elem.parentNode.dispatchEvent(ev);
      }
    }
  }
});

// node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/event/add-event-listener.js
var require_add_event_listener = __commonJS({
  "node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/event/add-event-listener.js"(exports, module) {
    module.exports = addEventListener2;
    function addEventListener2(type2, listener) {
      var elem = this;
      if (!elem.listeners) {
        elem.listeners = {};
      }
      if (!elem.listeners[type2]) {
        elem.listeners[type2] = [];
      }
      if (elem.listeners[type2].indexOf(listener) === -1) {
        elem.listeners[type2].push(listener);
      }
    }
  }
});

// node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/event/remove-event-listener.js
var require_remove_event_listener = __commonJS({
  "node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/event/remove-event-listener.js"(exports, module) {
    module.exports = removeEventListener2;
    function removeEventListener2(type2, listener) {
      var elem = this;
      if (!elem.listeners) {
        return;
      }
      if (!elem.listeners[type2]) {
        return;
      }
      var list = elem.listeners[type2];
      var index = list.indexOf(listener);
      if (index !== -1) {
        list.splice(index, 1);
      }
    }
  }
});

// node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/serialize.js
var require_serialize = __commonJS({
  "node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/serialize.js"(exports, module) {
    module.exports = serializeNode;
    var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"];
    function serializeNode(node) {
      switch (node.nodeType) {
        case 3:
          return escapeText(node.data);
        case 8:
          return "<!--" + node.data + "-->";
        default:
          return serializeElement(node);
      }
    }
    function serializeElement(elem) {
      var strings = [];
      var tagname = elem.tagName;
      if (elem.namespaceURI === "http://www.w3.org/1999/xhtml") {
        tagname = tagname.toLowerCase();
      }
      strings.push("<" + tagname + properties(elem) + datasetify(elem));
      if (voidElements.indexOf(tagname) > -1) {
        strings.push(" />");
      } else {
        strings.push(">");
        if (elem.childNodes.length) {
          strings.push.apply(strings, elem.childNodes.map(serializeNode));
        } else if (elem.textContent || elem.innerText) {
          strings.push(escapeText(elem.textContent || elem.innerText));
        } else if (elem.innerHTML) {
          strings.push(elem.innerHTML);
        }
        strings.push("</" + tagname + ">");
      }
      return strings.join("");
    }
    function isProperty(elem, key) {
      var type2 = typeof elem[key];
      if (key === "style" && Object.keys(elem.style).length > 0) {
        return true;
      }
      return elem.hasOwnProperty(key) && (type2 === "string" || type2 === "boolean" || type2 === "number") && key !== "nodeName" && key !== "className" && key !== "tagName" && key !== "textContent" && key !== "innerText" && key !== "namespaceURI" && key !== "innerHTML";
    }
    function stylify(styles) {
      if (typeof styles === "string") return styles;
      var attr = "";
      Object.keys(styles).forEach(function(key) {
        var value = styles[key];
        key = key.replace(/[A-Z]/g, function(c) {
          return "-" + c.toLowerCase();
        });
        attr += key + ":" + value + ";";
      });
      return attr;
    }
    function datasetify(elem) {
      var ds = elem.dataset;
      var props = [];
      for (var key in ds) {
        props.push({
          name: "data-" + key,
          value: ds[key]
        });
      }
      return props.length ? stringify2(props) : "";
    }
    function stringify2(list) {
      var attributes = [];
      list.forEach(function(tuple) {
        var name = tuple.name;
        var value = tuple.value;
        if (name === "style") {
          value = stylify(value);
        }
        attributes.push(name + '="' + escapeAttributeValue(value) + '"');
      });
      return attributes.length ? " " + attributes.join(" ") : "";
    }
    function properties(elem) {
      var props = [];
      for (var key in elem) {
        if (isProperty(elem, key)) {
          props.push({
            name: key,
            value: elem[key]
          });
        }
      }
      for (var ns in elem._attributes) {
        for (var attribute in elem._attributes[ns]) {
          var prop = elem._attributes[ns][attribute];
          var name = (prop.prefix ? prop.prefix + ":" : "") + attribute;
          props.push({
            name,
            value: prop.value
          });
        }
      }
      if (elem.className) {
        props.push({
          name: "class",
          value: elem.className
        });
      }
      return props.length ? stringify2(props) : "";
    }
    function escapeText(s) {
      var str = "";
      if (typeof s === "string") {
        str = s;
      } else if (s) {
        str = s.toString();
      }
      return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    }
    function escapeAttributeValue(str) {
      return escapeText(str).replace(/"/g, "&quot;");
    }
  }
});

// node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/dom-element.js
var require_dom_element = __commonJS({
  "node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/dom-element.js"(exports, module) {
    var domWalk = require_dom_walk();
    var dispatchEvent = require_dispatch_event();
    var addEventListener2 = require_add_event_listener();
    var removeEventListener2 = require_remove_event_listener();
    var serializeNode = require_serialize();
    var htmlns = "http://www.w3.org/1999/xhtml";
    module.exports = DOMElement;
    function DOMElement(tagName, owner, namespace) {
      if (!(this instanceof DOMElement)) {
        return new DOMElement(tagName);
      }
      var ns = namespace === void 0 ? htmlns : namespace || null;
      this.tagName = ns === htmlns ? String(tagName).toUpperCase() : tagName;
      this.nodeName = this.tagName;
      this.className = "";
      this.dataset = {};
      this.childNodes = [];
      this.parentNode = null;
      this.style = {};
      this.ownerDocument = owner || null;
      this.namespaceURI = ns;
      this._attributes = {};
      if (this.tagName === "INPUT") {
        this.type = "text";
      }
    }
    DOMElement.prototype.type = "DOMElement";
    DOMElement.prototype.nodeType = 1;
    DOMElement.prototype.appendChild = function _Element_appendChild(child) {
      if (child.parentNode) {
        child.parentNode.removeChild(child);
      }
      this.childNodes.push(child);
      child.parentNode = this;
      return child;
    };
    DOMElement.prototype.replaceChild = function _Element_replaceChild(elem, needle) {
      if (elem.parentNode) {
        elem.parentNode.removeChild(elem);
      }
      var index = this.childNodes.indexOf(needle);
      needle.parentNode = null;
      this.childNodes[index] = elem;
      elem.parentNode = this;
      return needle;
    };
    DOMElement.prototype.removeChild = function _Element_removeChild(elem) {
      var index = this.childNodes.indexOf(elem);
      this.childNodes.splice(index, 1);
      elem.parentNode = null;
      return elem;
    };
    DOMElement.prototype.insertBefore = function _Element_insertBefore(elem, needle) {
      if (elem.parentNode) {
        elem.parentNode.removeChild(elem);
      }
      var index = needle === null || needle === void 0 ? -1 : this.childNodes.indexOf(needle);
      if (index > -1) {
        this.childNodes.splice(index, 0, elem);
      } else {
        this.childNodes.push(elem);
      }
      elem.parentNode = this;
      return elem;
    };
    DOMElement.prototype.setAttributeNS = function _Element_setAttributeNS(namespace, name, value) {
      var prefix = null;
      var localName = name;
      var colonPosition = name.indexOf(":");
      if (colonPosition > -1) {
        prefix = name.substr(0, colonPosition);
        localName = name.substr(colonPosition + 1);
      }
      if (this.tagName === "INPUT" && name === "type") {
        this.type = value;
      } else {
        var attributes = this._attributes[namespace] || (this._attributes[namespace] = {});
        attributes[localName] = {
          value,
          prefix
        };
      }
    };
    DOMElement.prototype.getAttributeNS = function _Element_getAttributeNS(namespace, name) {
      var attributes = this._attributes[namespace];
      var value = attributes && attributes[name] && attributes[name].value;
      if (this.tagName === "INPUT" && name === "type") {
        return this.type;
      }
      if (typeof value !== "string") {
        return null;
      }
      return value;
    };
    DOMElement.prototype.removeAttributeNS = function _Element_removeAttributeNS(namespace, name) {
      var attributes = this._attributes[namespace];
      if (attributes) {
        delete attributes[name];
      }
    };
    DOMElement.prototype.hasAttributeNS = function _Element_hasAttributeNS(namespace, name) {
      var attributes = this._attributes[namespace];
      return !!attributes && name in attributes;
    };
    DOMElement.prototype.setAttribute = function _Element_setAttribute(name, value) {
      return this.setAttributeNS(null, name, value);
    };
    DOMElement.prototype.getAttribute = function _Element_getAttribute(name) {
      return this.getAttributeNS(null, name);
    };
    DOMElement.prototype.removeAttribute = function _Element_removeAttribute(name) {
      return this.removeAttributeNS(null, name);
    };
    DOMElement.prototype.hasAttribute = function _Element_hasAttribute(name) {
      return this.hasAttributeNS(null, name);
    };
    DOMElement.prototype.removeEventListener = removeEventListener2;
    DOMElement.prototype.addEventListener = addEventListener2;
    DOMElement.prototype.dispatchEvent = dispatchEvent;
    DOMElement.prototype.focus = function _Element_focus() {
      return void 0;
    };
    DOMElement.prototype.toString = function _Element_toString() {
      return serializeNode(this);
    };
    DOMElement.prototype.getElementsByClassName = function _Element_getElementsByClassName(classNames) {
      var classes = classNames.split(" ");
      var elems = [];
      domWalk(this, function(node) {
        if (node.nodeType === 1) {
          var nodeClassName = node.className || "";
          var nodeClasses = nodeClassName.split(" ");
          if (classes.every(function(item) {
            return nodeClasses.indexOf(item) !== -1;
          })) {
            elems.push(node);
          }
        }
      });
      return elems;
    };
    DOMElement.prototype.getElementsByTagName = function _Element_getElementsByTagName(tagName) {
      tagName = tagName.toLowerCase();
      var elems = [];
      domWalk(this.childNodes, function(node) {
        if (node.nodeType === 1 && (tagName === "*" || node.tagName.toLowerCase() === tagName)) {
          elems.push(node);
        }
      });
      return elems;
    };
    DOMElement.prototype.contains = function _Element_contains(element) {
      return domWalk(this, function(node) {
        return element === node;
      }) || false;
    };
  }
});

// node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/dom-fragment.js
var require_dom_fragment = __commonJS({
  "node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/dom-fragment.js"(exports, module) {
    var DOMElement = require_dom_element();
    module.exports = DocumentFragment;
    function DocumentFragment(owner) {
      if (!(this instanceof DocumentFragment)) {
        return new DocumentFragment();
      }
      this.childNodes = [];
      this.parentNode = null;
      this.ownerDocument = owner || null;
    }
    DocumentFragment.prototype.type = "DocumentFragment";
    DocumentFragment.prototype.nodeType = 11;
    DocumentFragment.prototype.nodeName = "#document-fragment";
    DocumentFragment.prototype.appendChild = DOMElement.prototype.appendChild;
    DocumentFragment.prototype.replaceChild = DOMElement.prototype.replaceChild;
    DocumentFragment.prototype.removeChild = DOMElement.prototype.removeChild;
    DocumentFragment.prototype.toString = function _DocumentFragment_toString() {
      return this.childNodes.map(function(node) {
        return String(node);
      }).join("");
    };
  }
});

// node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/event.js
var require_event = __commonJS({
  "node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/event.js"(exports, module) {
    module.exports = Event2;
    function Event2(family) {
    }
    Event2.prototype.initEvent = function _Event_initEvent(type2, bubbles, cancelable) {
      this.type = type2;
      this.bubbles = bubbles;
      this.cancelable = cancelable;
    };
    Event2.prototype.preventDefault = function _Event_preventDefault() {
    };
  }
});

// node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/document.js
var require_document = __commonJS({
  "node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/document.js"(exports, module) {
    var domWalk = require_dom_walk();
    var Comment = require_dom_comment();
    var DOMText = require_dom_text();
    var DOMElement = require_dom_element();
    var DocumentFragment = require_dom_fragment();
    var Event2 = require_event();
    var dispatchEvent = require_dispatch_event();
    var addEventListener2 = require_add_event_listener();
    var removeEventListener2 = require_remove_event_listener();
    module.exports = Document2;
    function Document2() {
      if (!(this instanceof Document2)) {
        return new Document2();
      }
      this.head = this.createElement("head");
      this.body = this.createElement("body");
      this.documentElement = this.createElement("html");
      this.documentElement.appendChild(this.head);
      this.documentElement.appendChild(this.body);
      this.childNodes = [this.documentElement];
      this.nodeType = 9;
    }
    var proto = Document2.prototype;
    proto.createTextNode = function createTextNode(value) {
      return new DOMText(value, this);
    };
    proto.createElementNS = function createElementNS(namespace, tagName) {
      var ns = namespace === null ? null : String(namespace);
      return new DOMElement(tagName, this, ns);
    };
    proto.createElement = function createElement(tagName) {
      return new DOMElement(tagName, this);
    };
    proto.createDocumentFragment = function createDocumentFragment() {
      return new DocumentFragment(this);
    };
    proto.createEvent = function createEvent(family) {
      return new Event2(family);
    };
    proto.createComment = function createComment(data) {
      return new Comment(data, this);
    };
    proto.getElementById = function getElementById(id) {
      id = String(id);
      var result = domWalk(this.childNodes, function(node) {
        if (String(node.id) === id) {
          return node;
        }
      });
      return result || null;
    };
    proto.getElementsByClassName = DOMElement.prototype.getElementsByClassName;
    proto.getElementsByTagName = DOMElement.prototype.getElementsByTagName;
    proto.contains = DOMElement.prototype.contains;
    proto.removeEventListener = removeEventListener2;
    proto.addEventListener = addEventListener2;
    proto.dispatchEvent = dispatchEvent;
  }
});

// (disabled):node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/index.js
var require_min_document = __commonJS({
  "(disabled):node_modules/.pnpm/min-document@2.19.0/node_modules/min-document/index.js"(exports, module) {
    var Document2 = require_document();
    module.exports = new Document2();
  }
});

// node_modules/.pnpm/global@4.4.0/node_modules/global/document.js
var require_document2 = __commonJS({
  "node_modules/.pnpm/global@4.4.0/node_modules/global/document.js"(exports, module) {
    var topLevel = typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {};
    var minDoc = require_min_document();
    var doccy;
    if (typeof document !== "undefined") {
      doccy = document;
    } else {
      doccy = topLevel["__GLOBAL_DOCUMENT_CACHE@4"];
      if (!doccy) {
        doccy = topLevel["__GLOBAL_DOCUMENT_CACHE@4"] = minDoc;
      }
    }
    module.exports = doccy;
  }
});

// node_modules/.pnpm/keycode@2.2.1/node_modules/keycode/index.js
var require_keycode = __commonJS({
  "node_modules/.pnpm/keycode@2.2.1/node_modules/keycode/index.js"(exports, module) {
    function keyCode(searchInput) {
      if (searchInput && "object" === typeof searchInput) {
        var hasKeyCode = searchInput.which || searchInput.keyCode || searchInput.charCode;
        if (hasKeyCode) searchInput = hasKeyCode;
      }
      if ("number" === typeof searchInput) return names[searchInput];
      var search = String(searchInput);
      var foundNamedKey = codes[search.toLowerCase()];
      if (foundNamedKey) return foundNamedKey;
      var foundNamedKey = aliases[search.toLowerCase()];
      if (foundNamedKey) return foundNamedKey;
      if (search.length === 1) return search.charCodeAt(0);
      return void 0;
    }
    keyCode.isEventKey = function isEventKey(event, nameOrCode) {
      if (event && "object" === typeof event) {
        var keyCode2 = event.which || event.keyCode || event.charCode;
        if (keyCode2 === null || keyCode2 === void 0) {
          return false;
        }
        if (typeof nameOrCode === "string") {
          var foundNamedKey = codes[nameOrCode.toLowerCase()];
          if (foundNamedKey) {
            return foundNamedKey === keyCode2;
          }
          var foundNamedKey = aliases[nameOrCode.toLowerCase()];
          if (foundNamedKey) {
            return foundNamedKey === keyCode2;
          }
        } else if (typeof nameOrCode === "number") {
          return nameOrCode === keyCode2;
        }
        return false;
      }
    };
    exports = module.exports = keyCode;
    var codes = exports.code = exports.codes = {
      "backspace": 8,
      "tab": 9,
      "enter": 13,
      "shift": 16,
      "ctrl": 17,
      "alt": 18,
      "pause/break": 19,
      "caps lock": 20,
      "esc": 27,
      "space": 32,
      "page up": 33,
      "page down": 34,
      "end": 35,
      "home": 36,
      "left": 37,
      "up": 38,
      "right": 39,
      "down": 40,
      "insert": 45,
      "delete": 46,
      "command": 91,
      "left command": 91,
      "right command": 93,
      "numpad *": 106,
      "numpad +": 107,
      "numpad -": 109,
      "numpad .": 110,
      "numpad /": 111,
      "num lock": 144,
      "scroll lock": 145,
      "my computer": 182,
      "my calculator": 183,
      ";": 186,
      "=": 187,
      ",": 188,
      "-": 189,
      ".": 190,
      "/": 191,
      "`": 192,
      "[": 219,
      "\\": 220,
      "]": 221,
      "'": 222
    };
    var aliases = exports.aliases = {
      "windows": 91,
      "\u21E7": 16,
      "\u2325": 18,
      "\u2303": 17,
      "\u2318": 91,
      "ctl": 17,
      "control": 17,
      "option": 18,
      "pause": 19,
      "break": 19,
      "caps": 20,
      "return": 13,
      "escape": 27,
      "spc": 32,
      "spacebar": 32,
      "pgup": 33,
      "pgdn": 34,
      "ins": 45,
      "del": 46,
      "cmd": 91
    };
    for (i = 97; i < 123; i++) codes[String.fromCharCode(i)] = i - 32;
    for (i = 48; i < 58; i++) codes[i - 48] = i;
    var i;
    for (i = 1; i < 13; i++) codes["f" + i] = i + 111;
    for (i = 0; i < 10; i++) codes["numpad " + i] = i + 96;
    var names = exports.names = exports.title = {};
    for (i in codes) names[codes[i]] = i;
    for (alias in aliases) {
      codes[alias] = aliases[alias];
    }
    var alias;
  }
});

// node_modules/.pnpm/safe-json-parse@4.0.0/node_modules/safe-json-parse/tuple.js
var require_tuple = __commonJS({
  "node_modules/.pnpm/safe-json-parse@4.0.0/node_modules/safe-json-parse/tuple.js"(exports, module) {
    module.exports = SafeParseTuple;
    function SafeParseTuple(obj, reviver) {
      var json;
      var error = null;
      try {
        json = JSON.parse(obj, reviver);
      } catch (err) {
        error = err;
      }
      return [error, json];
    }
  }
});

// node_modules/.pnpm/@babel+runtime@7.28.2/node_modules/@babel/runtime/helpers/extends.js
var require_extends = __commonJS({
  "node_modules/.pnpm/@babel+runtime@7.28.2/node_modules/@babel/runtime/helpers/extends.js"(exports, module) {
    function _extends3() {
      return module.exports = _extends3 = Object.assign ? Object.assign.bind() : function(n) {
        for (var e = 1; e < arguments.length; e++) {
          var t2 = arguments[e];
          for (var r2 in t2) ({}).hasOwnProperty.call(t2, r2) && (n[r2] = t2[r2]);
        }
        return n;
      }, module.exports.__esModule = true, module.exports["default"] = module.exports, _extends3.apply(null, arguments);
    }
    module.exports = _extends3, module.exports.__esModule = true, module.exports["default"] = module.exports;
  }
});

// node_modules/.pnpm/is-function@1.0.2/node_modules/is-function/index.js
var require_is_function = __commonJS({
  "node_modules/.pnpm/is-function@1.0.2/node_modules/is-function/index.js"(exports, module) {
    module.exports = isFunction;
    var toString2 = Object.prototype.toString;
    function isFunction(fn) {
      if (!fn) {
        return false;
      }
      var string = toString2.call(fn);
      return string === "[object Function]" || typeof fn === "function" && string !== "[object RegExp]" || typeof window !== "undefined" && // IE8 and below
      (fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt);
    }
  }
});

// node_modules/.pnpm/@videojs+xhr@2.6.0/node_modules/@videojs/xhr/lib/http-handler.js
var require_http_handler = __commonJS({
  "node_modules/.pnpm/@videojs+xhr@2.6.0/node_modules/@videojs/xhr/lib/http-handler.js"(exports, module) {
    "use strict";
    var window7 = require_window();
    var httpResponseHandler = function httpResponseHandler2(callback2, decodeResponseBody) {
      if (decodeResponseBody === void 0) {
        decodeResponseBody = false;
      }
      return function(err, response, responseBody) {
        if (err) {
          callback2(err);
          return;
        }
        if (response.statusCode >= 400 && response.statusCode <= 599) {
          var cause = responseBody;
          if (decodeResponseBody) {
            if (window7.TextDecoder) {
              var charset = getCharset(response.headers && response.headers["content-type"]);
              try {
                cause = new TextDecoder(charset).decode(responseBody);
              } catch (e) {
              }
            } else {
              cause = String.fromCharCode.apply(null, new Uint8Array(responseBody));
            }
          }
          callback2({
            cause
          });
          return;
        }
        callback2(null, responseBody);
      };
    };
    function getCharset(contentTypeHeader) {
      if (contentTypeHeader === void 0) {
        contentTypeHeader = "";
      }
      return contentTypeHeader.toLowerCase().split(";").reduce(function(charset, contentType) {
        var _contentType$split = contentType.split("="), type2 = _contentType$split[0], value = _contentType$split[1];
        if (type2.trim() === "charset") {
          return value.trim();
        }
        return charset;
      }, "utf-8");
    }
    module.exports = httpResponseHandler;
  }
});

// node_modules/.pnpm/@videojs+xhr@2.6.0/node_modules/@videojs/xhr/lib/index.js
var require_lib = __commonJS({
  "node_modules/.pnpm/@videojs+xhr@2.6.0/node_modules/@videojs/xhr/lib/index.js"(exports, module) {
    "use strict";
    var window7 = require_window();
    var _extends3 = require_extends();
    var isFunction = require_is_function();
    createXHR.httpHandler = require_http_handler();
    var parseHeaders = function parseHeaders2(headers) {
      var result = {};
      if (!headers) {
        return result;
      }
      headers.trim().split("\n").forEach(function(row) {
        var index = row.indexOf(":");
        var key = row.slice(0, index).trim().toLowerCase();
        var value = row.slice(index + 1).trim();
        if (typeof result[key] === "undefined") {
          result[key] = value;
        } else if (Array.isArray(result[key])) {
          result[key].push(value);
        } else {
          result[key] = [result[key], value];
        }
      });
      return result;
    };
    module.exports = createXHR;
    module.exports.default = createXHR;
    createXHR.XMLHttpRequest = window7.XMLHttpRequest || noop4;
    createXHR.XDomainRequest = "withCredentials" in new createXHR.XMLHttpRequest() ? createXHR.XMLHttpRequest : window7.XDomainRequest;
    forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
      createXHR[method === "delete" ? "del" : method] = function(uri, options, callback2) {
        options = initParams(uri, options, callback2);
        options.method = method.toUpperCase();
        return _createXHR(options);
      };
    });
    function forEachArray(array, iterator) {
      for (var i = 0; i < array.length; i++) {
        iterator(array[i]);
      }
    }
    function isEmpty(obj) {
      for (var i in obj) {
        if (obj.hasOwnProperty(i)) return false;
      }
      return true;
    }
    function initParams(uri, options, callback2) {
      var params = uri;
      if (isFunction(options)) {
        callback2 = options;
        if (typeof uri === "string") {
          params = {
            uri
          };
        }
      } else {
        params = _extends3({}, options, {
          uri
        });
      }
      params.callback = callback2;
      return params;
    }
    function createXHR(uri, options, callback2) {
      options = initParams(uri, options, callback2);
      return _createXHR(options);
    }
    function _createXHR(options) {
      if (typeof options.callback === "undefined") {
        throw new Error("callback argument missing");
      }
      var called = false;
      var callback2 = function cbOnce(err, response, body2) {
        if (!called) {
          called = true;
          options.callback(err, response, body2);
        }
      };
      function readystatechange() {
        if (xhr.readyState === 4) {
          setTimeout(loadFunc, 0);
        }
      }
      function getBody() {
        var body2 = void 0;
        if (xhr.response) {
          body2 = xhr.response;
        } else {
          body2 = xhr.responseText || getXml(xhr);
        }
        if (isJson) {
          try {
            body2 = JSON.parse(body2);
          } catch (e) {
          }
        }
        return body2;
      }
      function errorFunc(evt) {
        clearTimeout(timeoutTimer);
        if (!(evt instanceof Error)) {
          evt = new Error("" + (evt || "Unknown XMLHttpRequest Error"));
        }
        evt.statusCode = 0;
        return callback2(evt, failureResponse);
      }
      function loadFunc() {
        if (aborted) return;
        var status2;
        clearTimeout(timeoutTimer);
        if (options.useXDR && xhr.status === void 0) {
          status2 = 200;
        } else {
          status2 = xhr.status === 1223 ? 204 : xhr.status;
        }
        var response = failureResponse;
        var err = null;
        if (status2 !== 0) {
          response = {
            body: getBody(),
            statusCode: status2,
            method,
            headers: {},
            url: uri,
            rawRequest: xhr
          };
          if (xhr.getAllResponseHeaders) {
            response.headers = parseHeaders(xhr.getAllResponseHeaders());
          }
        } else {
          err = new Error("Internal XMLHttpRequest Error");
        }
        return callback2(err, response, response.body);
      }
      var xhr = options.xhr || null;
      if (!xhr) {
        if (options.cors || options.useXDR) {
          xhr = new createXHR.XDomainRequest();
        } else {
          xhr = new createXHR.XMLHttpRequest();
        }
      }
      var key;
      var aborted;
      var uri = xhr.url = options.uri || options.url;
      var method = xhr.method = options.method || "GET";
      var body = options.body || options.data;
      var headers = xhr.headers = options.headers || {};
      var sync = !!options.sync;
      var isJson = false;
      var timeoutTimer;
      var failureResponse = {
        body: void 0,
        headers: {},
        statusCode: 0,
        method,
        url: uri,
        rawRequest: xhr
      };
      if ("json" in options && options.json !== false) {
        isJson = true;
        headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json");
        if (method !== "GET" && method !== "HEAD") {
          headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json");
          body = JSON.stringify(options.json === true ? body : options.json);
        }
      }
      xhr.onreadystatechange = readystatechange;
      xhr.onload = loadFunc;
      xhr.onerror = errorFunc;
      xhr.onprogress = function() {
      };
      xhr.onabort = function() {
        aborted = true;
      };
      xhr.ontimeout = errorFunc;
      xhr.open(method, uri, !sync, options.username, options.password);
      if (!sync) {
        xhr.withCredentials = !!options.withCredentials;
      }
      if (!sync && options.timeout > 0) {
        timeoutTimer = setTimeout(function() {
          if (aborted) return;
          aborted = true;
          xhr.abort("timeout");
          var e = new Error("XMLHttpRequest timeout");
          e.code = "ETIMEDOUT";
          errorFunc(e);
        }, options.timeout);
      }
      if (xhr.setRequestHeader) {
        for (key in headers) {
          if (headers.hasOwnProperty(key)) {
            xhr.setRequestHeader(key, headers[key]);
          }
        }
      } else if (options.headers && !isEmpty(options.headers)) {
        throw new Error("Headers cannot be set on an XDomainRequest object");
      }
      if ("responseType" in options) {
        xhr.responseType = options.responseType;
      }
      if ("beforeSend" in options && typeof options.beforeSend === "function") {
        options.beforeSend(xhr);
      }
      xhr.send(body || null);
      return xhr;
    }
    function getXml(xhr) {
      try {
        if (xhr.responseType === "document") {
          return xhr.responseXML;
        }
        var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror";
        if (xhr.responseType === "" && !firefoxBugTakenEffect) {
          return xhr.responseXML;
        }
      } catch (e) {
      }
      return null;
    }
    function noop4() {
    }
  }
});

// node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/vtt.js
var require_vtt = __commonJS({
  "node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/vtt.js"(exports, module) {
    var document3 = require_document2();
    var _objCreate = Object.create || /* @__PURE__ */ function() {
      function F() {
      }
      return function(o) {
        if (arguments.length !== 1) {
          throw new Error("Object.create shim only accepts one parameter.");
        }
        F.prototype = o;
        return new F();
      };
    }();
    function ParsingError(errorData, message) {
      this.name = "ParsingError";
      this.code = errorData.code;
      this.message = message || errorData.message;
    }
    ParsingError.prototype = _objCreate(Error.prototype);
    ParsingError.prototype.constructor = ParsingError;
    ParsingError.Errors = {
      BadSignature: {
        code: 0,
        message: "Malformed WebVTT signature."
      },
      BadTimeStamp: {
        code: 1,
        message: "Malformed time stamp."
      }
    };
    function parseTimeStamp2(input) {
      function computeSeconds(h, m2, s, f) {
        return (h | 0) * 3600 + (m2 | 0) * 60 + (s | 0) + (f | 0) / 1e3;
      }
      var m = input.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);
      if (!m) {
        return null;
      }
      if (m[3]) {
        return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
      } else if (m[1] > 59) {
        return computeSeconds(m[1], m[2], 0, m[4]);
      } else {
        return computeSeconds(0, m[1], m[2], m[4]);
      }
    }
    function Settings2() {
      this.values = _objCreate(null);
    }
    Settings2.prototype = {
      // Only accept the first assignment to any key.
      set: function(k, v) {
        if (!this.get(k) && v !== "") {
          this.values[k] = v;
        }
      },
      // Return the value for a key, or a default value.
      // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
      // a number of possible default values as properties where 'defaultKey' is
      // the key of the property that will be chosen; otherwise it's assumed to be
      // a single value.
      get: function(k, dflt, defaultKey) {
        if (defaultKey) {
          return this.has(k) ? this.values[k] : dflt[defaultKey];
        }
        return this.has(k) ? this.values[k] : dflt;
      },
      // Check whether we have a value for a key.
      has: function(k) {
        return k in this.values;
      },
      // Accept a setting if its one of the given alternatives.
      alt: function(k, v, a) {
        for (var n = 0; n < a.length; ++n) {
          if (v === a[n]) {
            this.set(k, v);
            break;
          }
        }
      },
      // Accept a setting if its a valid (signed) integer.
      integer: function(k, v) {
        if (/^-?\d+$/.test(v)) {
          this.set(k, parseInt(v, 10));
        }
      },
      // Accept a setting if its a valid percentage.
      percent: function(k, v) {
        var m;
        if (m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
          v = parseFloat(v);
          if (v >= 0 && v <= 100) {
            this.set(k, v);
            return true;
          }
        }
        return false;
      }
    };
    function parseOptions2(input, callback2, keyValueDelim, groupDelim) {
      var groups = groupDelim ? input.split(groupDelim) : [input];
      for (var i in groups) {
        if (typeof groups[i] !== "string") {
          continue;
        }
        var kv = groups[i].split(keyValueDelim);
        if (kv.length !== 2) {
          continue;
        }
        var k = kv[0].trim();
        var v = kv[1].trim();
        callback2(k, v);
      }
    }
    function parseCue2(input, cue, regionList) {
      var oInput = input;
      function consumeTimeStamp() {
        var ts2 = parseTimeStamp2(input);
        if (ts2 === null) {
          throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput);
        }
        input = input.replace(/^[^\sa-zA-Z-]+/, "");
        return ts2;
      }
      function consumeCueSettings(input2, cue2) {
        var settings = new Settings2();
        parseOptions2(input2, function(k, v) {
          switch (k) {
            case "region":
              for (var i = regionList.length - 1; i >= 0; i--) {
                if (regionList[i].id === v) {
                  settings.set(k, regionList[i].region);
                  break;
                }
              }
              break;
            case "vertical":
              settings.alt(k, v, ["rl", "lr"]);
              break;
            case "line":
              var vals = v.split(","), vals0 = vals[0];
              settings.integer(k, vals0);
              settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
              settings.alt(k, vals0, ["auto"]);
              if (vals.length === 2) {
                settings.alt("lineAlign", vals[1], ["start", "center", "end"]);
              }
              break;
            case "position":
              vals = v.split(",");
              settings.percent(k, vals[0]);
              if (vals.length === 2) {
                settings.alt("positionAlign", vals[1], ["start", "center", "end"]);
              }
              break;
            case "size":
              settings.percent(k, v);
              break;
            case "align":
              settings.alt(k, v, ["start", "center", "end", "left", "right"]);
              break;
          }
        }, /:/, /\s/);
        cue2.region = settings.get("region", null);
        cue2.vertical = settings.get("vertical", "");
        try {
          cue2.line = settings.get("line", "auto");
        } catch (e) {
        }
        cue2.lineAlign = settings.get("lineAlign", "start");
        cue2.snapToLines = settings.get("snapToLines", true);
        cue2.size = settings.get("size", 100);
        try {
          cue2.align = settings.get("align", "center");
        } catch (e) {
          cue2.align = settings.get("align", "middle");
        }
        try {
          cue2.position = settings.get("position", "auto");
        } catch (e) {
          cue2.position = settings.get("position", {
            start: 0,
            left: 0,
            center: 50,
            middle: 50,
            end: 100,
            right: 100
          }, cue2.align);
        }
        cue2.positionAlign = settings.get("positionAlign", {
          start: "start",
          left: "start",
          center: "center",
          middle: "center",
          end: "end",
          right: "end"
        }, cue2.align);
      }
      function skipWhitespace() {
        input = input.replace(/^\s+/, "");
      }
      skipWhitespace();
      cue.startTime = consumeTimeStamp();
      skipWhitespace();
      if (input.substr(0, 3) !== "-->") {
        throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
      }
      input = input.substr(3);
      skipWhitespace();
      cue.endTime = consumeTimeStamp();
      skipWhitespace();
      consumeCueSettings(input, cue);
    }
    var TEXTAREA_ELEMENT = document3.createElement && document3.createElement("textarea");
    var TAG_NAME = {
      c: "span",
      i: "i",
      b: "b",
      u: "u",
      ruby: "ruby",
      rt: "rt",
      v: "span",
      lang: "span"
    };
    var DEFAULT_COLOR_CLASS = {
      white: "rgba(255,255,255,1)",
      lime: "rgba(0,255,0,1)",
      cyan: "rgba(0,255,255,1)",
      red: "rgba(255,0,0,1)",
      yellow: "rgba(255,255,0,1)",
      magenta: "rgba(255,0,255,1)",
      blue: "rgba(0,0,255,1)",
      black: "rgba(0,0,0,1)"
    };
    var TAG_ANNOTATION = {
      v: "title",
      lang: "lang"
    };
    var NEEDS_PARENT = {
      rt: "ruby"
    };
    function parseContent(window7, input) {
      function nextToken() {
        if (!input) {
          return null;
        }
        function consume(result) {
          input = input.substr(result.length);
          return result;
        }
        var m2 = input.match(/^([^<]*)(<[^>]*>?)?/);
        return consume(m2[1] ? m2[1] : m2[2]);
      }
      function unescape2(s) {
        TEXTAREA_ELEMENT.innerHTML = s;
        s = TEXTAREA_ELEMENT.textContent;
        TEXTAREA_ELEMENT.textContent = "";
        return s;
      }
      function shouldAdd(current2, element) {
        return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current2.localName;
      }
      function createElement(type2, annotation) {
        var tagName = TAG_NAME[type2];
        if (!tagName) {
          return null;
        }
        var element = window7.document.createElement(tagName);
        var name = TAG_ANNOTATION[type2];
        if (name && annotation) {
          element[name] = annotation.trim();
        }
        return element;
      }
      var rootDiv = window7.document.createElement("div"), current = rootDiv, t2, tagStack = [];
      while ((t2 = nextToken()) !== null) {
        if (t2[0] === "<") {
          if (t2[1] === "/") {
            if (tagStack.length && tagStack[tagStack.length - 1] === t2.substr(2).replace(">", "")) {
              tagStack.pop();
              current = current.parentNode;
            }
            continue;
          }
          var ts2 = parseTimeStamp2(t2.substr(1, t2.length - 2));
          var node;
          if (ts2) {
            node = window7.document.createProcessingInstruction("timestamp", ts2);
            current.appendChild(node);
            continue;
          }
          var m = t2.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);
          if (!m) {
            continue;
          }
          node = createElement(m[1], m[3]);
          if (!node) {
            continue;
          }
          if (!shouldAdd(current, node)) {
            continue;
          }
          if (m[2]) {
            var classes = m[2].split(".");
            classes.forEach(function(cl) {
              var bgColor = /^bg_/.test(cl);
              var colorName = bgColor ? cl.slice(3) : cl;
              if (DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)) {
                var propName = bgColor ? "background-color" : "color";
                var propValue = DEFAULT_COLOR_CLASS[colorName];
                node.style[propName] = propValue;
              }
            });
            node.className = classes.join(" ");
          }
          tagStack.push(m[1]);
          current.appendChild(node);
          current = node;
          continue;
        }
        current.appendChild(window7.document.createTextNode(unescape2(t2)));
      }
      return rootDiv;
    }
    var strongRTLRanges = [[1470, 1470], [1472, 1472], [1475, 1475], [1478, 1478], [1488, 1514], [1520, 1524], [1544, 1544], [1547, 1547], [1549, 1549], [1563, 1563], [1566, 1610], [1645, 1647], [1649, 1749], [1765, 1766], [1774, 1775], [1786, 1805], [1807, 1808], [1810, 1839], [1869, 1957], [1969, 1969], [1984, 2026], [2036, 2037], [2042, 2042], [2048, 2069], [2074, 2074], [2084, 2084], [2088, 2088], [2096, 2110], [2112, 2136], [2142, 2142], [2208, 2208], [2210, 2220], [8207, 8207], [64285, 64285], [64287, 64296], [64298, 64310], [64312, 64316], [64318, 64318], [64320, 64321], [64323, 64324], [64326, 64449], [64467, 64829], [64848, 64911], [64914, 64967], [65008, 65020], [65136, 65140], [65142, 65276], [67584, 67589], [67592, 67592], [67594, 67637], [67639, 67640], [67644, 67644], [67647, 67669], [67671, 67679], [67840, 67867], [67872, 67897], [67903, 67903], [67968, 68023], [68030, 68031], [68096, 68096], [68112, 68115], [68117, 68119], [68121, 68147], [68160, 68167], [68176, 68184], [68192, 68223], [68352, 68405], [68416, 68437], [68440, 68466], [68472, 68479], [68608, 68680], [126464, 126467], [126469, 126495], [126497, 126498], [126500, 126500], [126503, 126503], [126505, 126514], [126516, 126519], [126521, 126521], [126523, 126523], [126530, 126530], [126535, 126535], [126537, 126537], [126539, 126539], [126541, 126543], [126545, 126546], [126548, 126548], [126551, 126551], [126553, 126553], [126555, 126555], [126557, 126557], [126559, 126559], [126561, 126562], [126564, 126564], [126567, 126570], [126572, 126578], [126580, 126583], [126585, 126588], [126590, 126590], [126592, 126601], [126603, 126619], [126625, 126627], [126629, 126633], [126635, 126651], [1114109, 1114109]];
    function isStrongRTLChar(charCode) {
      for (var i = 0; i < strongRTLRanges.length; i++) {
        var currentRange = strongRTLRanges[i];
        if (charCode >= currentRange[0] && charCode <= currentRange[1]) {
          return true;
        }
      }
      return false;
    }
    function determineBidi(cueDiv) {
      var nodeStack = [], text = "", charCode;
      if (!cueDiv || !cueDiv.childNodes) {
        return "ltr";
      }
      function pushNodes(nodeStack2, node) {
        for (var i2 = node.childNodes.length - 1; i2 >= 0; i2--) {
          nodeStack2.push(node.childNodes[i2]);
        }
      }
      function nextTextNode(nodeStack2) {
        if (!nodeStack2 || !nodeStack2.length) {
          return null;
        }
        var node = nodeStack2.pop(), text2 = node.textContent || node.innerText;
        if (text2) {
          var m = text2.match(/^.*(\n|\r)/);
          if (m) {
            nodeStack2.length = 0;
            return m[0];
          }
          return text2;
        }
        if (node.tagName === "ruby") {
          return nextTextNode(nodeStack2);
        }
        if (node.childNodes) {
          pushNodes(nodeStack2, node);
          return nextTextNode(nodeStack2);
        }
      }
      pushNodes(nodeStack, cueDiv);
      while (text = nextTextNode(nodeStack)) {
        for (var i = 0; i < text.length; i++) {
          charCode = text.charCodeAt(i);
          if (isStrongRTLChar(charCode)) {
            return "rtl";
          }
        }
      }
      return "ltr";
    }
    function computeLinePos(cue) {
      if (typeof cue.line === "number" && (cue.snapToLines || cue.line >= 0 && cue.line <= 100)) {
        return cue.line;
      }
      if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) {
        return -1;
      }
      var track = cue.track, trackList = track.textTrackList, count = 0;
      for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
        if (trackList[i].mode === "showing") {
          count++;
        }
      }
      return ++count * -1;
    }
    function StyleBox() {
    }
    StyleBox.prototype.applyStyles = function(styles, div) {
      div = div || this.div;
      for (var prop in styles) {
        if (styles.hasOwnProperty(prop)) {
          div.style[prop] = styles[prop];
        }
      }
    };
    StyleBox.prototype.formatStyle = function(val, unit) {
      return val === 0 ? 0 : val + unit;
    };
    function CueStyleBox(window7, cue, styleOptions) {
      StyleBox.call(this);
      this.cue = cue;
      this.cueDiv = parseContent(window7, cue.text);
      var styles = {
        color: "rgba(255, 255, 255, 1)",
        backgroundColor: "rgba(0, 0, 0, 0.8)",
        position: "relative",
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        display: "inline",
        writingMode: cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl",
        unicodeBidi: "plaintext"
      };
      this.applyStyles(styles, this.cueDiv);
      this.div = window7.document.createElement("div");
      styles = {
        direction: determineBidi(this.cueDiv),
        writingMode: cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl",
        unicodeBidi: "plaintext",
        textAlign: cue.align === "middle" ? "center" : cue.align,
        font: styleOptions.font,
        whiteSpace: "pre-line",
        position: "absolute"
      };
      this.applyStyles(styles);
      this.div.appendChild(this.cueDiv);
      var textPos = 0;
      switch (cue.positionAlign) {
        case "start":
        case "line-left":
          textPos = cue.position;
          break;
        case "center":
          textPos = cue.position - cue.size / 2;
          break;
        case "end":
        case "line-right":
          textPos = cue.position - cue.size;
          break;
      }
      if (cue.vertical === "") {
        this.applyStyles({
          left: this.formatStyle(textPos, "%"),
          width: this.formatStyle(cue.size, "%")
        });
      } else {
        this.applyStyles({
          top: this.formatStyle(textPos, "%"),
          height: this.formatStyle(cue.size, "%")
        });
      }
      this.move = function(box) {
        this.applyStyles({
          top: this.formatStyle(box.top, "px"),
          bottom: this.formatStyle(box.bottom, "px"),
          left: this.formatStyle(box.left, "px"),
          right: this.formatStyle(box.right, "px"),
          height: this.formatStyle(box.height, "px"),
          width: this.formatStyle(box.width, "px")
        });
      };
    }
    CueStyleBox.prototype = _objCreate(StyleBox.prototype);
    CueStyleBox.prototype.constructor = CueStyleBox;
    function BoxPosition(obj) {
      var lh, height2, width2, top;
      if (obj.div) {
        height2 = obj.div.offsetHeight;
        width2 = obj.div.offsetWidth;
        top = obj.div.offsetTop;
        var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects();
        obj = obj.div.getBoundingClientRect();
        lh = rects ? Math.max(rects[0] && rects[0].height || 0, obj.height / rects.length) : 0;
      }
      this.left = obj.left;
      this.right = obj.right;
      this.top = obj.top || top;
      this.height = obj.height || height2;
      this.bottom = obj.bottom || top + (obj.height || height2);
      this.width = obj.width || width2;
      this.lineHeight = lh !== void 0 ? lh : obj.lineHeight;
    }
    BoxPosition.prototype.move = function(axis, toMove) {
      toMove = toMove !== void 0 ? toMove : this.lineHeight;
      switch (axis) {
        case "+x":
          this.left += toMove;
          this.right += toMove;
          break;
        case "-x":
          this.left -= toMove;
          this.right -= toMove;
          break;
        case "+y":
          this.top += toMove;
          this.bottom += toMove;
          break;
        case "-y":
          this.top -= toMove;
          this.bottom -= toMove;
          break;
      }
    };
    BoxPosition.prototype.overlaps = function(b2) {
      return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top;
    };
    BoxPosition.prototype.overlapsAny = function(boxes) {
      for (var i = 0; i < boxes.length; i++) {
        if (this.overlaps(boxes[i])) {
          return true;
        }
      }
      return false;
    };
    BoxPosition.prototype.within = function(container) {
      return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right;
    };
    BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) {
      switch (axis) {
        case "+x":
          return this.left < container.left;
        case "-x":
          return this.right > container.right;
        case "+y":
          return this.top < container.top;
        case "-y":
          return this.bottom > container.bottom;
      }
    };
    BoxPosition.prototype.intersectPercentage = function(b2) {
      var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)), y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)), intersectArea = x * y;
      return intersectArea / (this.height * this.width);
    };
    BoxPosition.prototype.toCSSCompatValues = function(reference) {
      return {
        top: this.top - reference.top,
        bottom: reference.bottom - this.bottom,
        left: this.left - reference.left,
        right: reference.right - this.right,
        height: this.height,
        width: this.width
      };
    };
    BoxPosition.getSimpleBoxPosition = function(obj) {
      var height2 = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
      var width2 = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
      var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
      obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj;
      var ret = {
        left: obj.left,
        right: obj.right,
        top: obj.top || top,
        height: obj.height || height2,
        bottom: obj.bottom || top + (obj.height || height2),
        width: obj.width || width2
      };
      return ret;
    };
    function moveBoxToLinePosition(window7, styleBox, containerBox, boxPositions) {
      function findBestPosition(b, axis2) {
        var bestPosition2, specifiedPosition = new BoxPosition(b), percentage = 1;
        for (var i = 0; i < axis2.length; i++) {
          while (b.overlapsOppositeAxis(containerBox, axis2[i]) || b.within(containerBox) && b.overlapsAny(boxPositions)) {
            b.move(axis2[i]);
          }
          if (b.within(containerBox)) {
            return b;
          }
          var p = b.intersectPercentage(containerBox);
          if (percentage > p) {
            bestPosition2 = new BoxPosition(b);
            percentage = p;
          }
          b = new BoxPosition(specifiedPosition);
        }
        return bestPosition2 || specifiedPosition;
      }
      var boxPosition = new BoxPosition(styleBox), cue = styleBox.cue, linePos = computeLinePos(cue), axis = [];
      if (cue.snapToLines) {
        var size;
        switch (cue.vertical) {
          case "":
            axis = ["+y", "-y"];
            size = "height";
            break;
          case "rl":
            axis = ["+x", "-x"];
            size = "width";
            break;
          case "lr":
            axis = ["-x", "+x"];
            size = "width";
            break;
        }
        var step = boxPosition.lineHeight, position = step * Math.round(linePos), maxPosition = containerBox[size] + step, initialAxis = axis[0];
        if (Math.abs(position) > maxPosition) {
          position = position < 0 ? -1 : 1;
          position *= Math.ceil(maxPosition / step) * step;
        }
        if (linePos < 0) {
          position += cue.vertical === "" ? containerBox.height : containerBox.width;
          axis = axis.reverse();
        }
        boxPosition.move(initialAxis, position);
      } else {
        var calculatedPercentage = boxPosition.lineHeight / containerBox.height * 100;
        switch (cue.lineAlign) {
          case "center":
            linePos -= calculatedPercentage / 2;
            break;
          case "end":
            linePos -= calculatedPercentage;
            break;
        }
        switch (cue.vertical) {
          case "":
            styleBox.applyStyles({
              top: styleBox.formatStyle(linePos, "%")
            });
            break;
          case "rl":
            styleBox.applyStyles({
              left: styleBox.formatStyle(linePos, "%")
            });
            break;
          case "lr":
            styleBox.applyStyles({
              right: styleBox.formatStyle(linePos, "%")
            });
            break;
        }
        axis = ["+y", "-x", "+x", "-y"];
        boxPosition = new BoxPosition(styleBox);
      }
      var bestPosition = findBestPosition(boxPosition, axis);
      styleBox.move(bestPosition.toCSSCompatValues(containerBox));
    }
    function WebVTT2() {
    }
    WebVTT2.StringDecoder = function() {
      return {
        decode: function(data) {
          if (!data) {
            return "";
          }
          if (typeof data !== "string") {
            throw new Error("Error - expected string data.");
          }
          return decodeURIComponent(encodeURIComponent(data));
        }
      };
    };
    WebVTT2.convertCueToDOMTree = function(window7, cuetext) {
      if (!window7 || !cuetext) {
        return null;
      }
      return parseContent(window7, cuetext);
    };
    var FONT_SIZE_PERCENT = 0.05;
    var FONT_STYLE = "sans-serif";
    var CUE_BACKGROUND_PADDING = "1.5%";
    WebVTT2.processCues = function(window7, cues, overlay) {
      if (!window7 || !cues || !overlay) {
        return null;
      }
      while (overlay.firstChild) {
        overlay.removeChild(overlay.firstChild);
      }
      var paddedOverlay = window7.document.createElement("div");
      paddedOverlay.style.position = "absolute";
      paddedOverlay.style.left = "0";
      paddedOverlay.style.right = "0";
      paddedOverlay.style.top = "0";
      paddedOverlay.style.bottom = "0";
      paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
      overlay.appendChild(paddedOverlay);
      function shouldCompute(cues2) {
        for (var i2 = 0; i2 < cues2.length; i2++) {
          if (cues2[i2].hasBeenReset || !cues2[i2].displayState) {
            return true;
          }
        }
        return false;
      }
      if (!shouldCompute(cues)) {
        for (var i = 0; i < cues.length; i++) {
          paddedOverlay.appendChild(cues[i].displayState);
        }
        return;
      }
      var boxPositions = [], containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay), fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
      var styleOptions = {
        font: fontSize + "px " + FONT_STYLE
      };
      (function() {
        var styleBox, cue;
        for (var i2 = 0; i2 < cues.length; i2++) {
          cue = cues[i2];
          styleBox = new CueStyleBox(window7, cue, styleOptions);
          paddedOverlay.appendChild(styleBox.div);
          moveBoxToLinePosition(window7, styleBox, containerBox, boxPositions);
          cue.displayState = styleBox.div;
          boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
        }
      })();
    };
    WebVTT2.Parser = function(window7, vttjs, decoder) {
      if (!decoder) {
        decoder = vttjs;
        vttjs = {};
      }
      if (!vttjs) {
        vttjs = {};
      }
      this.window = window7;
      this.vttjs = vttjs;
      this.state = "INITIAL";
      this.buffer = "";
      this.decoder = decoder || new TextDecoder("utf8");
      this.regionList = [];
    };
    WebVTT2.Parser.prototype = {
      // If the error is a ParsingError then report it to the consumer if
      // possible. If it's not a ParsingError then throw it like normal.
      reportOrThrowError: function(e) {
        if (e instanceof ParsingError) {
          this.onparsingerror && this.onparsingerror(e);
        } else {
          throw e;
        }
      },
      parse: function(data) {
        var self2 = this;
        if (data) {
          self2.buffer += self2.decoder.decode(data, {
            stream: true
          });
        }
        function collectNextLine() {
          var buffer = self2.buffer;
          var pos = 0;
          while (pos < buffer.length && buffer[pos] !== "\r" && buffer[pos] !== "\n") {
            ++pos;
          }
          var line2 = buffer.substr(0, pos);
          if (buffer[pos] === "\r") {
            ++pos;
          }
          if (buffer[pos] === "\n") {
            ++pos;
          }
          self2.buffer = buffer.substr(pos);
          return line2;
        }
        function parseRegion(input) {
          var settings = new Settings2();
          parseOptions2(input, function(k, v) {
            switch (k) {
              case "id":
                settings.set(k, v);
                break;
              case "width":
                settings.percent(k, v);
                break;
              case "lines":
                settings.integer(k, v);
                break;
              case "regionanchor":
              case "viewportanchor":
                var xy = v.split(",");
                if (xy.length !== 2) {
                  break;
                }
                var anchor = new Settings2();
                anchor.percent("x", xy[0]);
                anchor.percent("y", xy[1]);
                if (!anchor.has("x") || !anchor.has("y")) {
                  break;
                }
                settings.set(k + "X", anchor.get("x"));
                settings.set(k + "Y", anchor.get("y"));
                break;
              case "scroll":
                settings.alt(k, v, ["up"]);
                break;
            }
          }, /=/, /\s/);
          if (settings.has("id")) {
            var region = new (self2.vttjs.VTTRegion || self2.window.VTTRegion)();
            region.width = settings.get("width", 100);
            region.lines = settings.get("lines", 3);
            region.regionAnchorX = settings.get("regionanchorX", 0);
            region.regionAnchorY = settings.get("regionanchorY", 100);
            region.viewportAnchorX = settings.get("viewportanchorX", 0);
            region.viewportAnchorY = settings.get("viewportanchorY", 100);
            region.scroll = settings.get("scroll", "");
            self2.onregion && self2.onregion(region);
            self2.regionList.push({
              id: settings.get("id"),
              region
            });
          }
        }
        function parseTimestampMap(input) {
          var settings = new Settings2();
          parseOptions2(input, function(k, v) {
            switch (k) {
              case "MPEGT":
                settings.integer(k + "S", v);
                break;
              case "LOCA":
                settings.set(k + "L", parseTimeStamp2(v));
                break;
            }
          }, /[^\d]:/, /,/);
          self2.ontimestampmap && self2.ontimestampmap({
            "MPEGTS": settings.get("MPEGTS"),
            "LOCAL": settings.get("LOCAL")
          });
        }
        function parseHeader2(input) {
          if (input.match(/X-TIMESTAMP-MAP/)) {
            parseOptions2(input, function(k, v) {
              switch (k) {
                case "X-TIMESTAMP-MAP":
                  parseTimestampMap(v);
                  break;
              }
            }, /=/);
          } else {
            parseOptions2(input, function(k, v) {
              switch (k) {
                case "Region":
                  parseRegion(v);
                  break;
              }
            }, /:/);
          }
        }
        try {
          var line;
          if (self2.state === "INITIAL") {
            if (!/\r\n|\n/.test(self2.buffer)) {
              return this;
            }
            line = collectNextLine();
            var m = line.match(/^WEBVTT([ \t].*)?$/);
            if (!m || !m[0]) {
              throw new ParsingError(ParsingError.Errors.BadSignature);
            }
            self2.state = "HEADER";
          }
          var alreadyCollectedLine = false;
          while (self2.buffer) {
            if (!/\r\n|\n/.test(self2.buffer)) {
              return this;
            }
            if (!alreadyCollectedLine) {
              line = collectNextLine();
            } else {
              alreadyCollectedLine = false;
            }
            switch (self2.state) {
              case "HEADER":
                if (/:/.test(line)) {
                  parseHeader2(line);
                } else if (!line) {
                  self2.state = "ID";
                }
                continue;
              case "NOTE":
                if (!line) {
                  self2.state = "ID";
                }
                continue;
              case "ID":
                if (/^NOTE($|[ \t])/.test(line)) {
                  self2.state = "NOTE";
                  break;
                }
                if (!line) {
                  continue;
                }
                self2.cue = new (self2.vttjs.VTTCue || self2.window.VTTCue)(0, 0, "");
                try {
                  self2.cue.align = "center";
                } catch (e) {
                  self2.cue.align = "middle";
                }
                self2.state = "CUE";
                if (line.indexOf("-->") === -1) {
                  self2.cue.id = line;
                  continue;
                }
              // Process line as start of a cue.
              /*falls through*/
              case "CUE":
                try {
                  parseCue2(line, self2.cue, self2.regionList);
                } catch (e) {
                  self2.reportOrThrowError(e);
                  self2.cue = null;
                  self2.state = "BADCUE";
                  continue;
                }
                self2.state = "CUETEXT";
                continue;
              case "CUETEXT":
                var hasSubstring = line.indexOf("-->") !== -1;
                if (!line || hasSubstring && (alreadyCollectedLine = true)) {
                  self2.oncue && self2.oncue(self2.cue);
                  self2.cue = null;
                  self2.state = "ID";
                  continue;
                }
                if (self2.cue.text) {
                  self2.cue.text += "\n";
                }
                self2.cue.text += line.replace(/\u2028/g, "\n").replace(/u2029/g, "\n");
                continue;
              case "BADCUE":
                if (!line) {
                  self2.state = "ID";
                }
                continue;
            }
          }
        } catch (e) {
          self2.reportOrThrowError(e);
          if (self2.state === "CUETEXT" && self2.cue && self2.oncue) {
            self2.oncue(self2.cue);
          }
          self2.cue = null;
          self2.state = self2.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
        }
        return this;
      },
      flush: function() {
        var self2 = this;
        try {
          self2.buffer += self2.decoder.decode();
          if (self2.cue || self2.state === "HEADER") {
            self2.buffer += "\n\n";
            self2.parse();
          }
          if (self2.state === "INITIAL") {
            throw new ParsingError(ParsingError.Errors.BadSignature);
          }
        } catch (e) {
          self2.reportOrThrowError(e);
        }
        self2.onflush && self2.onflush();
        return this;
      }
    };
    module.exports = WebVTT2;
  }
});

// node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/vttcue.js
var require_vttcue = __commonJS({
  "node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/vttcue.js"(exports, module) {
    var autoKeyword = "auto";
    var directionSetting = {
      "": 1,
      "lr": 1,
      "rl": 1
    };
    var alignSetting = {
      "start": 1,
      "center": 1,
      "end": 1,
      "left": 1,
      "right": 1,
      "auto": 1,
      "line-left": 1,
      "line-right": 1
    };
    function findDirectionSetting(value) {
      if (typeof value !== "string") {
        return false;
      }
      var dir = directionSetting[value.toLowerCase()];
      return dir ? value.toLowerCase() : false;
    }
    function findAlignSetting(value) {
      if (typeof value !== "string") {
        return false;
      }
      var align = alignSetting[value.toLowerCase()];
      return align ? value.toLowerCase() : false;
    }
    function VTTCue3(startTime, endTime, text) {
      this.hasBeenReset = false;
      var _id = "";
      var _pauseOnExit = false;
      var _startTime = startTime;
      var _endTime = endTime;
      var _text = text;
      var _region = null;
      var _vertical = "";
      var _snapToLines = true;
      var _line = "auto";
      var _lineAlign = "start";
      var _position = "auto";
      var _positionAlign = "auto";
      var _size = 100;
      var _align = "center";
      Object.defineProperties(this, {
        "id": {
          enumerable: true,
          get: function() {
            return _id;
          },
          set: function(value) {
            _id = "" + value;
          }
        },
        "pauseOnExit": {
          enumerable: true,
          get: function() {
            return _pauseOnExit;
          },
          set: function(value) {
            _pauseOnExit = !!value;
          }
        },
        "startTime": {
          enumerable: true,
          get: function() {
            return _startTime;
          },
          set: function(value) {
            if (typeof value !== "number") {
              throw new TypeError("Start time must be set to a number.");
            }
            _startTime = value;
            this.hasBeenReset = true;
          }
        },
        "endTime": {
          enumerable: true,
          get: function() {
            return _endTime;
          },
          set: function(value) {
            if (typeof value !== "number") {
              throw new TypeError("End time must be set to a number.");
            }
            _endTime = value;
            this.hasBeenReset = true;
          }
        },
        "text": {
          enumerable: true,
          get: function() {
            return _text;
          },
          set: function(value) {
            _text = "" + value;
            this.hasBeenReset = true;
          }
        },
        "region": {
          enumerable: true,
          get: function() {
            return _region;
          },
          set: function(value) {
            _region = value;
            this.hasBeenReset = true;
          }
        },
        "vertical": {
          enumerable: true,
          get: function() {
            return _vertical;
          },
          set: function(value) {
            var setting = findDirectionSetting(value);
            if (setting === false) {
              throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");
            }
            _vertical = setting;
            this.hasBeenReset = true;
          }
        },
        "snapToLines": {
          enumerable: true,
          get: function() {
            return _snapToLines;
          },
          set: function(value) {
            _snapToLines = !!value;
            this.hasBeenReset = true;
          }
        },
        "line": {
          enumerable: true,
          get: function() {
            return _line;
          },
          set: function(value) {
            if (typeof value !== "number" && value !== autoKeyword) {
              throw new SyntaxError("Line: an invalid number or illegal string was specified.");
            }
            _line = value;
            this.hasBeenReset = true;
          }
        },
        "lineAlign": {
          enumerable: true,
          get: function() {
            return _lineAlign;
          },
          set: function(value) {
            var setting = findAlignSetting(value);
            if (!setting) {
              console.warn("lineAlign: an invalid or illegal string was specified.");
            } else {
              _lineAlign = setting;
              this.hasBeenReset = true;
            }
          }
        },
        "position": {
          enumerable: true,
          get: function() {
            return _position;
          },
          set: function(value) {
            if (value < 0 || value > 100) {
              throw new Error("Position must be between 0 and 100.");
            }
            _position = value;
            this.hasBeenReset = true;
          }
        },
        "positionAlign": {
          enumerable: true,
          get: function() {
            return _positionAlign;
          },
          set: function(value) {
            var setting = findAlignSetting(value);
            if (!setting) {
              console.warn("positionAlign: an invalid or illegal string was specified.");
            } else {
              _positionAlign = setting;
              this.hasBeenReset = true;
            }
          }
        },
        "size": {
          enumerable: true,
          get: function() {
            return _size;
          },
          set: function(value) {
            if (value < 0 || value > 100) {
              throw new Error("Size must be between 0 and 100.");
            }
            _size = value;
            this.hasBeenReset = true;
          }
        },
        "align": {
          enumerable: true,
          get: function() {
            return _align;
          },
          set: function(value) {
            var setting = findAlignSetting(value);
            if (!setting) {
              throw new SyntaxError("align: an invalid or illegal alignment string was specified.");
            }
            _align = setting;
            this.hasBeenReset = true;
          }
        }
      });
      this.displayState = void 0;
    }
    VTTCue3.prototype.getCueAsHTML = function() {
      return WebVTT.convertCueToDOMTree(window, this.text);
    };
    module.exports = VTTCue3;
  }
});

// node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/vttregion.js
var require_vttregion = __commonJS({
  "node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/vttregion.js"(exports, module) {
    var scrollSetting = {
      "": true,
      "up": true
    };
    function findScrollSetting(value) {
      if (typeof value !== "string") {
        return false;
      }
      var scroll = scrollSetting[value.toLowerCase()];
      return scroll ? value.toLowerCase() : false;
    }
    function isValidPercentValue(value) {
      return typeof value === "number" && value >= 0 && value <= 100;
    }
    function VTTRegion() {
      var _width = 100;
      var _lines = 3;
      var _regionAnchorX = 0;
      var _regionAnchorY = 100;
      var _viewportAnchorX = 0;
      var _viewportAnchorY = 100;
      var _scroll = "";
      Object.defineProperties(this, {
        "width": {
          enumerable: true,
          get: function() {
            return _width;
          },
          set: function(value) {
            if (!isValidPercentValue(value)) {
              throw new Error("Width must be between 0 and 100.");
            }
            _width = value;
          }
        },
        "lines": {
          enumerable: true,
          get: function() {
            return _lines;
          },
          set: function(value) {
            if (typeof value !== "number") {
              throw new TypeError("Lines must be set to a number.");
            }
            _lines = value;
          }
        },
        "regionAnchorY": {
          enumerable: true,
          get: function() {
            return _regionAnchorY;
          },
          set: function(value) {
            if (!isValidPercentValue(value)) {
              throw new Error("RegionAnchorX must be between 0 and 100.");
            }
            _regionAnchorY = value;
          }
        },
        "regionAnchorX": {
          enumerable: true,
          get: function() {
            return _regionAnchorX;
          },
          set: function(value) {
            if (!isValidPercentValue(value)) {
              throw new Error("RegionAnchorY must be between 0 and 100.");
            }
            _regionAnchorX = value;
          }
        },
        "viewportAnchorY": {
          enumerable: true,
          get: function() {
            return _viewportAnchorY;
          },
          set: function(value) {
            if (!isValidPercentValue(value)) {
              throw new Error("ViewportAnchorY must be between 0 and 100.");
            }
            _viewportAnchorY = value;
          }
        },
        "viewportAnchorX": {
          enumerable: true,
          get: function() {
            return _viewportAnchorX;
          },
          set: function(value) {
            if (!isValidPercentValue(value)) {
              throw new Error("ViewportAnchorX must be between 0 and 100.");
            }
            _viewportAnchorX = value;
          }
        },
        "scroll": {
          enumerable: true,
          get: function() {
            return _scroll;
          },
          set: function(value) {
            var setting = findScrollSetting(value);
            if (setting === false) {
              console.warn("Scroll: an invalid or illegal string was specified.");
            } else {
              _scroll = setting;
            }
          }
        }
      });
    }
    module.exports = VTTRegion;
  }
});

// node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/browser-index.js
var require_browser_index = __commonJS({
  "node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/browser-index.js"(exports, module) {
    var window7 = require_window();
    var vttjs = module.exports = {
      WebVTT: require_vtt(),
      VTTCue: require_vttcue(),
      VTTRegion: require_vttregion()
    };
    window7.vttjs = vttjs;
    window7.WebVTT = vttjs.WebVTT;
    var cueShim = vttjs.VTTCue;
    var regionShim = vttjs.VTTRegion;
    var nativeVTTCue = window7.VTTCue;
    var nativeVTTRegion = window7.VTTRegion;
    vttjs.shim = function() {
      window7.VTTCue = cueShim;
      window7.VTTRegion = regionShim;
    };
    vttjs.restore = function() {
      window7.VTTCue = nativeVTTCue;
      window7.VTTRegion = nativeVTTRegion;
    };
    if (!window7.VTTCue) {
      vttjs.shim();
    }
  }
});

// node_modules/.pnpm/url-toolkit@2.2.5/node_modules/url-toolkit/src/url-toolkit.js
var require_url_toolkit = __commonJS({
  "node_modules/.pnpm/url-toolkit@2.2.5/node_modules/url-toolkit/src/url-toolkit.js"(exports, module) {
    (function(root) {
      var URL_REGEX = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
      var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
      var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
      var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
      var URLToolkit2 = {
        // 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(baseURL, relativeURL, opts) {
          opts = opts || {};
          baseURL = baseURL.trim();
          relativeURL = relativeURL.trim();
          if (!relativeURL) {
            if (!opts.alwaysNormalize) {
              return baseURL;
            }
            var basePartsForNormalise = URLToolkit2.parseURL(baseURL);
            if (!basePartsForNormalise) {
              throw new Error("Error trying to parse base URL.");
            }
            basePartsForNormalise.path = URLToolkit2.normalizePath(basePartsForNormalise.path);
            return URLToolkit2.buildURLFromParts(basePartsForNormalise);
          }
          var relativeParts = URLToolkit2.parseURL(relativeURL);
          if (!relativeParts) {
            throw new Error("Error trying to parse relative URL.");
          }
          if (relativeParts.scheme) {
            if (!opts.alwaysNormalize) {
              return relativeURL;
            }
            relativeParts.path = URLToolkit2.normalizePath(relativeParts.path);
            return URLToolkit2.buildURLFromParts(relativeParts);
          }
          var baseParts = URLToolkit2.parseURL(baseURL);
          if (!baseParts) {
            throw new Error("Error trying to parse base URL.");
          }
          if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== "/") {
            var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
            baseParts.netLoc = pathParts[1];
            baseParts.path = pathParts[2];
          }
          if (baseParts.netLoc && !baseParts.path) {
            baseParts.path = "/";
          }
          var builtParts = {
            // 2c) Otherwise, the embedded URL inherits the scheme of
            // the base URL.
            scheme: baseParts.scheme,
            netLoc: relativeParts.netLoc,
            path: null,
            params: relativeParts.params,
            query: relativeParts.query,
            fragment: relativeParts.fragment
          };
          if (!relativeParts.netLoc) {
            builtParts.netLoc = baseParts.netLoc;
            if (relativeParts.path[0] !== "/") {
              if (!relativeParts.path) {
                builtParts.path = baseParts.path;
                if (!relativeParts.params) {
                  builtParts.params = baseParts.params;
                  if (!relativeParts.query) {
                    builtParts.query = baseParts.query;
                  }
                }
              } else {
                var baseURLPath = baseParts.path;
                var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf("/") + 1) + relativeParts.path;
                builtParts.path = URLToolkit2.normalizePath(newPath);
              }
            }
          }
          if (builtParts.path === null) {
            builtParts.path = opts.alwaysNormalize ? URLToolkit2.normalizePath(relativeParts.path) : relativeParts.path;
          }
          return URLToolkit2.buildURLFromParts(builtParts);
        },
        parseURL: function(url) {
          var parts = URL_REGEX.exec(url);
          if (!parts) {
            return null;
          }
          return {
            scheme: parts[1] || "",
            netLoc: parts[2] || "",
            path: parts[3] || "",
            params: parts[4] || "",
            query: parts[5] || "",
            fragment: parts[6] || ""
          };
        },
        normalizePath: function(path) {
          path = path.split("").reverse().join("").replace(SLASH_DOT_REGEX, "");
          while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, "")).length) {
          }
          return path.split("").reverse().join("");
        },
        buildURLFromParts: function(parts) {
          return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
        }
      };
      if (typeof exports === "object" && typeof module === "object") module.exports = URLToolkit2;
      else if (typeof define === "function" && define.amd) define([], function() {
        return URLToolkit2;
      });
      else if (typeof exports === "object") exports["URLToolkit"] = URLToolkit2;
      else root["URLToolkit"] = URLToolkit2;
    })(exports);
  }
});

// node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/conventions.js
var require_conventions = __commonJS({
  "node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/conventions.js"(exports) {
    "use strict";
    function find(list, predicate, ac) {
      if (ac === void 0) {
        ac = Array.prototype;
      }
      if (list && typeof ac.find === "function") {
        return ac.find.call(list, predicate);
      }
      for (var i = 0; i < list.length; i++) {
        if (Object.prototype.hasOwnProperty.call(list, i)) {
          var item = list[i];
          if (predicate.call(void 0, item, i, list)) {
            return item;
          }
        }
      }
    }
    function freeze(object, oc) {
      if (oc === void 0) {
        oc = Object;
      }
      return oc && typeof oc.freeze === "function" ? oc.freeze(object) : object;
    }
    var MIME_TYPE = freeze({
      /**
       * `text/html`, the only mime type that triggers treating an XML document as HTML.
       *
       * @see DOMParser.SupportedType.isHTML
       * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
       * @see https://en.wikipedia.org/wiki/HTML Wikipedia
       * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
       * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec
       */
      HTML: "text/html",
      /**
       * Helper method to check a mime type if it indicates an HTML document
       *
       * @param {string} [value]
       * @returns {boolean}
       *
       * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
       * @see https://en.wikipedia.org/wiki/HTML Wikipedia
       * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
       * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring 	 */
      isHTML: function(value) {
        return value === MIME_TYPE.HTML;
      },
      /**
       * `application/xml`, the standard mime type for XML documents.
       *
       * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration
       * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303
       * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
       */
      XML_APPLICATION: "application/xml",
      /**
       * `text/html`, an alias for `application/xml`.
       *
       * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303
       * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration
       * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
       */
      XML_TEXT: "text/xml",
      /**
       * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace,
       * but is parsed as an XML document.
       *
       * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration
       * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec
       * @see https://en.wikipedia.org/wiki/XHTML Wikipedia
       */
      XML_XHTML_APPLICATION: "application/xhtml+xml",
      /**
       * `image/svg+xml`,
       *
       * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration
       * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1
       * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia
       */
      XML_SVG_IMAGE: "image/svg+xml"
    });
    var NAMESPACE = freeze({
      /**
       * The XHTML namespace.
       *
       * @see http://www.w3.org/1999/xhtml
       */
      HTML: "http://www.w3.org/1999/xhtml",
      /**
       * Checks if `uri` equals `NAMESPACE.HTML`.
       *
       * @param {string} [uri]
       *
       * @see NAMESPACE.HTML
       */
      isHTML: function(uri) {
        return uri === NAMESPACE.HTML;
      },
      /**
       * The SVG namespace.
       *
       * @see http://www.w3.org/2000/svg
       */
      SVG: "http://www.w3.org/2000/svg",
      /**
       * The `xml:` namespace.
       *
       * @see http://www.w3.org/XML/1998/namespace
       */
      XML: "http://www.w3.org/XML/1998/namespace",
      /**
       * The `xmlns:` namespace
       *
       * @see https://www.w3.org/2000/xmlns/
       */
      XMLNS: "http://www.w3.org/2000/xmlns/"
    });
    exports.find = find;
    exports.freeze = freeze;
    exports.MIME_TYPE = MIME_TYPE;
    exports.NAMESPACE = NAMESPACE;
  }
});

// node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/dom.js
var require_dom = __commonJS({
  "node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/dom.js"(exports) {
    var conventions = require_conventions();
    var find = conventions.find;
    var NAMESPACE = conventions.NAMESPACE;
    function notEmptyString(input) {
      return input !== "";
    }
    function splitOnASCIIWhitespace(input) {
      return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : [];
    }
    function orderedSetReducer(current, element) {
      if (!current.hasOwnProperty(element)) {
        current[element] = true;
      }
      return current;
    }
    function toOrderedSet(input) {
      if (!input) return [];
      var list = splitOnASCIIWhitespace(input);
      return Object.keys(list.reduce(orderedSetReducer, {}));
    }
    function arrayIncludes(list) {
      return function(element) {
        return list && list.indexOf(element) !== -1;
      };
    }
    function copy(src, dest) {
      for (var p in src) {
        if (Object.prototype.hasOwnProperty.call(src, p)) {
          dest[p] = src[p];
        }
      }
    }
    function _extends3(Class, Super) {
      var pt = Class.prototype;
      if (!(pt instanceof Super)) {
        let t3 = function() {
        };
        var t2 = t3;
        ;
        t3.prototype = Super.prototype;
        t3 = new t3();
        copy(pt, t3);
        Class.prototype = pt = t3;
      }
      if (pt.constructor != Class) {
        if (typeof Class != "function") {
          console.error("unknown Class:" + Class);
        }
        pt.constructor = Class;
      }
    }
    var NodeType = {};
    var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
    var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
    var TEXT_NODE = NodeType.TEXT_NODE = 3;
    var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
    var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
    var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
    var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
    var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
    var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
    var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
    var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
    var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
    var ExceptionCode = {};
    var ExceptionMessage = {};
    var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = (ExceptionMessage[1] = "Index size error", 1);
    var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = (ExceptionMessage[2] = "DOMString size error", 2);
    var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = (ExceptionMessage[3] = "Hierarchy request error", 3);
    var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = (ExceptionMessage[4] = "Wrong document", 4);
    var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = (ExceptionMessage[5] = "Invalid character", 5);
    var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = (ExceptionMessage[6] = "No data allowed", 6);
    var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = (ExceptionMessage[7] = "No modification allowed", 7);
    var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = (ExceptionMessage[8] = "Not found", 8);
    var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = (ExceptionMessage[9] = "Not supported", 9);
    var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = (ExceptionMessage[10] = "Attribute in use", 10);
    var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = (ExceptionMessage[11] = "Invalid state", 11);
    var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = (ExceptionMessage[12] = "Syntax error", 12);
    var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = (ExceptionMessage[13] = "Invalid modification", 13);
    var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = (ExceptionMessage[14] = "Invalid namespace", 14);
    var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = (ExceptionMessage[15] = "Invalid access", 15);
    function DOMException2(code, message) {
      if (message instanceof Error) {
        var error = message;
      } else {
        error = this;
        Error.call(this, ExceptionMessage[code]);
        this.message = ExceptionMessage[code];
        if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException2);
      }
      error.code = code;
      if (message) this.message = this.message + ": " + message;
      return error;
    }
    DOMException2.prototype = Error.prototype;
    copy(ExceptionCode, DOMException2);
    function NodeList() {
    }
    NodeList.prototype = {
      /**
       * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
       * @standard level1
       */
      length: 0,
      /**
       * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
       * @standard level1
       * @param index  unsigned long
       *   Index into the collection.
       * @return Node
       * 	The node at the indexth position in the NodeList, or null if that is not a valid index.
       */
      item: function(index) {
        return index >= 0 && index < this.length ? this[index] : null;
      },
      toString: function(isHTML, nodeFilter) {
        for (var buf = [], i = 0; i < this.length; i++) {
          serializeToString(this[i], buf, isHTML, nodeFilter);
        }
        return buf.join("");
      },
      /**
       * @private
       * @param {function (Node):boolean} predicate
       * @returns {Node[]}
       */
      filter: function(predicate) {
        return Array.prototype.filter.call(this, predicate);
      },
      /**
       * @private
       * @param {Node} item
       * @returns {number}
       */
      indexOf: function(item) {
        return Array.prototype.indexOf.call(this, item);
      }
    };
    function LiveNodeList(node, refresh) {
      this._node = node;
      this._refresh = refresh;
      _updateLiveList(this);
    }
    function _updateLiveList(list) {
      var inc = list._node._inc || list._node.ownerDocument._inc;
      if (list._inc !== inc) {
        var ls = list._refresh(list._node);
        __set__(list, "length", ls.length);
        if (!list.$$length || ls.length < list.$$length) {
          for (var i = ls.length; i in list; i++) {
            if (Object.prototype.hasOwnProperty.call(list, i)) {
              delete list[i];
            }
          }
        }
        copy(ls, list);
        list._inc = inc;
      }
    }
    LiveNodeList.prototype.item = function(i) {
      _updateLiveList(this);
      return this[i] || null;
    };
    _extends3(LiveNodeList, NodeList);
    function NamedNodeMap() {
    }
    function _findNodeIndex(list, node) {
      var i = list.length;
      while (i--) {
        if (list[i] === node) {
          return i;
        }
      }
    }
    function _addNamedNode(el, list, newAttr, oldAttr) {
      if (oldAttr) {
        list[_findNodeIndex(list, oldAttr)] = newAttr;
      } else {
        list[list.length++] = newAttr;
      }
      if (el) {
        newAttr.ownerElement = el;
        var doc = el.ownerDocument;
        if (doc) {
          oldAttr && _onRemoveAttribute(doc, el, oldAttr);
          _onAddAttribute(doc, el, newAttr);
        }
      }
    }
    function _removeNamedNode(el, list, attr) {
      var i = _findNodeIndex(list, attr);
      if (i >= 0) {
        var lastIndex = list.length - 1;
        while (i < lastIndex) {
          list[i] = list[++i];
        }
        list.length = lastIndex;
        if (el) {
          var doc = el.ownerDocument;
          if (doc) {
            _onRemoveAttribute(doc, el, attr);
            attr.ownerElement = null;
          }
        }
      } else {
        throw new DOMException2(NOT_FOUND_ERR, new Error(el.tagName + "@" + attr));
      }
    }
    NamedNodeMap.prototype = {
      length: 0,
      item: NodeList.prototype.item,
      getNamedItem: function(key) {
        var i = this.length;
        while (i--) {
          var attr = this[i];
          if (attr.nodeName == key) {
            return attr;
          }
        }
      },
      setNamedItem: function(attr) {
        var el = attr.ownerElement;
        if (el && el != this._ownerElement) {
          throw new DOMException2(INUSE_ATTRIBUTE_ERR);
        }
        var oldAttr = this.getNamedItem(attr.nodeName);
        _addNamedNode(this._ownerElement, this, attr, oldAttr);
        return oldAttr;
      },
      /* returns Node */
      setNamedItemNS: function(attr) {
        var el = attr.ownerElement, oldAttr;
        if (el && el != this._ownerElement) {
          throw new DOMException2(INUSE_ATTRIBUTE_ERR);
        }
        oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName);
        _addNamedNode(this._ownerElement, this, attr, oldAttr);
        return oldAttr;
      },
      /* returns Node */
      removeNamedItem: function(key) {
        var attr = this.getNamedItem(key);
        _removeNamedNode(this._ownerElement, this, attr);
        return attr;
      },
      // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
      //for level2
      removeNamedItemNS: function(namespaceURI, localName) {
        var attr = this.getNamedItemNS(namespaceURI, localName);
        _removeNamedNode(this._ownerElement, this, attr);
        return attr;
      },
      getNamedItemNS: function(namespaceURI, localName) {
        var i = this.length;
        while (i--) {
          var node = this[i];
          if (node.localName == localName && node.namespaceURI == namespaceURI) {
            return node;
          }
        }
        return null;
      }
    };
    function DOMImplementation() {
    }
    DOMImplementation.prototype = {
      /**
       * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported.
       * The different implementations fairly diverged in what kind of features were reported.
       * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use.
       *
       * @deprecated It is deprecated and modern browsers return true in all cases.
       *
       * @param {string} feature
       * @param {string} [version]
       * @returns {boolean} always true
       *
       * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN
       * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core
       * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard
       */
      hasFeature: function(feature, version6) {
        return true;
      },
      /**
       * Creates an XML Document object of the specified type with its document element.
       *
       * __It behaves slightly different from the description in the living standard__:
       * - There is no interface/class `XMLDocument`, it returns a `Document` instance.
       * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared.
       * - this implementation is not validating names or qualified names
       *   (when parsing XML strings, the SAX parser takes care of that)
       *
       * @param {string|null} namespaceURI
       * @param {string} qualifiedName
       * @param {DocumentType=null} doctype
       * @returns {Document}
       *
       * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN
       * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial)
       * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument  DOM Level 2 Core
       *
       * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
       * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
       * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
       */
      createDocument: function(namespaceURI, qualifiedName, doctype) {
        var doc = new Document2();
        doc.implementation = this;
        doc.childNodes = new NodeList();
        doc.doctype = doctype || null;
        if (doctype) {
          doc.appendChild(doctype);
        }
        if (qualifiedName) {
          var root = doc.createElementNS(namespaceURI, qualifiedName);
          doc.appendChild(root);
        }
        return doc;
      },
      /**
       * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`.
       *
       * __This behavior is slightly different from the in the specs__:
       * - this implementation is not validating names or qualified names
       *   (when parsing XML strings, the SAX parser takes care of that)
       *
       * @param {string} qualifiedName
       * @param {string} [publicId]
       * @param {string} [systemId]
       * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation
       * 				  or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()`
       *
       * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN
       * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core
       * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard
       *
       * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
       * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
       * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
       */
      createDocumentType: function(qualifiedName, publicId, systemId) {
        var node = new DocumentType();
        node.name = qualifiedName;
        node.nodeName = qualifiedName;
        node.publicId = publicId || "";
        node.systemId = systemId || "";
        return node;
      }
    };
    function Node() {
    }
    Node.prototype = {
      firstChild: null,
      lastChild: null,
      previousSibling: null,
      nextSibling: null,
      attributes: null,
      parentNode: null,
      childNodes: null,
      ownerDocument: null,
      nodeValue: null,
      namespaceURI: null,
      prefix: null,
      localName: null,
      // Modified in DOM Level 2:
      insertBefore: function(newChild, refChild) {
        return _insertBefore(this, newChild, refChild);
      },
      replaceChild: function(newChild, oldChild) {
        _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
        if (oldChild) {
          this.removeChild(oldChild);
        }
      },
      removeChild: function(oldChild) {
        return _removeChild(this, oldChild);
      },
      appendChild: function(newChild) {
        return this.insertBefore(newChild, null);
      },
      hasChildNodes: function() {
        return this.firstChild != null;
      },
      cloneNode: function(deep) {
        return cloneNode(this.ownerDocument || this, this, deep);
      },
      // Modified in DOM Level 2:
      normalize: function() {
        var child = this.firstChild;
        while (child) {
          var next = child.nextSibling;
          if (next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE) {
            this.removeChild(next);
            child.appendData(next.data);
          } else {
            child.normalize();
            child = next;
          }
        }
      },
      // Introduced in DOM Level 2:
      isSupported: function(feature, version6) {
        return this.ownerDocument.implementation.hasFeature(feature, version6);
      },
      // Introduced in DOM Level 2:
      hasAttributes: function() {
        return this.attributes.length > 0;
      },
      /**
       * Look up the prefix associated to the given namespace URI, starting from this node.
       * **The default namespace declarations are ignored by this method.**
       * See Namespace Prefix Lookup for details on the algorithm used by this method.
       *
       * _Note: The implementation seems to be incomplete when compared to the algorithm described in the specs._
       *
       * @param {string | null} namespaceURI
       * @returns {string | null}
       * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix
       * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo
       * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix
       * @see https://github.com/xmldom/xmldom/issues/322
       */
      lookupPrefix: function(namespaceURI) {
        var el = this;
        while (el) {
          var map = el._nsMap;
          if (map) {
            for (var n in map) {
              if (Object.prototype.hasOwnProperty.call(map, n) && map[n] === namespaceURI) {
                return n;
              }
            }
          }
          el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
        }
        return null;
      },
      // Introduced in DOM Level 3:
      lookupNamespaceURI: function(prefix) {
        var el = this;
        while (el) {
          var map = el._nsMap;
          if (map) {
            if (prefix in map) {
              if (Object.prototype.hasOwnProperty.call(map, prefix)) {
                return map[prefix];
              }
            }
          }
          el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
        }
        return null;
      },
      // Introduced in DOM Level 3:
      isDefaultNamespace: function(namespaceURI) {
        var prefix = this.lookupPrefix(namespaceURI);
        return prefix == null;
      }
    };
    function _xmlEncoder(c) {
      return c == "<" && "&lt;" || c == ">" && "&gt;" || c == "&" && "&amp;" || c == '"' && "&quot;" || "&#" + c.charCodeAt() + ";";
    }
    copy(NodeType, Node);
    copy(NodeType, Node.prototype);
    function _visitNode(node, callback2) {
      if (callback2(node)) {
        return true;
      }
      if (node = node.firstChild) {
        do {
          if (_visitNode(node, callback2)) {
            return true;
          }
        } while (node = node.nextSibling);
      }
    }
    function Document2() {
      this.ownerDocument = this;
    }
    function _onAddAttribute(doc, el, newAttr) {
      doc && doc._inc++;
      var ns = newAttr.namespaceURI;
      if (ns === NAMESPACE.XMLNS) {
        el._nsMap[newAttr.prefix ? newAttr.localName : ""] = newAttr.value;
      }
    }
    function _onRemoveAttribute(doc, el, newAttr, remove2) {
      doc && doc._inc++;
      var ns = newAttr.namespaceURI;
      if (ns === NAMESPACE.XMLNS) {
        delete el._nsMap[newAttr.prefix ? newAttr.localName : ""];
      }
    }
    function _onUpdateChild(doc, el, newChild) {
      if (doc && doc._inc) {
        doc._inc++;
        var cs = el.childNodes;
        if (newChild) {
          cs[cs.length++] = newChild;
        } else {
          var child = el.firstChild;
          var i = 0;
          while (child) {
            cs[i++] = child;
            child = child.nextSibling;
          }
          cs.length = i;
          delete cs[cs.length];
        }
      }
    }
    function _removeChild(parentNode, child) {
      var previous = child.previousSibling;
      var next = child.nextSibling;
      if (previous) {
        previous.nextSibling = next;
      } else {
        parentNode.firstChild = next;
      }
      if (next) {
        next.previousSibling = previous;
      } else {
        parentNode.lastChild = previous;
      }
      child.parentNode = null;
      child.previousSibling = null;
      child.nextSibling = null;
      _onUpdateChild(parentNode.ownerDocument, parentNode);
      return child;
    }
    function hasValidParentNodeType(node) {
      return node && (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE);
    }
    function hasInsertableNodeType(node) {
      return node && (isElementNode(node) || isTextNode2(node) || isDocTypeNode(node) || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.COMMENT_NODE || node.nodeType === Node.PROCESSING_INSTRUCTION_NODE);
    }
    function isDocTypeNode(node) {
      return node && node.nodeType === Node.DOCUMENT_TYPE_NODE;
    }
    function isElementNode(node) {
      return node && node.nodeType === Node.ELEMENT_NODE;
    }
    function isTextNode2(node) {
      return node && node.nodeType === Node.TEXT_NODE;
    }
    function isElementInsertionPossible(doc, child) {
      var parentChildNodes = doc.childNodes || [];
      if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) {
        return false;
      }
      var docTypeNode = find(parentChildNodes, isDocTypeNode);
      return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
    }
    function isElementReplacementPossible(doc, child) {
      var parentChildNodes = doc.childNodes || [];
      function hasElementChildThatIsNotChild(node) {
        return isElementNode(node) && node !== child;
      }
      if (find(parentChildNodes, hasElementChildThatIsNotChild)) {
        return false;
      }
      var docTypeNode = find(parentChildNodes, isDocTypeNode);
      return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
    }
    function assertPreInsertionValidity1to5(parent, node, child) {
      if (!hasValidParentNodeType(parent)) {
        throw new DOMException2(HIERARCHY_REQUEST_ERR, "Unexpected parent node type " + parent.nodeType);
      }
      if (child && child.parentNode !== parent) {
        throw new DOMException2(NOT_FOUND_ERR, "child not in parent");
      }
      if (
        // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
        !hasInsertableNodeType(node) || // 5. If either `node` is a Text node and `parent` is a document,
        // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0
        // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE)
        // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException.
        isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE
      ) {
        throw new DOMException2(HIERARCHY_REQUEST_ERR, "Unexpected node type " + node.nodeType + " for parent node type " + parent.nodeType);
      }
    }
    function assertPreInsertionValidityInDocument(parent, node, child) {
      var parentChildNodes = parent.childNodes || [];
      var nodeChildNodes = node.childNodes || [];
      if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
        var nodeChildElements = nodeChildNodes.filter(isElementNode);
        if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode2)) {
          throw new DOMException2(HIERARCHY_REQUEST_ERR, "More than one element or text in fragment");
        }
        if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) {
          throw new DOMException2(HIERARCHY_REQUEST_ERR, "Element in fragment can not be inserted before doctype");
        }
      }
      if (isElementNode(node)) {
        if (!isElementInsertionPossible(parent, child)) {
          throw new DOMException2(HIERARCHY_REQUEST_ERR, "Only one element can be added and only after doctype");
        }
      }
      if (isDocTypeNode(node)) {
        if (find(parentChildNodes, isDocTypeNode)) {
          throw new DOMException2(HIERARCHY_REQUEST_ERR, "Only one doctype is allowed");
        }
        var parentElementChild = find(parentChildNodes, isElementNode);
        if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
          throw new DOMException2(HIERARCHY_REQUEST_ERR, "Doctype can only be inserted before an element");
        }
        if (!child && parentElementChild) {
          throw new DOMException2(HIERARCHY_REQUEST_ERR, "Doctype can not be appended since element is present");
        }
      }
    }
    function assertPreReplacementValidityInDocument(parent, node, child) {
      var parentChildNodes = parent.childNodes || [];
      var nodeChildNodes = node.childNodes || [];
      if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
        var nodeChildElements = nodeChildNodes.filter(isElementNode);
        if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode2)) {
          throw new DOMException2(HIERARCHY_REQUEST_ERR, "More than one element or text in fragment");
        }
        if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) {
          throw new DOMException2(HIERARCHY_REQUEST_ERR, "Element in fragment can not be inserted before doctype");
        }
      }
      if (isElementNode(node)) {
        if (!isElementReplacementPossible(parent, child)) {
          throw new DOMException2(HIERARCHY_REQUEST_ERR, "Only one element can be added and only after doctype");
        }
      }
      if (isDocTypeNode(node)) {
        let hasDoctypeChildThatIsNotChild2 = function(node2) {
          return isDocTypeNode(node2) && node2 !== child;
        };
        var hasDoctypeChildThatIsNotChild = hasDoctypeChildThatIsNotChild2;
        if (find(parentChildNodes, hasDoctypeChildThatIsNotChild2)) {
          throw new DOMException2(HIERARCHY_REQUEST_ERR, "Only one doctype is allowed");
        }
        var parentElementChild = find(parentChildNodes, isElementNode);
        if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
          throw new DOMException2(HIERARCHY_REQUEST_ERR, "Doctype can only be inserted before an element");
        }
      }
    }
    function _insertBefore(parent, node, child, _inDocumentAssertion) {
      assertPreInsertionValidity1to5(parent, node, child);
      if (parent.nodeType === Node.DOCUMENT_NODE) {
        (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child);
      }
      var cp = node.parentNode;
      if (cp) {
        cp.removeChild(node);
      }
      if (node.nodeType === DOCUMENT_FRAGMENT_NODE) {
        var newFirst = node.firstChild;
        if (newFirst == null) {
          return node;
        }
        var newLast = node.lastChild;
      } else {
        newFirst = newLast = node;
      }
      var pre = child ? child.previousSibling : parent.lastChild;
      newFirst.previousSibling = pre;
      newLast.nextSibling = child;
      if (pre) {
        pre.nextSibling = newFirst;
      } else {
        parent.firstChild = newFirst;
      }
      if (child == null) {
        parent.lastChild = newLast;
      } else {
        child.previousSibling = newLast;
      }
      do {
        newFirst.parentNode = parent;
      } while (newFirst !== newLast && (newFirst = newFirst.nextSibling));
      _onUpdateChild(parent.ownerDocument || parent, parent);
      if (node.nodeType == DOCUMENT_FRAGMENT_NODE) {
        node.firstChild = node.lastChild = null;
      }
      return node;
    }
    function _appendSingleChild(parentNode, newChild) {
      if (newChild.parentNode) {
        newChild.parentNode.removeChild(newChild);
      }
      newChild.parentNode = parentNode;
      newChild.previousSibling = parentNode.lastChild;
      newChild.nextSibling = null;
      if (newChild.previousSibling) {
        newChild.previousSibling.nextSibling = newChild;
      } else {
        parentNode.firstChild = newChild;
      }
      parentNode.lastChild = newChild;
      _onUpdateChild(parentNode.ownerDocument, parentNode, newChild);
      return newChild;
    }
    Document2.prototype = {
      //implementation : null,
      nodeName: "#document",
      nodeType: DOCUMENT_NODE,
      /**
       * The DocumentType node of the document.
       *
       * @readonly
       * @type DocumentType
       */
      doctype: null,
      documentElement: null,
      _inc: 1,
      insertBefore: function(newChild, refChild) {
        if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
          var child = newChild.firstChild;
          while (child) {
            var next = child.nextSibling;
            this.insertBefore(child, refChild);
            child = next;
          }
          return newChild;
        }
        _insertBefore(this, newChild, refChild);
        newChild.ownerDocument = this;
        if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) {
          this.documentElement = newChild;
        }
        return newChild;
      },
      removeChild: function(oldChild) {
        if (this.documentElement == oldChild) {
          this.documentElement = null;
        }
        return _removeChild(this, oldChild);
      },
      replaceChild: function(newChild, oldChild) {
        _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
        newChild.ownerDocument = this;
        if (oldChild) {
          this.removeChild(oldChild);
        }
        if (isElementNode(newChild)) {
          this.documentElement = newChild;
        }
      },
      // Introduced in DOM Level 2:
      importNode: function(importedNode, deep) {
        return importNode(this, importedNode, deep);
      },
      // Introduced in DOM Level 2:
      getElementById: function(id) {
        var rtv = null;
        _visitNode(this.documentElement, function(node) {
          if (node.nodeType == ELEMENT_NODE) {
            if (node.getAttribute("id") == id) {
              rtv = node;
              return true;
            }
          }
        });
        return rtv;
      },
      /**
       * The `getElementsByClassName` method of `Document` interface returns an array-like object
       * of all child elements which have **all** of the given class name(s).
       *
       * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters.
       *
       *
       * Warning: This is a live LiveNodeList.
       * Changes in the DOM will reflect in the array as the changes occur.
       * If an element selected by this array no longer qualifies for the selector,
       * it will automatically be removed. Be aware of this for iteration purposes.
       *
       * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace
       *
       * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
       * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname
       */
      getElementsByClassName: function(classNames) {
        var classNamesSet = toOrderedSet(classNames);
        return new LiveNodeList(this, function(base) {
          var ls = [];
          if (classNamesSet.length > 0) {
            _visitNode(base.documentElement, function(node) {
              if (node !== base && node.nodeType === ELEMENT_NODE) {
                var nodeClassNames = node.getAttribute("class");
                if (nodeClassNames) {
                  var matches = classNames === nodeClassNames;
                  if (!matches) {
                    var nodeClassNamesSet = toOrderedSet(nodeClassNames);
                    matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet));
                  }
                  if (matches) {
                    ls.push(node);
                  }
                }
              }
            });
          }
          return ls;
        });
      },
      //document factory method:
      createElement: function(tagName) {
        var node = new Element2();
        node.ownerDocument = this;
        node.nodeName = tagName;
        node.tagName = tagName;
        node.localName = tagName;
        node.childNodes = new NodeList();
        var attrs = node.attributes = new NamedNodeMap();
        attrs._ownerElement = node;
        return node;
      },
      createDocumentFragment: function() {
        var node = new DocumentFragment();
        node.ownerDocument = this;
        node.childNodes = new NodeList();
        return node;
      },
      createTextNode: function(data) {
        var node = new Text2();
        node.ownerDocument = this;
        node.appendData(data);
        return node;
      },
      createComment: function(data) {
        var node = new Comment();
        node.ownerDocument = this;
        node.appendData(data);
        return node;
      },
      createCDATASection: function(data) {
        var node = new CDATASection();
        node.ownerDocument = this;
        node.appendData(data);
        return node;
      },
      createProcessingInstruction: function(target, data) {
        var node = new ProcessingInstruction();
        node.ownerDocument = this;
        node.tagName = node.nodeName = node.target = target;
        node.nodeValue = node.data = data;
        return node;
      },
      createAttribute: function(name) {
        var node = new Attr();
        node.ownerDocument = this;
        node.name = name;
        node.nodeName = name;
        node.localName = name;
        node.specified = true;
        return node;
      },
      createEntityReference: function(name) {
        var node = new EntityReference();
        node.ownerDocument = this;
        node.nodeName = name;
        return node;
      },
      // Introduced in DOM Level 2:
      createElementNS: function(namespaceURI, qualifiedName) {
        var node = new Element2();
        var pl = qualifiedName.split(":");
        var attrs = node.attributes = new NamedNodeMap();
        node.childNodes = new NodeList();
        node.ownerDocument = this;
        node.nodeName = qualifiedName;
        node.tagName = qualifiedName;
        node.namespaceURI = namespaceURI;
        if (pl.length == 2) {
          node.prefix = pl[0];
          node.localName = pl[1];
        } else {
          node.localName = qualifiedName;
        }
        attrs._ownerElement = node;
        return node;
      },
      // Introduced in DOM Level 2:
      createAttributeNS: function(namespaceURI, qualifiedName) {
        var node = new Attr();
        var pl = qualifiedName.split(":");
        node.ownerDocument = this;
        node.nodeName = qualifiedName;
        node.name = qualifiedName;
        node.namespaceURI = namespaceURI;
        node.specified = true;
        if (pl.length == 2) {
          node.prefix = pl[0];
          node.localName = pl[1];
        } else {
          node.localName = qualifiedName;
        }
        return node;
      }
    };
    _extends3(Document2, Node);
    function Element2() {
      this._nsMap = {};
    }
    Element2.prototype = {
      nodeType: ELEMENT_NODE,
      hasAttribute: function(name) {
        return this.getAttributeNode(name) != null;
      },
      getAttribute: function(name) {
        var attr = this.getAttributeNode(name);
        return attr && attr.value || "";
      },
      getAttributeNode: function(name) {
        return this.attributes.getNamedItem(name);
      },
      setAttribute: function(name, value) {
        var attr = this.ownerDocument.createAttribute(name);
        attr.value = attr.nodeValue = "" + value;
        this.setAttributeNode(attr);
      },
      removeAttribute: function(name) {
        var attr = this.getAttributeNode(name);
        attr && this.removeAttributeNode(attr);
      },
      //four real opeartion method
      appendChild: function(newChild) {
        if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
          return this.insertBefore(newChild, null);
        } else {
          return _appendSingleChild(this, newChild);
        }
      },
      setAttributeNode: function(newAttr) {
        return this.attributes.setNamedItem(newAttr);
      },
      setAttributeNodeNS: function(newAttr) {
        return this.attributes.setNamedItemNS(newAttr);
      },
      removeAttributeNode: function(oldAttr) {
        return this.attributes.removeNamedItem(oldAttr.nodeName);
      },
      //get real attribute name,and remove it by removeAttributeNode
      removeAttributeNS: function(namespaceURI, localName) {
        var old = this.getAttributeNodeNS(namespaceURI, localName);
        old && this.removeAttributeNode(old);
      },
      hasAttributeNS: function(namespaceURI, localName) {
        return this.getAttributeNodeNS(namespaceURI, localName) != null;
      },
      getAttributeNS: function(namespaceURI, localName) {
        var attr = this.getAttributeNodeNS(namespaceURI, localName);
        return attr && attr.value || "";
      },
      setAttributeNS: function(namespaceURI, qualifiedName, value) {
        var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
        attr.value = attr.nodeValue = "" + value;
        this.setAttributeNode(attr);
      },
      getAttributeNodeNS: function(namespaceURI, localName) {
        return this.attributes.getNamedItemNS(namespaceURI, localName);
      },
      getElementsByTagName: function(tagName) {
        return new LiveNodeList(this, function(base) {
          var ls = [];
          _visitNode(base, function(node) {
            if (node !== base && node.nodeType == ELEMENT_NODE && (tagName === "*" || node.tagName == tagName)) {
              ls.push(node);
            }
          });
          return ls;
        });
      },
      getElementsByTagNameNS: function(namespaceURI, localName) {
        return new LiveNodeList(this, function(base) {
          var ls = [];
          _visitNode(base, function(node) {
            if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === "*" || node.namespaceURI === namespaceURI) && (localName === "*" || node.localName == localName)) {
              ls.push(node);
            }
          });
          return ls;
        });
      }
    };
    Document2.prototype.getElementsByTagName = Element2.prototype.getElementsByTagName;
    Document2.prototype.getElementsByTagNameNS = Element2.prototype.getElementsByTagNameNS;
    _extends3(Element2, Node);
    function Attr() {
    }
    Attr.prototype.nodeType = ATTRIBUTE_NODE;
    _extends3(Attr, Node);
    function CharacterData() {
    }
    CharacterData.prototype = {
      data: "",
      substringData: function(offset, count) {
        return this.data.substring(offset, offset + count);
      },
      appendData: function(text) {
        text = this.data + text;
        this.nodeValue = this.data = text;
        this.length = text.length;
      },
      insertData: function(offset, text) {
        this.replaceData(offset, 0, text);
      },
      appendChild: function(newChild) {
        throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]);
      },
      deleteData: function(offset, count) {
        this.replaceData(offset, count, "");
      },
      replaceData: function(offset, count, text) {
        var start2 = this.data.substring(0, offset);
        var end = this.data.substring(offset + count);
        text = start2 + text + end;
        this.nodeValue = this.data = text;
        this.length = text.length;
      }
    };
    _extends3(CharacterData, Node);
    function Text2() {
    }
    Text2.prototype = {
      nodeName: "#text",
      nodeType: TEXT_NODE,
      splitText: function(offset) {
        var text = this.data;
        var newText = text.substring(offset);
        text = text.substring(0, offset);
        this.data = this.nodeValue = text;
        this.length = text.length;
        var newNode = this.ownerDocument.createTextNode(newText);
        if (this.parentNode) {
          this.parentNode.insertBefore(newNode, this.nextSibling);
        }
        return newNode;
      }
    };
    _extends3(Text2, CharacterData);
    function Comment() {
    }
    Comment.prototype = {
      nodeName: "#comment",
      nodeType: COMMENT_NODE
    };
    _extends3(Comment, CharacterData);
    function CDATASection() {
    }
    CDATASection.prototype = {
      nodeName: "#cdata-section",
      nodeType: CDATA_SECTION_NODE
    };
    _extends3(CDATASection, CharacterData);
    function DocumentType() {
    }
    DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
    _extends3(DocumentType, Node);
    function Notation() {
    }
    Notation.prototype.nodeType = NOTATION_NODE;
    _extends3(Notation, Node);
    function Entity() {
    }
    Entity.prototype.nodeType = ENTITY_NODE;
    _extends3(Entity, Node);
    function EntityReference() {
    }
    EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
    _extends3(EntityReference, Node);
    function DocumentFragment() {
    }
    DocumentFragment.prototype.nodeName = "#document-fragment";
    DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
    _extends3(DocumentFragment, Node);
    function ProcessingInstruction() {
    }
    ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
    _extends3(ProcessingInstruction, Node);
    function XMLSerializer() {
    }
    XMLSerializer.prototype.serializeToString = function(node, isHtml, nodeFilter) {
      return nodeSerializeToString.call(node, isHtml, nodeFilter);
    };
    Node.prototype.toString = nodeSerializeToString;
    function nodeSerializeToString(isHtml, nodeFilter) {
      var buf = [];
      var refNode = this.nodeType == 9 && this.documentElement || this;
      var prefix = refNode.prefix;
      var uri = refNode.namespaceURI;
      if (uri && prefix == null) {
        var prefix = refNode.lookupPrefix(uri);
        if (prefix == null) {
          var visibleNamespaces = [
            {
              namespace: uri,
              prefix: null
            }
            //{namespace:uri,prefix:''}
          ];
        }
      }
      serializeToString(this, buf, isHtml, nodeFilter, visibleNamespaces);
      return buf.join("");
    }
    function needNamespaceDefine(node, isHTML, visibleNamespaces) {
      var prefix = node.prefix || "";
      var uri = node.namespaceURI;
      if (!uri) {
        return false;
      }
      if (prefix === "xml" && uri === NAMESPACE.XML || uri === NAMESPACE.XMLNS) {
        return false;
      }
      var i = visibleNamespaces.length;
      while (i--) {
        var ns = visibleNamespaces[i];
        if (ns.prefix === prefix) {
          return ns.namespace !== uri;
        }
      }
      return true;
    }
    function addSerializedAttribute(buf, qualifiedName, value) {
      buf.push(" ", qualifiedName, '="', value.replace(/[<&"]/g, _xmlEncoder), '"');
    }
    function serializeToString(node, buf, isHTML, nodeFilter, visibleNamespaces) {
      if (!visibleNamespaces) {
        visibleNamespaces = [];
      }
      if (nodeFilter) {
        node = nodeFilter(node);
        if (node) {
          if (typeof node == "string") {
            buf.push(node);
            return;
          }
        } else {
          return;
        }
      }
      switch (node.nodeType) {
        case ELEMENT_NODE:
          var attrs = node.attributes;
          var len = attrs.length;
          var child = node.firstChild;
          var nodeName = node.tagName;
          isHTML = NAMESPACE.isHTML(node.namespaceURI) || isHTML;
          var prefixedNodeName = nodeName;
          if (!isHTML && !node.prefix && node.namespaceURI) {
            var defaultNS;
            for (var ai = 0; ai < attrs.length; ai++) {
              if (attrs.item(ai).name === "xmlns") {
                defaultNS = attrs.item(ai).value;
                break;
              }
            }
            if (!defaultNS) {
              for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
                var namespace = visibleNamespaces[nsi];
                if (namespace.prefix === "" && namespace.namespace === node.namespaceURI) {
                  defaultNS = namespace.namespace;
                  break;
                }
              }
            }
            if (defaultNS !== node.namespaceURI) {
              for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
                var namespace = visibleNamespaces[nsi];
                if (namespace.namespace === node.namespaceURI) {
                  if (namespace.prefix) {
                    prefixedNodeName = namespace.prefix + ":" + nodeName;
                  }
                  break;
                }
              }
            }
          }
          buf.push("<", prefixedNodeName);
          for (var i = 0; i < len; i++) {
            var attr = attrs.item(i);
            if (attr.prefix == "xmlns") {
              visibleNamespaces.push({
                prefix: attr.localName,
                namespace: attr.value
              });
            } else if (attr.nodeName == "xmlns") {
              visibleNamespaces.push({
                prefix: "",
                namespace: attr.value
              });
            }
          }
          for (var i = 0; i < len; i++) {
            var attr = attrs.item(i);
            if (needNamespaceDefine(attr, isHTML, visibleNamespaces)) {
              var prefix = attr.prefix || "";
              var uri = attr.namespaceURI;
              addSerializedAttribute(buf, prefix ? "xmlns:" + prefix : "xmlns", uri);
              visibleNamespaces.push({
                prefix,
                namespace: uri
              });
            }
            serializeToString(attr, buf, isHTML, nodeFilter, visibleNamespaces);
          }
          if (nodeName === prefixedNodeName && needNamespaceDefine(node, isHTML, visibleNamespaces)) {
            var prefix = node.prefix || "";
            var uri = node.namespaceURI;
            addSerializedAttribute(buf, prefix ? "xmlns:" + prefix : "xmlns", uri);
            visibleNamespaces.push({
              prefix,
              namespace: uri
            });
          }
          if (child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)) {
            buf.push(">");
            if (isHTML && /^script$/i.test(nodeName)) {
              while (child) {
                if (child.data) {
                  buf.push(child.data);
                } else {
                  serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
                }
                child = child.nextSibling;
              }
            } else {
              while (child) {
                serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
                child = child.nextSibling;
              }
            }
            buf.push("</", prefixedNodeName, ">");
          } else {
            buf.push("/>");
          }
          return;
        case DOCUMENT_NODE:
        case DOCUMENT_FRAGMENT_NODE:
          var child = node.firstChild;
          while (child) {
            serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
            child = child.nextSibling;
          }
          return;
        case ATTRIBUTE_NODE:
          return addSerializedAttribute(buf, node.name, node.value);
        case TEXT_NODE:
          return buf.push(node.data.replace(/[<&]/g, _xmlEncoder).replace(/]]>/g, "]]&gt;"));
        case CDATA_SECTION_NODE:
          return buf.push("<![CDATA[", node.data, "]]>");
        case COMMENT_NODE:
          return buf.push("<!--", node.data, "-->");
        case DOCUMENT_TYPE_NODE:
          var pubid = node.publicId;
          var sysid = node.systemId;
          buf.push("<!DOCTYPE ", node.name);
          if (pubid) {
            buf.push(" PUBLIC ", pubid);
            if (sysid && sysid != ".") {
              buf.push(" ", sysid);
            }
            buf.push(">");
          } else if (sysid && sysid != ".") {
            buf.push(" SYSTEM ", sysid, ">");
          } else {
            var sub = node.internalSubset;
            if (sub) {
              buf.push(" [", sub, "]");
            }
            buf.push(">");
          }
          return;
        case PROCESSING_INSTRUCTION_NODE:
          return buf.push("<?", node.target, " ", node.data, "?>");
        case ENTITY_REFERENCE_NODE:
          return buf.push("&", node.nodeName, ";");
        //case ENTITY_NODE:
        //case NOTATION_NODE:
        default:
          buf.push("??", node.nodeName);
      }
    }
    function importNode(doc, node, deep) {
      var node2;
      switch (node.nodeType) {
        case ELEMENT_NODE:
          node2 = node.cloneNode(false);
          node2.ownerDocument = doc;
        //var attrs = node2.attributes;
        //var len = attrs.length;
        //for(var i=0;i<len;i++){
        //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
        //}
        case DOCUMENT_FRAGMENT_NODE:
          break;
        case ATTRIBUTE_NODE:
          deep = true;
          break;
      }
      if (!node2) {
        node2 = node.cloneNode(false);
      }
      node2.ownerDocument = doc;
      node2.parentNode = null;
      if (deep) {
        var child = node.firstChild;
        while (child) {
          node2.appendChild(importNode(doc, child, deep));
          child = child.nextSibling;
        }
      }
      return node2;
    }
    function cloneNode(doc, node, deep) {
      var node2 = new node.constructor();
      for (var n in node) {
        if (Object.prototype.hasOwnProperty.call(node, n)) {
          var v = node[n];
          if (typeof v != "object") {
            if (v != node2[n]) {
              node2[n] = v;
            }
          }
        }
      }
      if (node.childNodes) {
        node2.childNodes = new NodeList();
      }
      node2.ownerDocument = doc;
      switch (node2.nodeType) {
        case ELEMENT_NODE:
          var attrs = node.attributes;
          var attrs2 = node2.attributes = new NamedNodeMap();
          var len = attrs.length;
          attrs2._ownerElement = node2;
          for (var i = 0; i < len; i++) {
            node2.setAttributeNode(cloneNode(doc, attrs.item(i), true));
          }
          break;
          ;
        case ATTRIBUTE_NODE:
          deep = true;
      }
      if (deep) {
        var child = node.firstChild;
        while (child) {
          node2.appendChild(cloneNode(doc, child, deep));
          child = child.nextSibling;
        }
      }
      return node2;
    }
    function __set__(object, key, value) {
      object[key] = value;
    }
    try {
      if (Object.defineProperty) {
        let getTextContent3 = function(node) {
          switch (node.nodeType) {
            case ELEMENT_NODE:
            case DOCUMENT_FRAGMENT_NODE:
              var buf = [];
              node = node.firstChild;
              while (node) {
                if (node.nodeType !== 7 && node.nodeType !== 8) {
                  buf.push(getTextContent3(node));
                }
                node = node.nextSibling;
              }
              return buf.join("");
            default:
              return node.nodeValue;
          }
        };
        getTextContent2 = getTextContent3;
        Object.defineProperty(LiveNodeList.prototype, "length", {
          get: function() {
            _updateLiveList(this);
            return this.$$length;
          }
        });
        Object.defineProperty(Node.prototype, "textContent", {
          get: function() {
            return getTextContent3(this);
          },
          set: function(data) {
            switch (this.nodeType) {
              case ELEMENT_NODE:
              case DOCUMENT_FRAGMENT_NODE:
                while (this.firstChild) {
                  this.removeChild(this.firstChild);
                }
                if (data || String(data)) {
                  this.appendChild(this.ownerDocument.createTextNode(data));
                }
                break;
              default:
                this.data = data;
                this.value = data;
                this.nodeValue = data;
            }
          }
        });
        __set__ = function(object, key, value) {
          object["$$" + key] = value;
        };
      }
    } catch (e) {
    }
    var getTextContent2;
    exports.DocumentType = DocumentType;
    exports.DOMException = DOMException2;
    exports.DOMImplementation = DOMImplementation;
    exports.Element = Element2;
    exports.Node = Node;
    exports.NodeList = NodeList;
    exports.XMLSerializer = XMLSerializer;
  }
});

// node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/entities.js
var require_entities = __commonJS({
  "node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/entities.js"(exports) {
    "use strict";
    var freeze = require_conventions().freeze;
    exports.XML_ENTITIES = freeze({
      amp: "&",
      apos: "'",
      gt: ">",
      lt: "<",
      quot: '"'
    });
    exports.HTML_ENTITIES = freeze({
      Aacute: "\xC1",
      aacute: "\xE1",
      Abreve: "\u0102",
      abreve: "\u0103",
      ac: "\u223E",
      acd: "\u223F",
      acE: "\u223E\u0333",
      Acirc: "\xC2",
      acirc: "\xE2",
      acute: "\xB4",
      Acy: "\u0410",
      acy: "\u0430",
      AElig: "\xC6",
      aelig: "\xE6",
      af: "\u2061",
      Afr: "\u{1D504}",
      afr: "\u{1D51E}",
      Agrave: "\xC0",
      agrave: "\xE0",
      alefsym: "\u2135",
      aleph: "\u2135",
      Alpha: "\u0391",
      alpha: "\u03B1",
      Amacr: "\u0100",
      amacr: "\u0101",
      amalg: "\u2A3F",
      AMP: "&",
      amp: "&",
      And: "\u2A53",
      and: "\u2227",
      andand: "\u2A55",
      andd: "\u2A5C",
      andslope: "\u2A58",
      andv: "\u2A5A",
      ang: "\u2220",
      ange: "\u29A4",
      angle: "\u2220",
      angmsd: "\u2221",
      angmsdaa: "\u29A8",
      angmsdab: "\u29A9",
      angmsdac: "\u29AA",
      angmsdad: "\u29AB",
      angmsdae: "\u29AC",
      angmsdaf: "\u29AD",
      angmsdag: "\u29AE",
      angmsdah: "\u29AF",
      angrt: "\u221F",
      angrtvb: "\u22BE",
      angrtvbd: "\u299D",
      angsph: "\u2222",
      angst: "\xC5",
      angzarr: "\u237C",
      Aogon: "\u0104",
      aogon: "\u0105",
      Aopf: "\u{1D538}",
      aopf: "\u{1D552}",
      ap: "\u2248",
      apacir: "\u2A6F",
      apE: "\u2A70",
      ape: "\u224A",
      apid: "\u224B",
      apos: "'",
      ApplyFunction: "\u2061",
      approx: "\u2248",
      approxeq: "\u224A",
      Aring: "\xC5",
      aring: "\xE5",
      Ascr: "\u{1D49C}",
      ascr: "\u{1D4B6}",
      Assign: "\u2254",
      ast: "*",
      asymp: "\u2248",
      asympeq: "\u224D",
      Atilde: "\xC3",
      atilde: "\xE3",
      Auml: "\xC4",
      auml: "\xE4",
      awconint: "\u2233",
      awint: "\u2A11",
      backcong: "\u224C",
      backepsilon: "\u03F6",
      backprime: "\u2035",
      backsim: "\u223D",
      backsimeq: "\u22CD",
      Backslash: "\u2216",
      Barv: "\u2AE7",
      barvee: "\u22BD",
      Barwed: "\u2306",
      barwed: "\u2305",
      barwedge: "\u2305",
      bbrk: "\u23B5",
      bbrktbrk: "\u23B6",
      bcong: "\u224C",
      Bcy: "\u0411",
      bcy: "\u0431",
      bdquo: "\u201E",
      becaus: "\u2235",
      Because: "\u2235",
      because: "\u2235",
      bemptyv: "\u29B0",
      bepsi: "\u03F6",
      bernou: "\u212C",
      Bernoullis: "\u212C",
      Beta: "\u0392",
      beta: "\u03B2",
      beth: "\u2136",
      between: "\u226C",
      Bfr: "\u{1D505}",
      bfr: "\u{1D51F}",
      bigcap: "\u22C2",
      bigcirc: "\u25EF",
      bigcup: "\u22C3",
      bigodot: "\u2A00",
      bigoplus: "\u2A01",
      bigotimes: "\u2A02",
      bigsqcup: "\u2A06",
      bigstar: "\u2605",
      bigtriangledown: "\u25BD",
      bigtriangleup: "\u25B3",
      biguplus: "\u2A04",
      bigvee: "\u22C1",
      bigwedge: "\u22C0",
      bkarow: "\u290D",
      blacklozenge: "\u29EB",
      blacksquare: "\u25AA",
      blacktriangle: "\u25B4",
      blacktriangledown: "\u25BE",
      blacktriangleleft: "\u25C2",
      blacktriangleright: "\u25B8",
      blank: "\u2423",
      blk12: "\u2592",
      blk14: "\u2591",
      blk34: "\u2593",
      block: "\u2588",
      bne: "=\u20E5",
      bnequiv: "\u2261\u20E5",
      bNot: "\u2AED",
      bnot: "\u2310",
      Bopf: "\u{1D539}",
      bopf: "\u{1D553}",
      bot: "\u22A5",
      bottom: "\u22A5",
      bowtie: "\u22C8",
      boxbox: "\u29C9",
      boxDL: "\u2557",
      boxDl: "\u2556",
      boxdL: "\u2555",
      boxdl: "\u2510",
      boxDR: "\u2554",
      boxDr: "\u2553",
      boxdR: "\u2552",
      boxdr: "\u250C",
      boxH: "\u2550",
      boxh: "\u2500",
      boxHD: "\u2566",
      boxHd: "\u2564",
      boxhD: "\u2565",
      boxhd: "\u252C",
      boxHU: "\u2569",
      boxHu: "\u2567",
      boxhU: "\u2568",
      boxhu: "\u2534",
      boxminus: "\u229F",
      boxplus: "\u229E",
      boxtimes: "\u22A0",
      boxUL: "\u255D",
      boxUl: "\u255C",
      boxuL: "\u255B",
      boxul: "\u2518",
      boxUR: "\u255A",
      boxUr: "\u2559",
      boxuR: "\u2558",
      boxur: "\u2514",
      boxV: "\u2551",
      boxv: "\u2502",
      boxVH: "\u256C",
      boxVh: "\u256B",
      boxvH: "\u256A",
      boxvh: "\u253C",
      boxVL: "\u2563",
      boxVl: "\u2562",
      boxvL: "\u2561",
      boxvl: "\u2524",
      boxVR: "\u2560",
      boxVr: "\u255F",
      boxvR: "\u255E",
      boxvr: "\u251C",
      bprime: "\u2035",
      Breve: "\u02D8",
      breve: "\u02D8",
      brvbar: "\xA6",
      Bscr: "\u212C",
      bscr: "\u{1D4B7}",
      bsemi: "\u204F",
      bsim: "\u223D",
      bsime: "\u22CD",
      bsol: "\\",
      bsolb: "\u29C5",
      bsolhsub: "\u27C8",
      bull: "\u2022",
      bullet: "\u2022",
      bump: "\u224E",
      bumpE: "\u2AAE",
      bumpe: "\u224F",
      Bumpeq: "\u224E",
      bumpeq: "\u224F",
      Cacute: "\u0106",
      cacute: "\u0107",
      Cap: "\u22D2",
      cap: "\u2229",
      capand: "\u2A44",
      capbrcup: "\u2A49",
      capcap: "\u2A4B",
      capcup: "\u2A47",
      capdot: "\u2A40",
      CapitalDifferentialD: "\u2145",
      caps: "\u2229\uFE00",
      caret: "\u2041",
      caron: "\u02C7",
      Cayleys: "\u212D",
      ccaps: "\u2A4D",
      Ccaron: "\u010C",
      ccaron: "\u010D",
      Ccedil: "\xC7",
      ccedil: "\xE7",
      Ccirc: "\u0108",
      ccirc: "\u0109",
      Cconint: "\u2230",
      ccups: "\u2A4C",
      ccupssm: "\u2A50",
      Cdot: "\u010A",
      cdot: "\u010B",
      cedil: "\xB8",
      Cedilla: "\xB8",
      cemptyv: "\u29B2",
      cent: "\xA2",
      CenterDot: "\xB7",
      centerdot: "\xB7",
      Cfr: "\u212D",
      cfr: "\u{1D520}",
      CHcy: "\u0427",
      chcy: "\u0447",
      check: "\u2713",
      checkmark: "\u2713",
      Chi: "\u03A7",
      chi: "\u03C7",
      cir: "\u25CB",
      circ: "\u02C6",
      circeq: "\u2257",
      circlearrowleft: "\u21BA",
      circlearrowright: "\u21BB",
      circledast: "\u229B",
      circledcirc: "\u229A",
      circleddash: "\u229D",
      CircleDot: "\u2299",
      circledR: "\xAE",
      circledS: "\u24C8",
      CircleMinus: "\u2296",
      CirclePlus: "\u2295",
      CircleTimes: "\u2297",
      cirE: "\u29C3",
      cire: "\u2257",
      cirfnint: "\u2A10",
      cirmid: "\u2AEF",
      cirscir: "\u29C2",
      ClockwiseContourIntegral: "\u2232",
      CloseCurlyDoubleQuote: "\u201D",
      CloseCurlyQuote: "\u2019",
      clubs: "\u2663",
      clubsuit: "\u2663",
      Colon: "\u2237",
      colon: ":",
      Colone: "\u2A74",
      colone: "\u2254",
      coloneq: "\u2254",
      comma: ",",
      commat: "@",
      comp: "\u2201",
      compfn: "\u2218",
      complement: "\u2201",
      complexes: "\u2102",
      cong: "\u2245",
      congdot: "\u2A6D",
      Congruent: "\u2261",
      Conint: "\u222F",
      conint: "\u222E",
      ContourIntegral: "\u222E",
      Copf: "\u2102",
      copf: "\u{1D554}",
      coprod: "\u2210",
      Coproduct: "\u2210",
      COPY: "\xA9",
      copy: "\xA9",
      copysr: "\u2117",
      CounterClockwiseContourIntegral: "\u2233",
      crarr: "\u21B5",
      Cross: "\u2A2F",
      cross: "\u2717",
      Cscr: "\u{1D49E}",
      cscr: "\u{1D4B8}",
      csub: "\u2ACF",
      csube: "\u2AD1",
      csup: "\u2AD0",
      csupe: "\u2AD2",
      ctdot: "\u22EF",
      cudarrl: "\u2938",
      cudarrr: "\u2935",
      cuepr: "\u22DE",
      cuesc: "\u22DF",
      cularr: "\u21B6",
      cularrp: "\u293D",
      Cup: "\u22D3",
      cup: "\u222A",
      cupbrcap: "\u2A48",
      CupCap: "\u224D",
      cupcap: "\u2A46",
      cupcup: "\u2A4A",
      cupdot: "\u228D",
      cupor: "\u2A45",
      cups: "\u222A\uFE00",
      curarr: "\u21B7",
      curarrm: "\u293C",
      curlyeqprec: "\u22DE",
      curlyeqsucc: "\u22DF",
      curlyvee: "\u22CE",
      curlywedge: "\u22CF",
      curren: "\xA4",
      curvearrowleft: "\u21B6",
      curvearrowright: "\u21B7",
      cuvee: "\u22CE",
      cuwed: "\u22CF",
      cwconint: "\u2232",
      cwint: "\u2231",
      cylcty: "\u232D",
      Dagger: "\u2021",
      dagger: "\u2020",
      daleth: "\u2138",
      Darr: "\u21A1",
      dArr: "\u21D3",
      darr: "\u2193",
      dash: "\u2010",
      Dashv: "\u2AE4",
      dashv: "\u22A3",
      dbkarow: "\u290F",
      dblac: "\u02DD",
      Dcaron: "\u010E",
      dcaron: "\u010F",
      Dcy: "\u0414",
      dcy: "\u0434",
      DD: "\u2145",
      dd: "\u2146",
      ddagger: "\u2021",
      ddarr: "\u21CA",
      DDotrahd: "\u2911",
      ddotseq: "\u2A77",
      deg: "\xB0",
      Del: "\u2207",
      Delta: "\u0394",
      delta: "\u03B4",
      demptyv: "\u29B1",
      dfisht: "\u297F",
      Dfr: "\u{1D507}",
      dfr: "\u{1D521}",
      dHar: "\u2965",
      dharl: "\u21C3",
      dharr: "\u21C2",
      DiacriticalAcute: "\xB4",
      DiacriticalDot: "\u02D9",
      DiacriticalDoubleAcute: "\u02DD",
      DiacriticalGrave: "`",
      DiacriticalTilde: "\u02DC",
      diam: "\u22C4",
      Diamond: "\u22C4",
      diamond: "\u22C4",
      diamondsuit: "\u2666",
      diams: "\u2666",
      die: "\xA8",
      DifferentialD: "\u2146",
      digamma: "\u03DD",
      disin: "\u22F2",
      div: "\xF7",
      divide: "\xF7",
      divideontimes: "\u22C7",
      divonx: "\u22C7",
      DJcy: "\u0402",
      djcy: "\u0452",
      dlcorn: "\u231E",
      dlcrop: "\u230D",
      dollar: "$",
      Dopf: "\u{1D53B}",
      dopf: "\u{1D555}",
      Dot: "\xA8",
      dot: "\u02D9",
      DotDot: "\u20DC",
      doteq: "\u2250",
      doteqdot: "\u2251",
      DotEqual: "\u2250",
      dotminus: "\u2238",
      dotplus: "\u2214",
      dotsquare: "\u22A1",
      doublebarwedge: "\u2306",
      DoubleContourIntegral: "\u222F",
      DoubleDot: "\xA8",
      DoubleDownArrow: "\u21D3",
      DoubleLeftArrow: "\u21D0",
      DoubleLeftRightArrow: "\u21D4",
      DoubleLeftTee: "\u2AE4",
      DoubleLongLeftArrow: "\u27F8",
      DoubleLongLeftRightArrow: "\u27FA",
      DoubleLongRightArrow: "\u27F9",
      DoubleRightArrow: "\u21D2",
      DoubleRightTee: "\u22A8",
      DoubleUpArrow: "\u21D1",
      DoubleUpDownArrow: "\u21D5",
      DoubleVerticalBar: "\u2225",
      DownArrow: "\u2193",
      Downarrow: "\u21D3",
      downarrow: "\u2193",
      DownArrowBar: "\u2913",
      DownArrowUpArrow: "\u21F5",
      DownBreve: "\u0311",
      downdownarrows: "\u21CA",
      downharpoonleft: "\u21C3",
      downharpoonright: "\u21C2",
      DownLeftRightVector: "\u2950",
      DownLeftTeeVector: "\u295E",
      DownLeftVector: "\u21BD",
      DownLeftVectorBar: "\u2956",
      DownRightTeeVector: "\u295F",
      DownRightVector: "\u21C1",
      DownRightVectorBar: "\u2957",
      DownTee: "\u22A4",
      DownTeeArrow: "\u21A7",
      drbkarow: "\u2910",
      drcorn: "\u231F",
      drcrop: "\u230C",
      Dscr: "\u{1D49F}",
      dscr: "\u{1D4B9}",
      DScy: "\u0405",
      dscy: "\u0455",
      dsol: "\u29F6",
      Dstrok: "\u0110",
      dstrok: "\u0111",
      dtdot: "\u22F1",
      dtri: "\u25BF",
      dtrif: "\u25BE",
      duarr: "\u21F5",
      duhar: "\u296F",
      dwangle: "\u29A6",
      DZcy: "\u040F",
      dzcy: "\u045F",
      dzigrarr: "\u27FF",
      Eacute: "\xC9",
      eacute: "\xE9",
      easter: "\u2A6E",
      Ecaron: "\u011A",
      ecaron: "\u011B",
      ecir: "\u2256",
      Ecirc: "\xCA",
      ecirc: "\xEA",
      ecolon: "\u2255",
      Ecy: "\u042D",
      ecy: "\u044D",
      eDDot: "\u2A77",
      Edot: "\u0116",
      eDot: "\u2251",
      edot: "\u0117",
      ee: "\u2147",
      efDot: "\u2252",
      Efr: "\u{1D508}",
      efr: "\u{1D522}",
      eg: "\u2A9A",
      Egrave: "\xC8",
      egrave: "\xE8",
      egs: "\u2A96",
      egsdot: "\u2A98",
      el: "\u2A99",
      Element: "\u2208",
      elinters: "\u23E7",
      ell: "\u2113",
      els: "\u2A95",
      elsdot: "\u2A97",
      Emacr: "\u0112",
      emacr: "\u0113",
      empty: "\u2205",
      emptyset: "\u2205",
      EmptySmallSquare: "\u25FB",
      emptyv: "\u2205",
      EmptyVerySmallSquare: "\u25AB",
      emsp: "\u2003",
      emsp13: "\u2004",
      emsp14: "\u2005",
      ENG: "\u014A",
      eng: "\u014B",
      ensp: "\u2002",
      Eogon: "\u0118",
      eogon: "\u0119",
      Eopf: "\u{1D53C}",
      eopf: "\u{1D556}",
      epar: "\u22D5",
      eparsl: "\u29E3",
      eplus: "\u2A71",
      epsi: "\u03B5",
      Epsilon: "\u0395",
      epsilon: "\u03B5",
      epsiv: "\u03F5",
      eqcirc: "\u2256",
      eqcolon: "\u2255",
      eqsim: "\u2242",
      eqslantgtr: "\u2A96",
      eqslantless: "\u2A95",
      Equal: "\u2A75",
      equals: "=",
      EqualTilde: "\u2242",
      equest: "\u225F",
      Equilibrium: "\u21CC",
      equiv: "\u2261",
      equivDD: "\u2A78",
      eqvparsl: "\u29E5",
      erarr: "\u2971",
      erDot: "\u2253",
      Escr: "\u2130",
      escr: "\u212F",
      esdot: "\u2250",
      Esim: "\u2A73",
      esim: "\u2242",
      Eta: "\u0397",
      eta: "\u03B7",
      ETH: "\xD0",
      eth: "\xF0",
      Euml: "\xCB",
      euml: "\xEB",
      euro: "\u20AC",
      excl: "!",
      exist: "\u2203",
      Exists: "\u2203",
      expectation: "\u2130",
      ExponentialE: "\u2147",
      exponentiale: "\u2147",
      fallingdotseq: "\u2252",
      Fcy: "\u0424",
      fcy: "\u0444",
      female: "\u2640",
      ffilig: "\uFB03",
      fflig: "\uFB00",
      ffllig: "\uFB04",
      Ffr: "\u{1D509}",
      ffr: "\u{1D523}",
      filig: "\uFB01",
      FilledSmallSquare: "\u25FC",
      FilledVerySmallSquare: "\u25AA",
      fjlig: "fj",
      flat: "\u266D",
      fllig: "\uFB02",
      fltns: "\u25B1",
      fnof: "\u0192",
      Fopf: "\u{1D53D}",
      fopf: "\u{1D557}",
      ForAll: "\u2200",
      forall: "\u2200",
      fork: "\u22D4",
      forkv: "\u2AD9",
      Fouriertrf: "\u2131",
      fpartint: "\u2A0D",
      frac12: "\xBD",
      frac13: "\u2153",
      frac14: "\xBC",
      frac15: "\u2155",
      frac16: "\u2159",
      frac18: "\u215B",
      frac23: "\u2154",
      frac25: "\u2156",
      frac34: "\xBE",
      frac35: "\u2157",
      frac38: "\u215C",
      frac45: "\u2158",
      frac56: "\u215A",
      frac58: "\u215D",
      frac78: "\u215E",
      frasl: "\u2044",
      frown: "\u2322",
      Fscr: "\u2131",
      fscr: "\u{1D4BB}",
      gacute: "\u01F5",
      Gamma: "\u0393",
      gamma: "\u03B3",
      Gammad: "\u03DC",
      gammad: "\u03DD",
      gap: "\u2A86",
      Gbreve: "\u011E",
      gbreve: "\u011F",
      Gcedil: "\u0122",
      Gcirc: "\u011C",
      gcirc: "\u011D",
      Gcy: "\u0413",
      gcy: "\u0433",
      Gdot: "\u0120",
      gdot: "\u0121",
      gE: "\u2267",
      ge: "\u2265",
      gEl: "\u2A8C",
      gel: "\u22DB",
      geq: "\u2265",
      geqq: "\u2267",
      geqslant: "\u2A7E",
      ges: "\u2A7E",
      gescc: "\u2AA9",
      gesdot: "\u2A80",
      gesdoto: "\u2A82",
      gesdotol: "\u2A84",
      gesl: "\u22DB\uFE00",
      gesles: "\u2A94",
      Gfr: "\u{1D50A}",
      gfr: "\u{1D524}",
      Gg: "\u22D9",
      gg: "\u226B",
      ggg: "\u22D9",
      gimel: "\u2137",
      GJcy: "\u0403",
      gjcy: "\u0453",
      gl: "\u2277",
      gla: "\u2AA5",
      glE: "\u2A92",
      glj: "\u2AA4",
      gnap: "\u2A8A",
      gnapprox: "\u2A8A",
      gnE: "\u2269",
      gne: "\u2A88",
      gneq: "\u2A88",
      gneqq: "\u2269",
      gnsim: "\u22E7",
      Gopf: "\u{1D53E}",
      gopf: "\u{1D558}",
      grave: "`",
      GreaterEqual: "\u2265",
      GreaterEqualLess: "\u22DB",
      GreaterFullEqual: "\u2267",
      GreaterGreater: "\u2AA2",
      GreaterLess: "\u2277",
      GreaterSlantEqual: "\u2A7E",
      GreaterTilde: "\u2273",
      Gscr: "\u{1D4A2}",
      gscr: "\u210A",
      gsim: "\u2273",
      gsime: "\u2A8E",
      gsiml: "\u2A90",
      Gt: "\u226B",
      GT: ">",
      gt: ">",
      gtcc: "\u2AA7",
      gtcir: "\u2A7A",
      gtdot: "\u22D7",
      gtlPar: "\u2995",
      gtquest: "\u2A7C",
      gtrapprox: "\u2A86",
      gtrarr: "\u2978",
      gtrdot: "\u22D7",
      gtreqless: "\u22DB",
      gtreqqless: "\u2A8C",
      gtrless: "\u2277",
      gtrsim: "\u2273",
      gvertneqq: "\u2269\uFE00",
      gvnE: "\u2269\uFE00",
      Hacek: "\u02C7",
      hairsp: "\u200A",
      half: "\xBD",
      hamilt: "\u210B",
      HARDcy: "\u042A",
      hardcy: "\u044A",
      hArr: "\u21D4",
      harr: "\u2194",
      harrcir: "\u2948",
      harrw: "\u21AD",
      Hat: "^",
      hbar: "\u210F",
      Hcirc: "\u0124",
      hcirc: "\u0125",
      hearts: "\u2665",
      heartsuit: "\u2665",
      hellip: "\u2026",
      hercon: "\u22B9",
      Hfr: "\u210C",
      hfr: "\u{1D525}",
      HilbertSpace: "\u210B",
      hksearow: "\u2925",
      hkswarow: "\u2926",
      hoarr: "\u21FF",
      homtht: "\u223B",
      hookleftarrow: "\u21A9",
      hookrightarrow: "\u21AA",
      Hopf: "\u210D",
      hopf: "\u{1D559}",
      horbar: "\u2015",
      HorizontalLine: "\u2500",
      Hscr: "\u210B",
      hscr: "\u{1D4BD}",
      hslash: "\u210F",
      Hstrok: "\u0126",
      hstrok: "\u0127",
      HumpDownHump: "\u224E",
      HumpEqual: "\u224F",
      hybull: "\u2043",
      hyphen: "\u2010",
      Iacute: "\xCD",
      iacute: "\xED",
      ic: "\u2063",
      Icirc: "\xCE",
      icirc: "\xEE",
      Icy: "\u0418",
      icy: "\u0438",
      Idot: "\u0130",
      IEcy: "\u0415",
      iecy: "\u0435",
      iexcl: "\xA1",
      iff: "\u21D4",
      Ifr: "\u2111",
      ifr: "\u{1D526}",
      Igrave: "\xCC",
      igrave: "\xEC",
      ii: "\u2148",
      iiiint: "\u2A0C",
      iiint: "\u222D",
      iinfin: "\u29DC",
      iiota: "\u2129",
      IJlig: "\u0132",
      ijlig: "\u0133",
      Im: "\u2111",
      Imacr: "\u012A",
      imacr: "\u012B",
      image: "\u2111",
      ImaginaryI: "\u2148",
      imagline: "\u2110",
      imagpart: "\u2111",
      imath: "\u0131",
      imof: "\u22B7",
      imped: "\u01B5",
      Implies: "\u21D2",
      in: "\u2208",
      incare: "\u2105",
      infin: "\u221E",
      infintie: "\u29DD",
      inodot: "\u0131",
      Int: "\u222C",
      int: "\u222B",
      intcal: "\u22BA",
      integers: "\u2124",
      Integral: "\u222B",
      intercal: "\u22BA",
      Intersection: "\u22C2",
      intlarhk: "\u2A17",
      intprod: "\u2A3C",
      InvisibleComma: "\u2063",
      InvisibleTimes: "\u2062",
      IOcy: "\u0401",
      iocy: "\u0451",
      Iogon: "\u012E",
      iogon: "\u012F",
      Iopf: "\u{1D540}",
      iopf: "\u{1D55A}",
      Iota: "\u0399",
      iota: "\u03B9",
      iprod: "\u2A3C",
      iquest: "\xBF",
      Iscr: "\u2110",
      iscr: "\u{1D4BE}",
      isin: "\u2208",
      isindot: "\u22F5",
      isinE: "\u22F9",
      isins: "\u22F4",
      isinsv: "\u22F3",
      isinv: "\u2208",
      it: "\u2062",
      Itilde: "\u0128",
      itilde: "\u0129",
      Iukcy: "\u0406",
      iukcy: "\u0456",
      Iuml: "\xCF",
      iuml: "\xEF",
      Jcirc: "\u0134",
      jcirc: "\u0135",
      Jcy: "\u0419",
      jcy: "\u0439",
      Jfr: "\u{1D50D}",
      jfr: "\u{1D527}",
      jmath: "\u0237",
      Jopf: "\u{1D541}",
      jopf: "\u{1D55B}",
      Jscr: "\u{1D4A5}",
      jscr: "\u{1D4BF}",
      Jsercy: "\u0408",
      jsercy: "\u0458",
      Jukcy: "\u0404",
      jukcy: "\u0454",
      Kappa: "\u039A",
      kappa: "\u03BA",
      kappav: "\u03F0",
      Kcedil: "\u0136",
      kcedil: "\u0137",
      Kcy: "\u041A",
      kcy: "\u043A",
      Kfr: "\u{1D50E}",
      kfr: "\u{1D528}",
      kgreen: "\u0138",
      KHcy: "\u0425",
      khcy: "\u0445",
      KJcy: "\u040C",
      kjcy: "\u045C",
      Kopf: "\u{1D542}",
      kopf: "\u{1D55C}",
      Kscr: "\u{1D4A6}",
      kscr: "\u{1D4C0}",
      lAarr: "\u21DA",
      Lacute: "\u0139",
      lacute: "\u013A",
      laemptyv: "\u29B4",
      lagran: "\u2112",
      Lambda: "\u039B",
      lambda: "\u03BB",
      Lang: "\u27EA",
      lang: "\u27E8",
      langd: "\u2991",
      langle: "\u27E8",
      lap: "\u2A85",
      Laplacetrf: "\u2112",
      laquo: "\xAB",
      Larr: "\u219E",
      lArr: "\u21D0",
      larr: "\u2190",
      larrb: "\u21E4",
      larrbfs: "\u291F",
      larrfs: "\u291D",
      larrhk: "\u21A9",
      larrlp: "\u21AB",
      larrpl: "\u2939",
      larrsim: "\u2973",
      larrtl: "\u21A2",
      lat: "\u2AAB",
      lAtail: "\u291B",
      latail: "\u2919",
      late: "\u2AAD",
      lates: "\u2AAD\uFE00",
      lBarr: "\u290E",
      lbarr: "\u290C",
      lbbrk: "\u2772",
      lbrace: "{",
      lbrack: "[",
      lbrke: "\u298B",
      lbrksld: "\u298F",
      lbrkslu: "\u298D",
      Lcaron: "\u013D",
      lcaron: "\u013E",
      Lcedil: "\u013B",
      lcedil: "\u013C",
      lceil: "\u2308",
      lcub: "{",
      Lcy: "\u041B",
      lcy: "\u043B",
      ldca: "\u2936",
      ldquo: "\u201C",
      ldquor: "\u201E",
      ldrdhar: "\u2967",
      ldrushar: "\u294B",
      ldsh: "\u21B2",
      lE: "\u2266",
      le: "\u2264",
      LeftAngleBracket: "\u27E8",
      LeftArrow: "\u2190",
      Leftarrow: "\u21D0",
      leftarrow: "\u2190",
      LeftArrowBar: "\u21E4",
      LeftArrowRightArrow: "\u21C6",
      leftarrowtail: "\u21A2",
      LeftCeiling: "\u2308",
      LeftDoubleBracket: "\u27E6",
      LeftDownTeeVector: "\u2961",
      LeftDownVector: "\u21C3",
      LeftDownVectorBar: "\u2959",
      LeftFloor: "\u230A",
      leftharpoondown: "\u21BD",
      leftharpoonup: "\u21BC",
      leftleftarrows: "\u21C7",
      LeftRightArrow: "\u2194",
      Leftrightarrow: "\u21D4",
      leftrightarrow: "\u2194",
      leftrightarrows: "\u21C6",
      leftrightharpoons: "\u21CB",
      leftrightsquigarrow: "\u21AD",
      LeftRightVector: "\u294E",
      LeftTee: "\u22A3",
      LeftTeeArrow: "\u21A4",
      LeftTeeVector: "\u295A",
      leftthreetimes: "\u22CB",
      LeftTriangle: "\u22B2",
      LeftTriangleBar: "\u29CF",
      LeftTriangleEqual: "\u22B4",
      LeftUpDownVector: "\u2951",
      LeftUpTeeVector: "\u2960",
      LeftUpVector: "\u21BF",
      LeftUpVectorBar: "\u2958",
      LeftVector: "\u21BC",
      LeftVectorBar: "\u2952",
      lEg: "\u2A8B",
      leg: "\u22DA",
      leq: "\u2264",
      leqq: "\u2266",
      leqslant: "\u2A7D",
      les: "\u2A7D",
      lescc: "\u2AA8",
      lesdot: "\u2A7F",
      lesdoto: "\u2A81",
      lesdotor: "\u2A83",
      lesg: "\u22DA\uFE00",
      lesges: "\u2A93",
      lessapprox: "\u2A85",
      lessdot: "\u22D6",
      lesseqgtr: "\u22DA",
      lesseqqgtr: "\u2A8B",
      LessEqualGreater: "\u22DA",
      LessFullEqual: "\u2266",
      LessGreater: "\u2276",
      lessgtr: "\u2276",
      LessLess: "\u2AA1",
      lesssim: "\u2272",
      LessSlantEqual: "\u2A7D",
      LessTilde: "\u2272",
      lfisht: "\u297C",
      lfloor: "\u230A",
      Lfr: "\u{1D50F}",
      lfr: "\u{1D529}",
      lg: "\u2276",
      lgE: "\u2A91",
      lHar: "\u2962",
      lhard: "\u21BD",
      lharu: "\u21BC",
      lharul: "\u296A",
      lhblk: "\u2584",
      LJcy: "\u0409",
      ljcy: "\u0459",
      Ll: "\u22D8",
      ll: "\u226A",
      llarr: "\u21C7",
      llcorner: "\u231E",
      Lleftarrow: "\u21DA",
      llhard: "\u296B",
      lltri: "\u25FA",
      Lmidot: "\u013F",
      lmidot: "\u0140",
      lmoust: "\u23B0",
      lmoustache: "\u23B0",
      lnap: "\u2A89",
      lnapprox: "\u2A89",
      lnE: "\u2268",
      lne: "\u2A87",
      lneq: "\u2A87",
      lneqq: "\u2268",
      lnsim: "\u22E6",
      loang: "\u27EC",
      loarr: "\u21FD",
      lobrk: "\u27E6",
      LongLeftArrow: "\u27F5",
      Longleftarrow: "\u27F8",
      longleftarrow: "\u27F5",
      LongLeftRightArrow: "\u27F7",
      Longleftrightarrow: "\u27FA",
      longleftrightarrow: "\u27F7",
      longmapsto: "\u27FC",
      LongRightArrow: "\u27F6",
      Longrightarrow: "\u27F9",
      longrightarrow: "\u27F6",
      looparrowleft: "\u21AB",
      looparrowright: "\u21AC",
      lopar: "\u2985",
      Lopf: "\u{1D543}",
      lopf: "\u{1D55D}",
      loplus: "\u2A2D",
      lotimes: "\u2A34",
      lowast: "\u2217",
      lowbar: "_",
      LowerLeftArrow: "\u2199",
      LowerRightArrow: "\u2198",
      loz: "\u25CA",
      lozenge: "\u25CA",
      lozf: "\u29EB",
      lpar: "(",
      lparlt: "\u2993",
      lrarr: "\u21C6",
      lrcorner: "\u231F",
      lrhar: "\u21CB",
      lrhard: "\u296D",
      lrm: "\u200E",
      lrtri: "\u22BF",
      lsaquo: "\u2039",
      Lscr: "\u2112",
      lscr: "\u{1D4C1}",
      Lsh: "\u21B0",
      lsh: "\u21B0",
      lsim: "\u2272",
      lsime: "\u2A8D",
      lsimg: "\u2A8F",
      lsqb: "[",
      lsquo: "\u2018",
      lsquor: "\u201A",
      Lstrok: "\u0141",
      lstrok: "\u0142",
      Lt: "\u226A",
      LT: "<",
      lt: "<",
      ltcc: "\u2AA6",
      ltcir: "\u2A79",
      ltdot: "\u22D6",
      lthree: "\u22CB",
      ltimes: "\u22C9",
      ltlarr: "\u2976",
      ltquest: "\u2A7B",
      ltri: "\u25C3",
      ltrie: "\u22B4",
      ltrif: "\u25C2",
      ltrPar: "\u2996",
      lurdshar: "\u294A",
      luruhar: "\u2966",
      lvertneqq: "\u2268\uFE00",
      lvnE: "\u2268\uFE00",
      macr: "\xAF",
      male: "\u2642",
      malt: "\u2720",
      maltese: "\u2720",
      Map: "\u2905",
      map: "\u21A6",
      mapsto: "\u21A6",
      mapstodown: "\u21A7",
      mapstoleft: "\u21A4",
      mapstoup: "\u21A5",
      marker: "\u25AE",
      mcomma: "\u2A29",
      Mcy: "\u041C",
      mcy: "\u043C",
      mdash: "\u2014",
      mDDot: "\u223A",
      measuredangle: "\u2221",
      MediumSpace: "\u205F",
      Mellintrf: "\u2133",
      Mfr: "\u{1D510}",
      mfr: "\u{1D52A}",
      mho: "\u2127",
      micro: "\xB5",
      mid: "\u2223",
      midast: "*",
      midcir: "\u2AF0",
      middot: "\xB7",
      minus: "\u2212",
      minusb: "\u229F",
      minusd: "\u2238",
      minusdu: "\u2A2A",
      MinusPlus: "\u2213",
      mlcp: "\u2ADB",
      mldr: "\u2026",
      mnplus: "\u2213",
      models: "\u22A7",
      Mopf: "\u{1D544}",
      mopf: "\u{1D55E}",
      mp: "\u2213",
      Mscr: "\u2133",
      mscr: "\u{1D4C2}",
      mstpos: "\u223E",
      Mu: "\u039C",
      mu: "\u03BC",
      multimap: "\u22B8",
      mumap: "\u22B8",
      nabla: "\u2207",
      Nacute: "\u0143",
      nacute: "\u0144",
      nang: "\u2220\u20D2",
      nap: "\u2249",
      napE: "\u2A70\u0338",
      napid: "\u224B\u0338",
      napos: "\u0149",
      napprox: "\u2249",
      natur: "\u266E",
      natural: "\u266E",
      naturals: "\u2115",
      nbsp: "\xA0",
      nbump: "\u224E\u0338",
      nbumpe: "\u224F\u0338",
      ncap: "\u2A43",
      Ncaron: "\u0147",
      ncaron: "\u0148",
      Ncedil: "\u0145",
      ncedil: "\u0146",
      ncong: "\u2247",
      ncongdot: "\u2A6D\u0338",
      ncup: "\u2A42",
      Ncy: "\u041D",
      ncy: "\u043D",
      ndash: "\u2013",
      ne: "\u2260",
      nearhk: "\u2924",
      neArr: "\u21D7",
      nearr: "\u2197",
      nearrow: "\u2197",
      nedot: "\u2250\u0338",
      NegativeMediumSpace: "\u200B",
      NegativeThickSpace: "\u200B",
      NegativeThinSpace: "\u200B",
      NegativeVeryThinSpace: "\u200B",
      nequiv: "\u2262",
      nesear: "\u2928",
      nesim: "\u2242\u0338",
      NestedGreaterGreater: "\u226B",
      NestedLessLess: "\u226A",
      NewLine: "\n",
      nexist: "\u2204",
      nexists: "\u2204",
      Nfr: "\u{1D511}",
      nfr: "\u{1D52B}",
      ngE: "\u2267\u0338",
      nge: "\u2271",
      ngeq: "\u2271",
      ngeqq: "\u2267\u0338",
      ngeqslant: "\u2A7E\u0338",
      nges: "\u2A7E\u0338",
      nGg: "\u22D9\u0338",
      ngsim: "\u2275",
      nGt: "\u226B\u20D2",
      ngt: "\u226F",
      ngtr: "\u226F",
      nGtv: "\u226B\u0338",
      nhArr: "\u21CE",
      nharr: "\u21AE",
      nhpar: "\u2AF2",
      ni: "\u220B",
      nis: "\u22FC",
      nisd: "\u22FA",
      niv: "\u220B",
      NJcy: "\u040A",
      njcy: "\u045A",
      nlArr: "\u21CD",
      nlarr: "\u219A",
      nldr: "\u2025",
      nlE: "\u2266\u0338",
      nle: "\u2270",
      nLeftarrow: "\u21CD",
      nleftarrow: "\u219A",
      nLeftrightarrow: "\u21CE",
      nleftrightarrow: "\u21AE",
      nleq: "\u2270",
      nleqq: "\u2266\u0338",
      nleqslant: "\u2A7D\u0338",
      nles: "\u2A7D\u0338",
      nless: "\u226E",
      nLl: "\u22D8\u0338",
      nlsim: "\u2274",
      nLt: "\u226A\u20D2",
      nlt: "\u226E",
      nltri: "\u22EA",
      nltrie: "\u22EC",
      nLtv: "\u226A\u0338",
      nmid: "\u2224",
      NoBreak: "\u2060",
      NonBreakingSpace: "\xA0",
      Nopf: "\u2115",
      nopf: "\u{1D55F}",
      Not: "\u2AEC",
      not: "\xAC",
      NotCongruent: "\u2262",
      NotCupCap: "\u226D",
      NotDoubleVerticalBar: "\u2226",
      NotElement: "\u2209",
      NotEqual: "\u2260",
      NotEqualTilde: "\u2242\u0338",
      NotExists: "\u2204",
      NotGreater: "\u226F",
      NotGreaterEqual: "\u2271",
      NotGreaterFullEqual: "\u2267\u0338",
      NotGreaterGreater: "\u226B\u0338",
      NotGreaterLess: "\u2279",
      NotGreaterSlantEqual: "\u2A7E\u0338",
      NotGreaterTilde: "\u2275",
      NotHumpDownHump: "\u224E\u0338",
      NotHumpEqual: "\u224F\u0338",
      notin: "\u2209",
      notindot: "\u22F5\u0338",
      notinE: "\u22F9\u0338",
      notinva: "\u2209",
      notinvb: "\u22F7",
      notinvc: "\u22F6",
      NotLeftTriangle: "\u22EA",
      NotLeftTriangleBar: "\u29CF\u0338",
      NotLeftTriangleEqual: "\u22EC",
      NotLess: "\u226E",
      NotLessEqual: "\u2270",
      NotLessGreater: "\u2278",
      NotLessLess: "\u226A\u0338",
      NotLessSlantEqual: "\u2A7D\u0338",
      NotLessTilde: "\u2274",
      NotNestedGreaterGreater: "\u2AA2\u0338",
      NotNestedLessLess: "\u2AA1\u0338",
      notni: "\u220C",
      notniva: "\u220C",
      notnivb: "\u22FE",
      notnivc: "\u22FD",
      NotPrecedes: "\u2280",
      NotPrecedesEqual: "\u2AAF\u0338",
      NotPrecedesSlantEqual: "\u22E0",
      NotReverseElement: "\u220C",
      NotRightTriangle: "\u22EB",
      NotRightTriangleBar: "\u29D0\u0338",
      NotRightTriangleEqual: "\u22ED",
      NotSquareSubset: "\u228F\u0338",
      NotSquareSubsetEqual: "\u22E2",
      NotSquareSuperset: "\u2290\u0338",
      NotSquareSupersetEqual: "\u22E3",
      NotSubset: "\u2282\u20D2",
      NotSubsetEqual: "\u2288",
      NotSucceeds: "\u2281",
      NotSucceedsEqual: "\u2AB0\u0338",
      NotSucceedsSlantEqual: "\u22E1",
      NotSucceedsTilde: "\u227F\u0338",
      NotSuperset: "\u2283\u20D2",
      NotSupersetEqual: "\u2289",
      NotTilde: "\u2241",
      NotTildeEqual: "\u2244",
      NotTildeFullEqual: "\u2247",
      NotTildeTilde: "\u2249",
      NotVerticalBar: "\u2224",
      npar: "\u2226",
      nparallel: "\u2226",
      nparsl: "\u2AFD\u20E5",
      npart: "\u2202\u0338",
      npolint: "\u2A14",
      npr: "\u2280",
      nprcue: "\u22E0",
      npre: "\u2AAF\u0338",
      nprec: "\u2280",
      npreceq: "\u2AAF\u0338",
      nrArr: "\u21CF",
      nrarr: "\u219B",
      nrarrc: "\u2933\u0338",
      nrarrw: "\u219D\u0338",
      nRightarrow: "\u21CF",
      nrightarrow: "\u219B",
      nrtri: "\u22EB",
      nrtrie: "\u22ED",
      nsc: "\u2281",
      nsccue: "\u22E1",
      nsce: "\u2AB0\u0338",
      Nscr: "\u{1D4A9}",
      nscr: "\u{1D4C3}",
      nshortmid: "\u2224",
      nshortparallel: "\u2226",
      nsim: "\u2241",
      nsime: "\u2244",
      nsimeq: "\u2244",
      nsmid: "\u2224",
      nspar: "\u2226",
      nsqsube: "\u22E2",
      nsqsupe: "\u22E3",
      nsub: "\u2284",
      nsubE: "\u2AC5\u0338",
      nsube: "\u2288",
      nsubset: "\u2282\u20D2",
      nsubseteq: "\u2288",
      nsubseteqq: "\u2AC5\u0338",
      nsucc: "\u2281",
      nsucceq: "\u2AB0\u0338",
      nsup: "\u2285",
      nsupE: "\u2AC6\u0338",
      nsupe: "\u2289",
      nsupset: "\u2283\u20D2",
      nsupseteq: "\u2289",
      nsupseteqq: "\u2AC6\u0338",
      ntgl: "\u2279",
      Ntilde: "\xD1",
      ntilde: "\xF1",
      ntlg: "\u2278",
      ntriangleleft: "\u22EA",
      ntrianglelefteq: "\u22EC",
      ntriangleright: "\u22EB",
      ntrianglerighteq: "\u22ED",
      Nu: "\u039D",
      nu: "\u03BD",
      num: "#",
      numero: "\u2116",
      numsp: "\u2007",
      nvap: "\u224D\u20D2",
      nVDash: "\u22AF",
      nVdash: "\u22AE",
      nvDash: "\u22AD",
      nvdash: "\u22AC",
      nvge: "\u2265\u20D2",
      nvgt: ">\u20D2",
      nvHarr: "\u2904",
      nvinfin: "\u29DE",
      nvlArr: "\u2902",
      nvle: "\u2264\u20D2",
      nvlt: "<\u20D2",
      nvltrie: "\u22B4\u20D2",
      nvrArr: "\u2903",
      nvrtrie: "\u22B5\u20D2",
      nvsim: "\u223C\u20D2",
      nwarhk: "\u2923",
      nwArr: "\u21D6",
      nwarr: "\u2196",
      nwarrow: "\u2196",
      nwnear: "\u2927",
      Oacute: "\xD3",
      oacute: "\xF3",
      oast: "\u229B",
      ocir: "\u229A",
      Ocirc: "\xD4",
      ocirc: "\xF4",
      Ocy: "\u041E",
      ocy: "\u043E",
      odash: "\u229D",
      Odblac: "\u0150",
      odblac: "\u0151",
      odiv: "\u2A38",
      odot: "\u2299",
      odsold: "\u29BC",
      OElig: "\u0152",
      oelig: "\u0153",
      ofcir: "\u29BF",
      Ofr: "\u{1D512}",
      ofr: "\u{1D52C}",
      ogon: "\u02DB",
      Ograve: "\xD2",
      ograve: "\xF2",
      ogt: "\u29C1",
      ohbar: "\u29B5",
      ohm: "\u03A9",
      oint: "\u222E",
      olarr: "\u21BA",
      olcir: "\u29BE",
      olcross: "\u29BB",
      oline: "\u203E",
      olt: "\u29C0",
      Omacr: "\u014C",
      omacr: "\u014D",
      Omega: "\u03A9",
      omega: "\u03C9",
      Omicron: "\u039F",
      omicron: "\u03BF",
      omid: "\u29B6",
      ominus: "\u2296",
      Oopf: "\u{1D546}",
      oopf: "\u{1D560}",
      opar: "\u29B7",
      OpenCurlyDoubleQuote: "\u201C",
      OpenCurlyQuote: "\u2018",
      operp: "\u29B9",
      oplus: "\u2295",
      Or: "\u2A54",
      or: "\u2228",
      orarr: "\u21BB",
      ord: "\u2A5D",
      order: "\u2134",
      orderof: "\u2134",
      ordf: "\xAA",
      ordm: "\xBA",
      origof: "\u22B6",
      oror: "\u2A56",
      orslope: "\u2A57",
      orv: "\u2A5B",
      oS: "\u24C8",
      Oscr: "\u{1D4AA}",
      oscr: "\u2134",
      Oslash: "\xD8",
      oslash: "\xF8",
      osol: "\u2298",
      Otilde: "\xD5",
      otilde: "\xF5",
      Otimes: "\u2A37",
      otimes: "\u2297",
      otimesas: "\u2A36",
      Ouml: "\xD6",
      ouml: "\xF6",
      ovbar: "\u233D",
      OverBar: "\u203E",
      OverBrace: "\u23DE",
      OverBracket: "\u23B4",
      OverParenthesis: "\u23DC",
      par: "\u2225",
      para: "\xB6",
      parallel: "\u2225",
      parsim: "\u2AF3",
      parsl: "\u2AFD",
      part: "\u2202",
      PartialD: "\u2202",
      Pcy: "\u041F",
      pcy: "\u043F",
      percnt: "%",
      period: ".",
      permil: "\u2030",
      perp: "\u22A5",
      pertenk: "\u2031",
      Pfr: "\u{1D513}",
      pfr: "\u{1D52D}",
      Phi: "\u03A6",
      phi: "\u03C6",
      phiv: "\u03D5",
      phmmat: "\u2133",
      phone: "\u260E",
      Pi: "\u03A0",
      pi: "\u03C0",
      pitchfork: "\u22D4",
      piv: "\u03D6",
      planck: "\u210F",
      planckh: "\u210E",
      plankv: "\u210F",
      plus: "+",
      plusacir: "\u2A23",
      plusb: "\u229E",
      pluscir: "\u2A22",
      plusdo: "\u2214",
      plusdu: "\u2A25",
      pluse: "\u2A72",
      PlusMinus: "\xB1",
      plusmn: "\xB1",
      plussim: "\u2A26",
      plustwo: "\u2A27",
      pm: "\xB1",
      Poincareplane: "\u210C",
      pointint: "\u2A15",
      Popf: "\u2119",
      popf: "\u{1D561}",
      pound: "\xA3",
      Pr: "\u2ABB",
      pr: "\u227A",
      prap: "\u2AB7",
      prcue: "\u227C",
      prE: "\u2AB3",
      pre: "\u2AAF",
      prec: "\u227A",
      precapprox: "\u2AB7",
      preccurlyeq: "\u227C",
      Precedes: "\u227A",
      PrecedesEqual: "\u2AAF",
      PrecedesSlantEqual: "\u227C",
      PrecedesTilde: "\u227E",
      preceq: "\u2AAF",
      precnapprox: "\u2AB9",
      precneqq: "\u2AB5",
      precnsim: "\u22E8",
      precsim: "\u227E",
      Prime: "\u2033",
      prime: "\u2032",
      primes: "\u2119",
      prnap: "\u2AB9",
      prnE: "\u2AB5",
      prnsim: "\u22E8",
      prod: "\u220F",
      Product: "\u220F",
      profalar: "\u232E",
      profline: "\u2312",
      profsurf: "\u2313",
      prop: "\u221D",
      Proportion: "\u2237",
      Proportional: "\u221D",
      propto: "\u221D",
      prsim: "\u227E",
      prurel: "\u22B0",
      Pscr: "\u{1D4AB}",
      pscr: "\u{1D4C5}",
      Psi: "\u03A8",
      psi: "\u03C8",
      puncsp: "\u2008",
      Qfr: "\u{1D514}",
      qfr: "\u{1D52E}",
      qint: "\u2A0C",
      Qopf: "\u211A",
      qopf: "\u{1D562}",
      qprime: "\u2057",
      Qscr: "\u{1D4AC}",
      qscr: "\u{1D4C6}",
      quaternions: "\u210D",
      quatint: "\u2A16",
      quest: "?",
      questeq: "\u225F",
      QUOT: '"',
      quot: '"',
      rAarr: "\u21DB",
      race: "\u223D\u0331",
      Racute: "\u0154",
      racute: "\u0155",
      radic: "\u221A",
      raemptyv: "\u29B3",
      Rang: "\u27EB",
      rang: "\u27E9",
      rangd: "\u2992",
      range: "\u29A5",
      rangle: "\u27E9",
      raquo: "\xBB",
      Rarr: "\u21A0",
      rArr: "\u21D2",
      rarr: "\u2192",
      rarrap: "\u2975",
      rarrb: "\u21E5",
      rarrbfs: "\u2920",
      rarrc: "\u2933",
      rarrfs: "\u291E",
      rarrhk: "\u21AA",
      rarrlp: "\u21AC",
      rarrpl: "\u2945",
      rarrsim: "\u2974",
      Rarrtl: "\u2916",
      rarrtl: "\u21A3",
      rarrw: "\u219D",
      rAtail: "\u291C",
      ratail: "\u291A",
      ratio: "\u2236",
      rationals: "\u211A",
      RBarr: "\u2910",
      rBarr: "\u290F",
      rbarr: "\u290D",
      rbbrk: "\u2773",
      rbrace: "}",
      rbrack: "]",
      rbrke: "\u298C",
      rbrksld: "\u298E",
      rbrkslu: "\u2990",
      Rcaron: "\u0158",
      rcaron: "\u0159",
      Rcedil: "\u0156",
      rcedil: "\u0157",
      rceil: "\u2309",
      rcub: "}",
      Rcy: "\u0420",
      rcy: "\u0440",
      rdca: "\u2937",
      rdldhar: "\u2969",
      rdquo: "\u201D",
      rdquor: "\u201D",
      rdsh: "\u21B3",
      Re: "\u211C",
      real: "\u211C",
      realine: "\u211B",
      realpart: "\u211C",
      reals: "\u211D",
      rect: "\u25AD",
      REG: "\xAE",
      reg: "\xAE",
      ReverseElement: "\u220B",
      ReverseEquilibrium: "\u21CB",
      ReverseUpEquilibrium: "\u296F",
      rfisht: "\u297D",
      rfloor: "\u230B",
      Rfr: "\u211C",
      rfr: "\u{1D52F}",
      rHar: "\u2964",
      rhard: "\u21C1",
      rharu: "\u21C0",
      rharul: "\u296C",
      Rho: "\u03A1",
      rho: "\u03C1",
      rhov: "\u03F1",
      RightAngleBracket: "\u27E9",
      RightArrow: "\u2192",
      Rightarrow: "\u21D2",
      rightarrow: "\u2192",
      RightArrowBar: "\u21E5",
      RightArrowLeftArrow: "\u21C4",
      rightarrowtail: "\u21A3",
      RightCeiling: "\u2309",
      RightDoubleBracket: "\u27E7",
      RightDownTeeVector: "\u295D",
      RightDownVector: "\u21C2",
      RightDownVectorBar: "\u2955",
      RightFloor: "\u230B",
      rightharpoondown: "\u21C1",
      rightharpoonup: "\u21C0",
      rightleftarrows: "\u21C4",
      rightleftharpoons: "\u21CC",
      rightrightarrows: "\u21C9",
      rightsquigarrow: "\u219D",
      RightTee: "\u22A2",
      RightTeeArrow: "\u21A6",
      RightTeeVector: "\u295B",
      rightthreetimes: "\u22CC",
      RightTriangle: "\u22B3",
      RightTriangleBar: "\u29D0",
      RightTriangleEqual: "\u22B5",
      RightUpDownVector: "\u294F",
      RightUpTeeVector: "\u295C",
      RightUpVector: "\u21BE",
      RightUpVectorBar: "\u2954",
      RightVector: "\u21C0",
      RightVectorBar: "\u2953",
      ring: "\u02DA",
      risingdotseq: "\u2253",
      rlarr: "\u21C4",
      rlhar: "\u21CC",
      rlm: "\u200F",
      rmoust: "\u23B1",
      rmoustache: "\u23B1",
      rnmid: "\u2AEE",
      roang: "\u27ED",
      roarr: "\u21FE",
      robrk: "\u27E7",
      ropar: "\u2986",
      Ropf: "\u211D",
      ropf: "\u{1D563}",
      roplus: "\u2A2E",
      rotimes: "\u2A35",
      RoundImplies: "\u2970",
      rpar: ")",
      rpargt: "\u2994",
      rppolint: "\u2A12",
      rrarr: "\u21C9",
      Rrightarrow: "\u21DB",
      rsaquo: "\u203A",
      Rscr: "\u211B",
      rscr: "\u{1D4C7}",
      Rsh: "\u21B1",
      rsh: "\u21B1",
      rsqb: "]",
      rsquo: "\u2019",
      rsquor: "\u2019",
      rthree: "\u22CC",
      rtimes: "\u22CA",
      rtri: "\u25B9",
      rtrie: "\u22B5",
      rtrif: "\u25B8",
      rtriltri: "\u29CE",
      RuleDelayed: "\u29F4",
      ruluhar: "\u2968",
      rx: "\u211E",
      Sacute: "\u015A",
      sacute: "\u015B",
      sbquo: "\u201A",
      Sc: "\u2ABC",
      sc: "\u227B",
      scap: "\u2AB8",
      Scaron: "\u0160",
      scaron: "\u0161",
      sccue: "\u227D",
      scE: "\u2AB4",
      sce: "\u2AB0",
      Scedil: "\u015E",
      scedil: "\u015F",
      Scirc: "\u015C",
      scirc: "\u015D",
      scnap: "\u2ABA",
      scnE: "\u2AB6",
      scnsim: "\u22E9",
      scpolint: "\u2A13",
      scsim: "\u227F",
      Scy: "\u0421",
      scy: "\u0441",
      sdot: "\u22C5",
      sdotb: "\u22A1",
      sdote: "\u2A66",
      searhk: "\u2925",
      seArr: "\u21D8",
      searr: "\u2198",
      searrow: "\u2198",
      sect: "\xA7",
      semi: ";",
      seswar: "\u2929",
      setminus: "\u2216",
      setmn: "\u2216",
      sext: "\u2736",
      Sfr: "\u{1D516}",
      sfr: "\u{1D530}",
      sfrown: "\u2322",
      sharp: "\u266F",
      SHCHcy: "\u0429",
      shchcy: "\u0449",
      SHcy: "\u0428",
      shcy: "\u0448",
      ShortDownArrow: "\u2193",
      ShortLeftArrow: "\u2190",
      shortmid: "\u2223",
      shortparallel: "\u2225",
      ShortRightArrow: "\u2192",
      ShortUpArrow: "\u2191",
      shy: "\xAD",
      Sigma: "\u03A3",
      sigma: "\u03C3",
      sigmaf: "\u03C2",
      sigmav: "\u03C2",
      sim: "\u223C",
      simdot: "\u2A6A",
      sime: "\u2243",
      simeq: "\u2243",
      simg: "\u2A9E",
      simgE: "\u2AA0",
      siml: "\u2A9D",
      simlE: "\u2A9F",
      simne: "\u2246",
      simplus: "\u2A24",
      simrarr: "\u2972",
      slarr: "\u2190",
      SmallCircle: "\u2218",
      smallsetminus: "\u2216",
      smashp: "\u2A33",
      smeparsl: "\u29E4",
      smid: "\u2223",
      smile: "\u2323",
      smt: "\u2AAA",
      smte: "\u2AAC",
      smtes: "\u2AAC\uFE00",
      SOFTcy: "\u042C",
      softcy: "\u044C",
      sol: "/",
      solb: "\u29C4",
      solbar: "\u233F",
      Sopf: "\u{1D54A}",
      sopf: "\u{1D564}",
      spades: "\u2660",
      spadesuit: "\u2660",
      spar: "\u2225",
      sqcap: "\u2293",
      sqcaps: "\u2293\uFE00",
      sqcup: "\u2294",
      sqcups: "\u2294\uFE00",
      Sqrt: "\u221A",
      sqsub: "\u228F",
      sqsube: "\u2291",
      sqsubset: "\u228F",
      sqsubseteq: "\u2291",
      sqsup: "\u2290",
      sqsupe: "\u2292",
      sqsupset: "\u2290",
      sqsupseteq: "\u2292",
      squ: "\u25A1",
      Square: "\u25A1",
      square: "\u25A1",
      SquareIntersection: "\u2293",
      SquareSubset: "\u228F",
      SquareSubsetEqual: "\u2291",
      SquareSuperset: "\u2290",
      SquareSupersetEqual: "\u2292",
      SquareUnion: "\u2294",
      squarf: "\u25AA",
      squf: "\u25AA",
      srarr: "\u2192",
      Sscr: "\u{1D4AE}",
      sscr: "\u{1D4C8}",
      ssetmn: "\u2216",
      ssmile: "\u2323",
      sstarf: "\u22C6",
      Star: "\u22C6",
      star: "\u2606",
      starf: "\u2605",
      straightepsilon: "\u03F5",
      straightphi: "\u03D5",
      strns: "\xAF",
      Sub: "\u22D0",
      sub: "\u2282",
      subdot: "\u2ABD",
      subE: "\u2AC5",
      sube: "\u2286",
      subedot: "\u2AC3",
      submult: "\u2AC1",
      subnE: "\u2ACB",
      subne: "\u228A",
      subplus: "\u2ABF",
      subrarr: "\u2979",
      Subset: "\u22D0",
      subset: "\u2282",
      subseteq: "\u2286",
      subseteqq: "\u2AC5",
      SubsetEqual: "\u2286",
      subsetneq: "\u228A",
      subsetneqq: "\u2ACB",
      subsim: "\u2AC7",
      subsub: "\u2AD5",
      subsup: "\u2AD3",
      succ: "\u227B",
      succapprox: "\u2AB8",
      succcurlyeq: "\u227D",
      Succeeds: "\u227B",
      SucceedsEqual: "\u2AB0",
      SucceedsSlantEqual: "\u227D",
      SucceedsTilde: "\u227F",
      succeq: "\u2AB0",
      succnapprox: "\u2ABA",
      succneqq: "\u2AB6",
      succnsim: "\u22E9",
      succsim: "\u227F",
      SuchThat: "\u220B",
      Sum: "\u2211",
      sum: "\u2211",
      sung: "\u266A",
      Sup: "\u22D1",
      sup: "\u2283",
      sup1: "\xB9",
      sup2: "\xB2",
      sup3: "\xB3",
      supdot: "\u2ABE",
      supdsub: "\u2AD8",
      supE: "\u2AC6",
      supe: "\u2287",
      supedot: "\u2AC4",
      Superset: "\u2283",
      SupersetEqual: "\u2287",
      suphsol: "\u27C9",
      suphsub: "\u2AD7",
      suplarr: "\u297B",
      supmult: "\u2AC2",
      supnE: "\u2ACC",
      supne: "\u228B",
      supplus: "\u2AC0",
      Supset: "\u22D1",
      supset: "\u2283",
      supseteq: "\u2287",
      supseteqq: "\u2AC6",
      supsetneq: "\u228B",
      supsetneqq: "\u2ACC",
      supsim: "\u2AC8",
      supsub: "\u2AD4",
      supsup: "\u2AD6",
      swarhk: "\u2926",
      swArr: "\u21D9",
      swarr: "\u2199",
      swarrow: "\u2199",
      swnwar: "\u292A",
      szlig: "\xDF",
      Tab: "	",
      target: "\u2316",
      Tau: "\u03A4",
      tau: "\u03C4",
      tbrk: "\u23B4",
      Tcaron: "\u0164",
      tcaron: "\u0165",
      Tcedil: "\u0162",
      tcedil: "\u0163",
      Tcy: "\u0422",
      tcy: "\u0442",
      tdot: "\u20DB",
      telrec: "\u2315",
      Tfr: "\u{1D517}",
      tfr: "\u{1D531}",
      there4: "\u2234",
      Therefore: "\u2234",
      therefore: "\u2234",
      Theta: "\u0398",
      theta: "\u03B8",
      thetasym: "\u03D1",
      thetav: "\u03D1",
      thickapprox: "\u2248",
      thicksim: "\u223C",
      ThickSpace: "\u205F\u200A",
      thinsp: "\u2009",
      ThinSpace: "\u2009",
      thkap: "\u2248",
      thksim: "\u223C",
      THORN: "\xDE",
      thorn: "\xFE",
      Tilde: "\u223C",
      tilde: "\u02DC",
      TildeEqual: "\u2243",
      TildeFullEqual: "\u2245",
      TildeTilde: "\u2248",
      times: "\xD7",
      timesb: "\u22A0",
      timesbar: "\u2A31",
      timesd: "\u2A30",
      tint: "\u222D",
      toea: "\u2928",
      top: "\u22A4",
      topbot: "\u2336",
      topcir: "\u2AF1",
      Topf: "\u{1D54B}",
      topf: "\u{1D565}",
      topfork: "\u2ADA",
      tosa: "\u2929",
      tprime: "\u2034",
      TRADE: "\u2122",
      trade: "\u2122",
      triangle: "\u25B5",
      triangledown: "\u25BF",
      triangleleft: "\u25C3",
      trianglelefteq: "\u22B4",
      triangleq: "\u225C",
      triangleright: "\u25B9",
      trianglerighteq: "\u22B5",
      tridot: "\u25EC",
      trie: "\u225C",
      triminus: "\u2A3A",
      TripleDot: "\u20DB",
      triplus: "\u2A39",
      trisb: "\u29CD",
      tritime: "\u2A3B",
      trpezium: "\u23E2",
      Tscr: "\u{1D4AF}",
      tscr: "\u{1D4C9}",
      TScy: "\u0426",
      tscy: "\u0446",
      TSHcy: "\u040B",
      tshcy: "\u045B",
      Tstrok: "\u0166",
      tstrok: "\u0167",
      twixt: "\u226C",
      twoheadleftarrow: "\u219E",
      twoheadrightarrow: "\u21A0",
      Uacute: "\xDA",
      uacute: "\xFA",
      Uarr: "\u219F",
      uArr: "\u21D1",
      uarr: "\u2191",
      Uarrocir: "\u2949",
      Ubrcy: "\u040E",
      ubrcy: "\u045E",
      Ubreve: "\u016C",
      ubreve: "\u016D",
      Ucirc: "\xDB",
      ucirc: "\xFB",
      Ucy: "\u0423",
      ucy: "\u0443",
      udarr: "\u21C5",
      Udblac: "\u0170",
      udblac: "\u0171",
      udhar: "\u296E",
      ufisht: "\u297E",
      Ufr: "\u{1D518}",
      ufr: "\u{1D532}",
      Ugrave: "\xD9",
      ugrave: "\xF9",
      uHar: "\u2963",
      uharl: "\u21BF",
      uharr: "\u21BE",
      uhblk: "\u2580",
      ulcorn: "\u231C",
      ulcorner: "\u231C",
      ulcrop: "\u230F",
      ultri: "\u25F8",
      Umacr: "\u016A",
      umacr: "\u016B",
      uml: "\xA8",
      UnderBar: "_",
      UnderBrace: "\u23DF",
      UnderBracket: "\u23B5",
      UnderParenthesis: "\u23DD",
      Union: "\u22C3",
      UnionPlus: "\u228E",
      Uogon: "\u0172",
      uogon: "\u0173",
      Uopf: "\u{1D54C}",
      uopf: "\u{1D566}",
      UpArrow: "\u2191",
      Uparrow: "\u21D1",
      uparrow: "\u2191",
      UpArrowBar: "\u2912",
      UpArrowDownArrow: "\u21C5",
      UpDownArrow: "\u2195",
      Updownarrow: "\u21D5",
      updownarrow: "\u2195",
      UpEquilibrium: "\u296E",
      upharpoonleft: "\u21BF",
      upharpoonright: "\u21BE",
      uplus: "\u228E",
      UpperLeftArrow: "\u2196",
      UpperRightArrow: "\u2197",
      Upsi: "\u03D2",
      upsi: "\u03C5",
      upsih: "\u03D2",
      Upsilon: "\u03A5",
      upsilon: "\u03C5",
      UpTee: "\u22A5",
      UpTeeArrow: "\u21A5",
      upuparrows: "\u21C8",
      urcorn: "\u231D",
      urcorner: "\u231D",
      urcrop: "\u230E",
      Uring: "\u016E",
      uring: "\u016F",
      urtri: "\u25F9",
      Uscr: "\u{1D4B0}",
      uscr: "\u{1D4CA}",
      utdot: "\u22F0",
      Utilde: "\u0168",
      utilde: "\u0169",
      utri: "\u25B5",
      utrif: "\u25B4",
      uuarr: "\u21C8",
      Uuml: "\xDC",
      uuml: "\xFC",
      uwangle: "\u29A7",
      vangrt: "\u299C",
      varepsilon: "\u03F5",
      varkappa: "\u03F0",
      varnothing: "\u2205",
      varphi: "\u03D5",
      varpi: "\u03D6",
      varpropto: "\u221D",
      vArr: "\u21D5",
      varr: "\u2195",
      varrho: "\u03F1",
      varsigma: "\u03C2",
      varsubsetneq: "\u228A\uFE00",
      varsubsetneqq: "\u2ACB\uFE00",
      varsupsetneq: "\u228B\uFE00",
      varsupsetneqq: "\u2ACC\uFE00",
      vartheta: "\u03D1",
      vartriangleleft: "\u22B2",
      vartriangleright: "\u22B3",
      Vbar: "\u2AEB",
      vBar: "\u2AE8",
      vBarv: "\u2AE9",
      Vcy: "\u0412",
      vcy: "\u0432",
      VDash: "\u22AB",
      Vdash: "\u22A9",
      vDash: "\u22A8",
      vdash: "\u22A2",
      Vdashl: "\u2AE6",
      Vee: "\u22C1",
      vee: "\u2228",
      veebar: "\u22BB",
      veeeq: "\u225A",
      vellip: "\u22EE",
      Verbar: "\u2016",
      verbar: "|",
      Vert: "\u2016",
      vert: "|",
      VerticalBar: "\u2223",
      VerticalLine: "|",
      VerticalSeparator: "\u2758",
      VerticalTilde: "\u2240",
      VeryThinSpace: "\u200A",
      Vfr: "\u{1D519}",
      vfr: "\u{1D533}",
      vltri: "\u22B2",
      vnsub: "\u2282\u20D2",
      vnsup: "\u2283\u20D2",
      Vopf: "\u{1D54D}",
      vopf: "\u{1D567}",
      vprop: "\u221D",
      vrtri: "\u22B3",
      Vscr: "\u{1D4B1}",
      vscr: "\u{1D4CB}",
      vsubnE: "\u2ACB\uFE00",
      vsubne: "\u228A\uFE00",
      vsupnE: "\u2ACC\uFE00",
      vsupne: "\u228B\uFE00",
      Vvdash: "\u22AA",
      vzigzag: "\u299A",
      Wcirc: "\u0174",
      wcirc: "\u0175",
      wedbar: "\u2A5F",
      Wedge: "\u22C0",
      wedge: "\u2227",
      wedgeq: "\u2259",
      weierp: "\u2118",
      Wfr: "\u{1D51A}",
      wfr: "\u{1D534}",
      Wopf: "\u{1D54E}",
      wopf: "\u{1D568}",
      wp: "\u2118",
      wr: "\u2240",
      wreath: "\u2240",
      Wscr: "\u{1D4B2}",
      wscr: "\u{1D4CC}",
      xcap: "\u22C2",
      xcirc: "\u25EF",
      xcup: "\u22C3",
      xdtri: "\u25BD",
      Xfr: "\u{1D51B}",
      xfr: "\u{1D535}",
      xhArr: "\u27FA",
      xharr: "\u27F7",
      Xi: "\u039E",
      xi: "\u03BE",
      xlArr: "\u27F8",
      xlarr: "\u27F5",
      xmap: "\u27FC",
      xnis: "\u22FB",
      xodot: "\u2A00",
      Xopf: "\u{1D54F}",
      xopf: "\u{1D569}",
      xoplus: "\u2A01",
      xotime: "\u2A02",
      xrArr: "\u27F9",
      xrarr: "\u27F6",
      Xscr: "\u{1D4B3}",
      xscr: "\u{1D4CD}",
      xsqcup: "\u2A06",
      xuplus: "\u2A04",
      xutri: "\u25B3",
      xvee: "\u22C1",
      xwedge: "\u22C0",
      Yacute: "\xDD",
      yacute: "\xFD",
      YAcy: "\u042F",
      yacy: "\u044F",
      Ycirc: "\u0176",
      ycirc: "\u0177",
      Ycy: "\u042B",
      ycy: "\u044B",
      yen: "\xA5",
      Yfr: "\u{1D51C}",
      yfr: "\u{1D536}",
      YIcy: "\u0407",
      yicy: "\u0457",
      Yopf: "\u{1D550}",
      yopf: "\u{1D56A}",
      Yscr: "\u{1D4B4}",
      yscr: "\u{1D4CE}",
      YUcy: "\u042E",
      yucy: "\u044E",
      Yuml: "\u0178",
      yuml: "\xFF",
      Zacute: "\u0179",
      zacute: "\u017A",
      Zcaron: "\u017D",
      zcaron: "\u017E",
      Zcy: "\u0417",
      zcy: "\u0437",
      Zdot: "\u017B",
      zdot: "\u017C",
      zeetrf: "\u2128",
      ZeroWidthSpace: "\u200B",
      Zeta: "\u0396",
      zeta: "\u03B6",
      Zfr: "\u2128",
      zfr: "\u{1D537}",
      ZHcy: "\u0416",
      zhcy: "\u0436",
      zigrarr: "\u21DD",
      Zopf: "\u2124",
      zopf: "\u{1D56B}",
      Zscr: "\u{1D4B5}",
      zscr: "\u{1D4CF}",
      zwj: "\u200D",
      zwnj: "\u200C"
    });
    exports.entityMap = exports.HTML_ENTITIES;
  }
});

// node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/sax.js
var require_sax = __commonJS({
  "node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/sax.js"(exports) {
    var NAMESPACE = require_conventions().NAMESPACE;
    var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;
    var nameChar = new RegExp("[\\-\\.0-9" + nameStartChar.source.slice(1, -1) + "\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
    var tagNamePattern = new RegExp("^" + nameStartChar.source + nameChar.source + "*(?::" + nameStartChar.source + nameChar.source + "*)?$");
    var S_TAG = 0;
    var S_ATTR = 1;
    var S_ATTR_SPACE = 2;
    var S_EQ = 3;
    var S_ATTR_NOQUOT_VALUE = 4;
    var S_ATTR_END = 5;
    var S_TAG_SPACE = 6;
    var S_TAG_CLOSE = 7;
    function ParseError(message, locator) {
      this.message = message;
      this.locator = locator;
      if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
    }
    ParseError.prototype = new Error();
    ParseError.prototype.name = ParseError.name;
    function XMLReader() {
    }
    XMLReader.prototype = {
      parse: function(source, defaultNSMap, entityMap) {
        var domBuilder = this.domBuilder;
        domBuilder.startDocument();
        _copy(defaultNSMap, defaultNSMap = {});
        parse3(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);
        domBuilder.endDocument();
      }
    };
    function parse3(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
      function fixedFromCharCode(code) {
        if (code > 65535) {
          code -= 65536;
          var surrogate1 = 55296 + (code >> 10), surrogate2 = 56320 + (code & 1023);
          return String.fromCharCode(surrogate1, surrogate2);
        } else {
          return String.fromCharCode(code);
        }
      }
      function entityReplacer(a2) {
        var k = a2.slice(1, -1);
        if (k in entityMap) {
          return entityMap[k];
        } else if (k.charAt(0) === "#") {
          return fixedFromCharCode(parseInt(k.substr(1).replace("x", "0x")));
        } else {
          errorHandler.error("entity not found:" + a2);
          return a2;
        }
      }
      function appendText(end2) {
        if (end2 > start2) {
          var xt = source.substring(start2, end2).replace(/&#?\w+;/g, entityReplacer);
          locator && position(start2);
          domBuilder.characters(xt, 0, end2 - start2);
          start2 = end2;
        }
      }
      function position(p, m) {
        while (p >= lineEnd && (m = linePattern.exec(source))) {
          lineStart = m.index;
          lineEnd = lineStart + m[0].length;
          locator.lineNumber++;
        }
        locator.columnNumber = p - lineStart + 1;
      }
      var lineStart = 0;
      var lineEnd = 0;
      var linePattern = /.*(?:\r\n?|\n)|.*$/g;
      var locator = domBuilder.locator;
      var parseStack = [{
        currentNSMap: defaultNSMapCopy
      }];
      var closeMap = {};
      var start2 = 0;
      while (true) {
        try {
          var tagStart = source.indexOf("<", start2);
          if (tagStart < 0) {
            if (!source.substr(start2).match(/^\s*$/)) {
              var doc = domBuilder.doc;
              var text = doc.createTextNode(source.substr(start2));
              doc.appendChild(text);
              domBuilder.currentElement = text;
            }
            return;
          }
          if (tagStart > start2) {
            appendText(tagStart);
          }
          switch (source.charAt(tagStart + 1)) {
            case "/":
              var end = source.indexOf(">", tagStart + 3);
              var tagName = source.substring(tagStart + 2, end).replace(/[ \t\n\r]+$/g, "");
              var config = parseStack.pop();
              if (end < 0) {
                tagName = source.substring(tagStart + 2).replace(/[\s<].*/, "");
                errorHandler.error("end tag name: " + tagName + " is not complete:" + config.tagName);
                end = tagStart + 1 + tagName.length;
              } else if (tagName.match(/\s</)) {
                tagName = tagName.replace(/[\s<].*/, "");
                errorHandler.error("end tag name: " + tagName + " maybe not complete");
                end = tagStart + 1 + tagName.length;
              }
              var localNSMap = config.localNSMap;
              var endMatch = config.tagName == tagName;
              var endIgnoreCaseMach = endMatch || config.tagName && config.tagName.toLowerCase() == tagName.toLowerCase();
              if (endIgnoreCaseMach) {
                domBuilder.endElement(config.uri, config.localName, tagName);
                if (localNSMap) {
                  for (var prefix in localNSMap) {
                    if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
                      domBuilder.endPrefixMapping(prefix);
                    }
                  }
                }
                if (!endMatch) {
                  errorHandler.fatalError("end tag name: " + tagName + " is not match the current start tagName:" + config.tagName);
                }
              } else {
                parseStack.push(config);
              }
              end++;
              break;
            // end elment
            case "?":
              locator && position(tagStart);
              end = parseInstruction(source, tagStart, domBuilder);
              break;
            case "!":
              locator && position(tagStart);
              end = parseDCC(source, tagStart, domBuilder, errorHandler);
              break;
            default:
              locator && position(tagStart);
              var el = new ElementAttributes();
              var currentNSMap = parseStack[parseStack.length - 1].currentNSMap;
              var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler);
              var len = el.length;
              if (!el.closed && fixSelfClosed(source, end, el.tagName, closeMap)) {
                el.closed = true;
                if (!entityMap.nbsp) {
                  errorHandler.warning("unclosed xml attribute");
                }
              }
              if (locator && len) {
                var locator2 = copyLocator(locator, {});
                for (var i = 0; i < len; i++) {
                  var a = el[i];
                  position(a.offset);
                  a.locator = copyLocator(locator, {});
                }
                domBuilder.locator = locator2;
                if (appendElement(el, domBuilder, currentNSMap)) {
                  parseStack.push(el);
                }
                domBuilder.locator = locator;
              } else {
                if (appendElement(el, domBuilder, currentNSMap)) {
                  parseStack.push(el);
                }
              }
              if (NAMESPACE.isHTML(el.uri) && !el.closed) {
                end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);
              } else {
                end++;
              }
          }
        } catch (e) {
          if (e instanceof ParseError) {
            throw e;
          }
          errorHandler.error("element parse error: " + e);
          end = -1;
        }
        if (end > start2) {
          start2 = end;
        } else {
          appendText(Math.max(tagStart, start2) + 1);
        }
      }
    }
    function copyLocator(f, t2) {
      t2.lineNumber = f.lineNumber;
      t2.columnNumber = f.columnNumber;
      return t2;
    }
    function parseElementStartPart(source, start2, el, currentNSMap, entityReplacer, errorHandler) {
      function addAttribute(qname, value2, startIndex) {
        if (el.attributeNames.hasOwnProperty(qname)) {
          errorHandler.fatalError("Attribute " + qname + " redefined");
        }
        el.addValue(qname, value2, startIndex);
      }
      var attrName;
      var value;
      var p = ++start2;
      var s = S_TAG;
      while (true) {
        var c = source.charAt(p);
        switch (c) {
          case "=":
            if (s === S_ATTR) {
              attrName = source.slice(start2, p);
              s = S_EQ;
            } else if (s === S_ATTR_SPACE) {
              s = S_EQ;
            } else {
              throw new Error("attribute equal must after attrName");
            }
            break;
          case "'":
          case '"':
            if (s === S_EQ || s === S_ATTR) {
              if (s === S_ATTR) {
                errorHandler.warning('attribute value must after "="');
                attrName = source.slice(start2, p);
              }
              start2 = p + 1;
              p = source.indexOf(c, start2);
              if (p > 0) {
                value = source.slice(start2, p).replace(/&#?\w+;/g, entityReplacer);
                addAttribute(attrName, value, start2 - 1);
                s = S_ATTR_END;
              } else {
                throw new Error("attribute value no end '" + c + "' match");
              }
            } else if (s == S_ATTR_NOQUOT_VALUE) {
              value = source.slice(start2, p).replace(/&#?\w+;/g, entityReplacer);
              addAttribute(attrName, value, start2);
              errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ")!!");
              start2 = p + 1;
              s = S_ATTR_END;
            } else {
              throw new Error('attribute value must after "="');
            }
            break;
          case "/":
            switch (s) {
              case S_TAG:
                el.setTagName(source.slice(start2, p));
              case S_ATTR_END:
              case S_TAG_SPACE:
              case S_TAG_CLOSE:
                s = S_TAG_CLOSE;
                el.closed = true;
              case S_ATTR_NOQUOT_VALUE:
              case S_ATTR:
                break;
              case S_ATTR_SPACE:
                el.closed = true;
                break;
              //case S_EQ:
              default:
                throw new Error("attribute invalid close char('/')");
            }
            break;
          case "":
            errorHandler.error("unexpected end of input");
            if (s == S_TAG) {
              el.setTagName(source.slice(start2, p));
            }
            return p;
          case ">":
            switch (s) {
              case S_TAG:
                el.setTagName(source.slice(start2, p));
              case S_ATTR_END:
              case S_TAG_SPACE:
              case S_TAG_CLOSE:
                break;
              //normal
              case S_ATTR_NOQUOT_VALUE:
              //Compatible state
              case S_ATTR:
                value = source.slice(start2, p);
                if (value.slice(-1) === "/") {
                  el.closed = true;
                  value = value.slice(0, -1);
                }
              case S_ATTR_SPACE:
                if (s === S_ATTR_SPACE) {
                  value = attrName;
                }
                if (s == S_ATTR_NOQUOT_VALUE) {
                  errorHandler.warning('attribute "' + value + '" missed quot(")!');
                  addAttribute(attrName, value.replace(/&#?\w+;/g, entityReplacer), start2);
                } else {
                  if (!NAMESPACE.isHTML(currentNSMap[""]) || !value.match(/^(?:disabled|checked|selected)$/i)) {
                    errorHandler.warning('attribute "' + value + '" missed value!! "' + value + '" instead!!');
                  }
                  addAttribute(value, value, start2);
                }
                break;
              case S_EQ:
                throw new Error("attribute value missed!!");
            }
            return p;
          /*xml space '\x20' | #x9 | #xD | #xA; */
          case "\x80":
            c = " ";
          default:
            if (c <= " ") {
              switch (s) {
                case S_TAG:
                  el.setTagName(source.slice(start2, p));
                  s = S_TAG_SPACE;
                  break;
                case S_ATTR:
                  attrName = source.slice(start2, p);
                  s = S_ATTR_SPACE;
                  break;
                case S_ATTR_NOQUOT_VALUE:
                  var value = source.slice(start2, p).replace(/&#?\w+;/g, entityReplacer);
                  errorHandler.warning('attribute "' + value + '" missed quot(")!!');
                  addAttribute(attrName, value, start2);
                case S_ATTR_END:
                  s = S_TAG_SPACE;
                  break;
              }
            } else {
              switch (s) {
                //case S_TAG:void();break;
                //case S_ATTR:void();break;
                //case S_ATTR_NOQUOT_VALUE:void();break;
                case S_ATTR_SPACE:
                  var tagName = el.tagName;
                  if (!NAMESPACE.isHTML(currentNSMap[""]) || !attrName.match(/^(?:disabled|checked|selected)$/i)) {
                    errorHandler.warning('attribute "' + attrName + '" missed value!! "' + attrName + '" instead2!!');
                  }
                  addAttribute(attrName, attrName, start2);
                  start2 = p;
                  s = S_ATTR;
                  break;
                case S_ATTR_END:
                  errorHandler.warning('attribute space is required"' + attrName + '"!!');
                case S_TAG_SPACE:
                  s = S_ATTR;
                  start2 = p;
                  break;
                case S_EQ:
                  s = S_ATTR_NOQUOT_VALUE;
                  start2 = p;
                  break;
                case S_TAG_CLOSE:
                  throw new Error("elements closed character '/' and '>' must be connected to");
              }
            }
        }
        p++;
      }
    }
    function appendElement(el, domBuilder, currentNSMap) {
      var tagName = el.tagName;
      var localNSMap = null;
      var i = el.length;
      while (i--) {
        var a = el[i];
        var qName = a.qName;
        var value = a.value;
        var nsp = qName.indexOf(":");
        if (nsp > 0) {
          var prefix = a.prefix = qName.slice(0, nsp);
          var localName = qName.slice(nsp + 1);
          var nsPrefix = prefix === "xmlns" && localName;
        } else {
          localName = qName;
          prefix = null;
          nsPrefix = qName === "xmlns" && "";
        }
        a.localName = localName;
        if (nsPrefix !== false) {
          if (localNSMap == null) {
            localNSMap = {};
            _copy(currentNSMap, currentNSMap = {});
          }
          currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
          a.uri = NAMESPACE.XMLNS;
          domBuilder.startPrefixMapping(nsPrefix, value);
        }
      }
      var i = el.length;
      while (i--) {
        a = el[i];
        var prefix = a.prefix;
        if (prefix) {
          if (prefix === "xml") {
            a.uri = NAMESPACE.XML;
          }
          if (prefix !== "xmlns") {
            a.uri = currentNSMap[prefix || ""];
          }
        }
      }
      var nsp = tagName.indexOf(":");
      if (nsp > 0) {
        prefix = el.prefix = tagName.slice(0, nsp);
        localName = el.localName = tagName.slice(nsp + 1);
      } else {
        prefix = null;
        localName = el.localName = tagName;
      }
      var ns = el.uri = currentNSMap[prefix || ""];
      domBuilder.startElement(ns, localName, tagName, el);
      if (el.closed) {
        domBuilder.endElement(ns, localName, tagName);
        if (localNSMap) {
          for (prefix in localNSMap) {
            if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
              domBuilder.endPrefixMapping(prefix);
            }
          }
        }
      } else {
        el.currentNSMap = currentNSMap;
        el.localNSMap = localNSMap;
        return true;
      }
    }
    function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {
      if (/^(?:script|textarea)$/i.test(tagName)) {
        var elEndStart = source.indexOf("</" + tagName + ">", elStartEnd);
        var text = source.substring(elStartEnd + 1, elEndStart);
        if (/[&<]/.test(text)) {
          if (/^script$/i.test(tagName)) {
            domBuilder.characters(text, 0, text.length);
            return elEndStart;
          }
          text = text.replace(/&#?\w+;/g, entityReplacer);
          domBuilder.characters(text, 0, text.length);
          return elEndStart;
        }
      }
      return elStartEnd + 1;
    }
    function fixSelfClosed(source, elStartEnd, tagName, closeMap) {
      var pos = closeMap[tagName];
      if (pos == null) {
        pos = source.lastIndexOf("</" + tagName + ">");
        if (pos < elStartEnd) {
          pos = source.lastIndexOf("</" + tagName);
        }
        closeMap[tagName] = pos;
      }
      return pos < elStartEnd;
    }
    function _copy(source, target) {
      for (var n in source) {
        if (Object.prototype.hasOwnProperty.call(source, n)) {
          target[n] = source[n];
        }
      }
    }
    function parseDCC(source, start2, domBuilder, errorHandler) {
      var next = source.charAt(start2 + 2);
      switch (next) {
        case "-":
          if (source.charAt(start2 + 3) === "-") {
            var end = source.indexOf("-->", start2 + 4);
            if (end > start2) {
              domBuilder.comment(source, start2 + 4, end - start2 - 4);
              return end + 3;
            } else {
              errorHandler.error("Unclosed comment");
              return -1;
            }
          } else {
            return -1;
          }
        default:
          if (source.substr(start2 + 3, 6) == "CDATA[") {
            var end = source.indexOf("]]>", start2 + 9);
            domBuilder.startCDATA();
            domBuilder.characters(source, start2 + 9, end - start2 - 9);
            domBuilder.endCDATA();
            return end + 3;
          }
          var matchs = split(source, start2);
          var len = matchs.length;
          if (len > 1 && /!doctype/i.test(matchs[0][0])) {
            var name = matchs[1][0];
            var pubid = false;
            var sysid = false;
            if (len > 3) {
              if (/^public$/i.test(matchs[2][0])) {
                pubid = matchs[3][0];
                sysid = len > 4 && matchs[4][0];
              } else if (/^system$/i.test(matchs[2][0])) {
                sysid = matchs[3][0];
              }
            }
            var lastMatch = matchs[len - 1];
            domBuilder.startDTD(name, pubid, sysid);
            domBuilder.endDTD();
            return lastMatch.index + lastMatch[0].length;
          }
      }
      return -1;
    }
    function parseInstruction(source, start2, domBuilder) {
      var end = source.indexOf("?>", start2);
      if (end) {
        var match = source.substring(start2, end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
        if (match) {
          var len = match[0].length;
          domBuilder.processingInstruction(match[1], match[2]);
          return end + 2;
        } else {
          return -1;
        }
      }
      return -1;
    }
    function ElementAttributes() {
      this.attributeNames = {};
    }
    ElementAttributes.prototype = {
      setTagName: function(tagName) {
        if (!tagNamePattern.test(tagName)) {
          throw new Error("invalid tagName:" + tagName);
        }
        this.tagName = tagName;
      },
      addValue: function(qName, value, offset) {
        if (!tagNamePattern.test(qName)) {
          throw new Error("invalid attribute:" + qName);
        }
        this.attributeNames[qName] = this.length;
        this[this.length++] = {
          qName,
          value,
          offset
        };
      },
      length: 0,
      getLocalName: function(i) {
        return this[i].localName;
      },
      getLocator: function(i) {
        return this[i].locator;
      },
      getQName: function(i) {
        return this[i].qName;
      },
      getURI: function(i) {
        return this[i].uri;
      },
      getValue: function(i) {
        return this[i].value;
      }
      //	,getIndex:function(uri, localName)){
      //		if(localName){
      //
      //		}else{
      //			var qName = uri
      //		}
      //	},
      //	getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
      //	getType:function(uri,localName){}
      //	getType:function(i){},
    };
    function split(source, start2) {
      var match;
      var buf = [];
      var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
      reg.lastIndex = start2;
      reg.exec(source);
      while (match = reg.exec(source)) {
        buf.push(match);
        if (match[1]) return buf;
      }
    }
    exports.XMLReader = XMLReader;
    exports.ParseError = ParseError;
  }
});

// node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/dom-parser.js
var require_dom_parser = __commonJS({
  "node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/dom-parser.js"(exports) {
    var conventions = require_conventions();
    var dom = require_dom();
    var entities = require_entities();
    var sax = require_sax();
    var DOMImplementation = dom.DOMImplementation;
    var NAMESPACE = conventions.NAMESPACE;
    var ParseError = sax.ParseError;
    var XMLReader = sax.XMLReader;
    function DOMParser3(options) {
      this.options = options || {
        locator: {}
      };
    }
    DOMParser3.prototype.parseFromString = function(source, mimeType) {
      var options = this.options;
      var sax2 = new XMLReader();
      var domBuilder = options.domBuilder || new DOMHandler();
      var errorHandler = options.errorHandler;
      var locator = options.locator;
      var defaultNSMap = options.xmlns || {};
      var isHTML = /\/x?html?$/.test(mimeType);
      var entityMap = isHTML ? entities.HTML_ENTITIES : entities.XML_ENTITIES;
      if (locator) {
        domBuilder.setDocumentLocator(locator);
      }
      sax2.errorHandler = buildErrorHandler(errorHandler, domBuilder, locator);
      sax2.domBuilder = options.domBuilder || domBuilder;
      if (isHTML) {
        defaultNSMap[""] = NAMESPACE.HTML;
      }
      defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML;
      if (source && typeof source === "string") {
        sax2.parse(source, defaultNSMap, entityMap);
      } else {
        sax2.errorHandler.error("invalid doc source");
      }
      return domBuilder.doc;
    };
    function buildErrorHandler(errorImpl, domBuilder, locator) {
      if (!errorImpl) {
        if (domBuilder instanceof DOMHandler) {
          return domBuilder;
        }
        errorImpl = domBuilder;
      }
      var errorHandler = {};
      var isCallback = errorImpl instanceof Function;
      locator = locator || {};
      function build(key) {
        var fn = errorImpl[key];
        if (!fn && isCallback) {
          fn = errorImpl.length == 2 ? function(msg) {
            errorImpl(key, msg);
          } : errorImpl;
        }
        errorHandler[key] = fn && function(msg) {
          fn("[xmldom " + key + "]	" + msg + _locator(locator));
        } || function() {
        };
      }
      build("warning");
      build("error");
      build("fatalError");
      return errorHandler;
    }
    function DOMHandler() {
      this.cdata = false;
    }
    function position(locator, node) {
      node.lineNumber = locator.lineNumber;
      node.columnNumber = locator.columnNumber;
    }
    DOMHandler.prototype = {
      startDocument: function() {
        this.doc = new DOMImplementation().createDocument(null, null, null);
        if (this.locator) {
          this.doc.documentURI = this.locator.systemId;
        }
      },
      startElement: function(namespaceURI, localName, qName, attrs) {
        var doc = this.doc;
        var el = doc.createElementNS(namespaceURI, qName || localName);
        var len = attrs.length;
        appendElement(this, el);
        this.currentElement = el;
        this.locator && position(this.locator, el);
        for (var i = 0; i < len; i++) {
          var namespaceURI = attrs.getURI(i);
          var value = attrs.getValue(i);
          var qName = attrs.getQName(i);
          var attr = doc.createAttributeNS(namespaceURI, qName);
          this.locator && position(attrs.getLocator(i), attr);
          attr.value = attr.nodeValue = value;
          el.setAttributeNode(attr);
        }
      },
      endElement: function(namespaceURI, localName, qName) {
        var current = this.currentElement;
        var tagName = current.tagName;
        this.currentElement = current.parentNode;
      },
      startPrefixMapping: function(prefix, uri) {
      },
      endPrefixMapping: function(prefix) {
      },
      processingInstruction: function(target, data) {
        var ins = this.doc.createProcessingInstruction(target, data);
        this.locator && position(this.locator, ins);
        appendElement(this, ins);
      },
      ignorableWhitespace: function(ch, start2, length) {
      },
      characters: function(chars, start2, length) {
        chars = _toString.apply(this, arguments);
        if (chars) {
          if (this.cdata) {
            var charNode = this.doc.createCDATASection(chars);
          } else {
            var charNode = this.doc.createTextNode(chars);
          }
          if (this.currentElement) {
            this.currentElement.appendChild(charNode);
          } else if (/^\s*$/.test(chars)) {
            this.doc.appendChild(charNode);
          }
          this.locator && position(this.locator, charNode);
        }
      },
      skippedEntity: function(name) {
      },
      endDocument: function() {
        this.doc.normalize();
      },
      setDocumentLocator: function(locator) {
        if (this.locator = locator) {
          locator.lineNumber = 0;
        }
      },
      //LexicalHandler
      comment: function(chars, start2, length) {
        chars = _toString.apply(this, arguments);
        var comm = this.doc.createComment(chars);
        this.locator && position(this.locator, comm);
        appendElement(this, comm);
      },
      startCDATA: function() {
        this.cdata = true;
      },
      endCDATA: function() {
        this.cdata = false;
      },
      startDTD: function(name, publicId, systemId) {
        var impl = this.doc.implementation;
        if (impl && impl.createDocumentType) {
          var dt = impl.createDocumentType(name, publicId, systemId);
          this.locator && position(this.locator, dt);
          appendElement(this, dt);
          this.doc.doctype = dt;
        }
      },
      /**
       * @see org.xml.sax.ErrorHandler
       * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
       */
      warning: function(error) {
        console.warn("[xmldom warning]	" + error, _locator(this.locator));
      },
      error: function(error) {
        console.error("[xmldom error]	" + error, _locator(this.locator));
      },
      fatalError: function(error) {
        throw new ParseError(error, this.locator);
      }
    };
    function _locator(l) {
      if (l) {
        return "\n@" + (l.systemId || "") + "#[line:" + l.lineNumber + ",col:" + l.columnNumber + "]";
      }
    }
    function _toString(chars, start2, length) {
      if (typeof chars == "string") {
        return chars.substr(start2, length);
      } else {
        if (chars.length >= start2 + length || start2) {
          return new java.lang.String(chars, start2, length) + "";
        }
        return chars;
      }
    }
    "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g, function(key) {
      DOMHandler.prototype[key] = function() {
        return null;
      };
    });
    function appendElement(hander, node) {
      if (!hander.currentElement) {
        hander.doc.appendChild(node);
      } else {
        hander.currentElement.appendChild(node);
      }
    }
    exports.__DOMHandler = DOMHandler;
    exports.DOMParser = DOMParser3;
    exports.DOMImplementation = dom.DOMImplementation;
    exports.XMLSerializer = dom.XMLSerializer;
  }
});

// node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/index.js
var require_lib2 = __commonJS({
  "node_modules/.pnpm/@xmldom+xmldom@0.7.13/node_modules/@xmldom/xmldom/lib/index.js"(exports) {
    var dom = require_dom();
    exports.DOMImplementation = dom.DOMImplementation;
    exports.XMLSerializer = dom.XMLSerializer;
    exports.DOMParser = require_dom_parser().DOMParser;
  }
});

// node_modules/.pnpm/mux.js@6.0.1/node_modules/mux.js/lib/utils/numbers.js
var require_numbers = __commonJS({
  "node_modules/.pnpm/mux.js@6.0.1/node_modules/mux.js/lib/utils/numbers.js"(exports, module) {
    var MAX_UINT32 = Math.pow(2, 32);
    var getUint64 = function(uint8) {
      var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
      var value;
      if (dv.getBigUint64) {
        value = dv.getBigUint64(0);
        if (value < Number.MAX_SAFE_INTEGER) {
          return Number(value);
        }
        return value;
      }
      return dv.getUint32(0) * MAX_UINT32 + dv.getUint32(4);
    };
    module.exports = {
      getUint64,
      MAX_UINT32
    };
  }
});

// node_modules/.pnpm/mux.js@6.0.1/node_modules/mux.js/lib/tools/parse-sidx.js
var require_parse_sidx = __commonJS({
  "node_modules/.pnpm/mux.js@6.0.1/node_modules/mux.js/lib/tools/parse-sidx.js"(exports, module) {
    var getUint64 = require_numbers().getUint64;
    var parseSidx2 = function(data) {
      var view2 = new DataView(data.buffer, data.byteOffset, data.byteLength), result = {
        version: data[0],
        flags: new Uint8Array(data.subarray(1, 4)),
        references: [],
        referenceId: view2.getUint32(4),
        timescale: view2.getUint32(8)
      }, i = 12;
      if (result.version === 0) {
        result.earliestPresentationTime = view2.getUint32(i);
        result.firstOffset = view2.getUint32(i + 4);
        i += 8;
      } else {
        result.earliestPresentationTime = getUint64(data.subarray(i));
        result.firstOffset = getUint64(data.subarray(i + 8));
        i += 16;
      }
      i += 2;
      var referenceCount = view2.getUint16(i);
      i += 2;
      for (; referenceCount > 0; i += 12, referenceCount--) {
        result.references.push({
          referenceType: (data[i] & 128) >>> 7,
          referencedSize: view2.getUint32(i) & 2147483647,
          subsegmentDuration: view2.getUint32(i + 4),
          startsWithSap: !!(data[i + 8] & 128),
          sapType: (data[i + 8] & 112) >>> 4,
          sapDeltaTime: view2.getUint32(i + 8) & 268435455
        });
      }
      return result;
    };
    module.exports = parseSidx2;
  }
});

// node_modules/.pnpm/mux.js@6.0.1/node_modules/mux.js/lib/utils/clock.js
var require_clock = __commonJS({
  "node_modules/.pnpm/mux.js@6.0.1/node_modules/mux.js/lib/utils/clock.js"(exports, module) {
    var ONE_SECOND_IN_TS2 = 9e4;
    var secondsToVideoTs;
    var secondsToAudioTs;
    var videoTsToSeconds;
    var audioTsToSeconds;
    var audioTsToVideoTs;
    var videoTsToAudioTs;
    var metadataTsToSeconds;
    secondsToVideoTs = function(seconds) {
      return seconds * ONE_SECOND_IN_TS2;
    };
    secondsToAudioTs = function(seconds, sampleRate) {
      return seconds * sampleRate;
    };
    videoTsToSeconds = function(timestamp) {
      return timestamp / ONE_SECOND_IN_TS2;
    };
    audioTsToSeconds = function(timestamp, sampleRate) {
      return timestamp / sampleRate;
    };
    audioTsToVideoTs = function(timestamp, sampleRate) {
      return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
    };
    videoTsToAudioTs = function(timestamp, sampleRate) {
      return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
    };
    metadataTsToSeconds = function(timestamp, timelineStartPts, keepOriginalTimestamps) {
      return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
    };
    module.exports = {
      ONE_SECOND_IN_TS: ONE_SECOND_IN_TS2,
      secondsToVideoTs,
      secondsToAudioTs,
      videoTsToSeconds,
      audioTsToSeconds,
      audioTsToVideoTs,
      videoTsToAudioTs,
      metadataTsToSeconds
    };
  }
});

// src/app/player/components/art-player/art-player.component.ts
var import_artplayer = __toESM(require_artplayer());

// node_modules/.pnpm/hls.js@1.6.1/node_modules/hls.js/dist/hls.mjs
var isFiniteNumber = Number.isFinite || function(value) {
  return typeof value === "number" && isFinite(value);
};
var isSafeInteger = Number.isSafeInteger || function(value) {
  return typeof value === "number" && Math.abs(value) <= MAX_SAFE_INTEGER;
};
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
var ErrorTypes = /* @__PURE__ */ function(ErrorTypes2) {
  ErrorTypes2["NETWORK_ERROR"] = "networkError";
  ErrorTypes2["MEDIA_ERROR"] = "mediaError";
  ErrorTypes2["KEY_SYSTEM_ERROR"] = "keySystemError";
  ErrorTypes2["MUX_ERROR"] = "muxError";
  ErrorTypes2["OTHER_ERROR"] = "otherError";
  return ErrorTypes2;
}({});
var ErrorDetails = /* @__PURE__ */ function(ErrorDetails2) {
  ErrorDetails2["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  ErrorDetails2["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  ErrorDetails2["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  ErrorDetails2["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  ErrorDetails2["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  ErrorDetails2["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  ErrorDetails2["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  ErrorDetails2["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  ErrorDetails2["KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR"] = "keySystemDestroyMediaKeysError";
  ErrorDetails2["KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR"] = "keySystemDestroyCloseSessionError";
  ErrorDetails2["KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR"] = "keySystemDestroyRemoveSessionError";
  ErrorDetails2["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  ErrorDetails2["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  ErrorDetails2["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  ErrorDetails2["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  ErrorDetails2["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  ErrorDetails2["LEVEL_LOAD_ERROR"] = "levelLoadError";
  ErrorDetails2["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  ErrorDetails2["LEVEL_PARSING_ERROR"] = "levelParsingError";
  ErrorDetails2["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  ErrorDetails2["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  ErrorDetails2["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  ErrorDetails2["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  ErrorDetails2["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  ErrorDetails2["FRAG_LOAD_ERROR"] = "fragLoadError";
  ErrorDetails2["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  ErrorDetails2["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  ErrorDetails2["FRAG_PARSING_ERROR"] = "fragParsingError";
  ErrorDetails2["FRAG_GAP"] = "fragGap";
  ErrorDetails2["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  ErrorDetails2["KEY_LOAD_ERROR"] = "keyLoadError";
  ErrorDetails2["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  ErrorDetails2["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  ErrorDetails2["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  ErrorDetails2["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  ErrorDetails2["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  ErrorDetails2["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  ErrorDetails2["BUFFER_FULL_ERROR"] = "bufferFullError";
  ErrorDetails2["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  ErrorDetails2["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  ErrorDetails2["ASSET_LIST_LOAD_ERROR"] = "assetListLoadError";
  ErrorDetails2["ASSET_LIST_LOAD_TIMEOUT"] = "assetListLoadTimeout";
  ErrorDetails2["ASSET_LIST_PARSING_ERROR"] = "assetListParsingError";
  ErrorDetails2["INTERSTITIAL_ASSET_ITEM_ERROR"] = "interstitialAssetItemError";
  ErrorDetails2["INTERNAL_EXCEPTION"] = "internalException";
  ErrorDetails2["INTERNAL_ABORTED"] = "aborted";
  ErrorDetails2["ATTACH_MEDIA_ERROR"] = "attachMediaError";
  ErrorDetails2["UNKNOWN"] = "unknown";
  return ErrorDetails2;
}({});
var Events = /* @__PURE__ */ function(Events3) {
  Events3["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  Events3["MEDIA_ATTACHED"] = "hlsMediaAttached";
  Events3["MEDIA_DETACHING"] = "hlsMediaDetaching";
  Events3["MEDIA_DETACHED"] = "hlsMediaDetached";
  Events3["MEDIA_ENDED"] = "hlsMediaEnded";
  Events3["STALL_RESOLVED"] = "hlsStallResolved";
  Events3["BUFFER_RESET"] = "hlsBufferReset";
  Events3["BUFFER_CODECS"] = "hlsBufferCodecs";
  Events3["BUFFER_CREATED"] = "hlsBufferCreated";
  Events3["BUFFER_APPENDING"] = "hlsBufferAppending";
  Events3["BUFFER_APPENDED"] = "hlsBufferAppended";
  Events3["BUFFER_EOS"] = "hlsBufferEos";
  Events3["BUFFERED_TO_END"] = "hlsBufferedToEnd";
  Events3["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  Events3["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  Events3["MANIFEST_LOADING"] = "hlsManifestLoading";
  Events3["MANIFEST_LOADED"] = "hlsManifestLoaded";
  Events3["MANIFEST_PARSED"] = "hlsManifestParsed";
  Events3["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  Events3["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  Events3["LEVEL_LOADING"] = "hlsLevelLoading";
  Events3["LEVEL_LOADED"] = "hlsLevelLoaded";
  Events3["LEVEL_UPDATED"] = "hlsLevelUpdated";
  Events3["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  Events3["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  Events3["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  Events3["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  Events3["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  Events3["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  Events3["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  Events3["AUDIO_TRACK_UPDATED"] = "hlsAudioTrackUpdated";
  Events3["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  Events3["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  Events3["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  Events3["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  Events3["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  Events3["SUBTITLE_TRACK_UPDATED"] = "hlsSubtitleTrackUpdated";
  Events3["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  Events3["CUES_PARSED"] = "hlsCuesParsed";
  Events3["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  Events3["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  Events3["FRAG_LOADING"] = "hlsFragLoading";
  Events3["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  Events3["FRAG_LOADED"] = "hlsFragLoaded";
  Events3["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  Events3["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  Events3["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  Events3["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  Events3["FRAG_PARSED"] = "hlsFragParsed";
  Events3["FRAG_BUFFERED"] = "hlsFragBuffered";
  Events3["FRAG_CHANGED"] = "hlsFragChanged";
  Events3["FPS_DROP"] = "hlsFpsDrop";
  Events3["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  Events3["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  Events3["ERROR"] = "hlsError";
  Events3["DESTROYING"] = "hlsDestroying";
  Events3["KEY_LOADING"] = "hlsKeyLoading";
  Events3["KEY_LOADED"] = "hlsKeyLoaded";
  Events3["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  Events3["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  Events3["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  Events3["ASSET_LIST_LOADING"] = "hlsAssetListLoading";
  Events3["ASSET_LIST_LOADED"] = "hlsAssetListLoaded";
  Events3["INTERSTITIALS_UPDATED"] = "hlsInterstitialsUpdated";
  Events3["INTERSTITIALS_BUFFERED_TO_BOUNDARY"] = "hlsInterstitialsBufferedToBoundary";
  Events3["INTERSTITIAL_ASSET_PLAYER_CREATED"] = "hlsInterstitialAssetPlayerCreated";
  Events3["INTERSTITIAL_STARTED"] = "hlsInterstitialStarted";
  Events3["INTERSTITIAL_ASSET_STARTED"] = "hlsInterstitialAssetStarted";
  Events3["INTERSTITIAL_ASSET_ENDED"] = "hlsInterstitialAssetEnded";
  Events3["INTERSTITIAL_ASSET_ERROR"] = "hlsInterstitialAssetError";
  Events3["INTERSTITIAL_ENDED"] = "hlsInterstitialEnded";
  Events3["INTERSTITIALS_PRIMARY_RESUMED"] = "hlsInterstitialsPrimaryResumed";
  Events3["PLAYOUT_LIMIT_REACHED"] = "hlsPlayoutLimitReached";
  Events3["EVENT_CUE_ENTER"] = "hlsEventCueEnter";
  return Events3;
}({});
var PlaylistContextType = {
  MANIFEST: "manifest",
  LEVEL: "level",
  AUDIO_TRACK: "audioTrack",
  SUBTITLE_TRACK: "subtitleTrack"
};
var PlaylistLevelType = {
  MAIN: "main",
  AUDIO: "audio",
  SUBTITLE: "subtitle"
};
var EWMA = class {
  //  About half of the estimated value will be from the last |halfLife| samples by weight.
  constructor(halfLife, estimate = 0, weight = 0) {
    this.halfLife = void 0;
    this.alpha_ = void 0;
    this.estimate_ = void 0;
    this.totalWeight_ = void 0;
    this.halfLife = halfLife;
    this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
    this.estimate_ = estimate;
    this.totalWeight_ = weight;
  }
  sample(weight, value) {
    const adjAlpha = Math.pow(this.alpha_, weight);
    this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
    this.totalWeight_ += weight;
  }
  getTotalWeight() {
    return this.totalWeight_;
  }
  getEstimate() {
    if (this.alpha_) {
      const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
      if (zeroFactor) {
        return this.estimate_ / zeroFactor;
      }
    }
    return this.estimate_;
  }
};
var EwmaBandWidthEstimator = class {
  constructor(slow, fast, defaultEstimate, defaultTTFB = 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_ = defaultEstimate;
    this.minWeight_ = 1e-3;
    this.minDelayMs_ = 50;
    this.slow_ = new EWMA(slow);
    this.fast_ = new EWMA(fast);
    this.defaultTTFB_ = defaultTTFB;
    this.ttfb_ = new EWMA(slow);
  }
  update(slow, fast) {
    const {
      slow_,
      fast_,
      ttfb_
    } = this;
    if (slow_.halfLife !== slow) {
      this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
    }
    if (fast_.halfLife !== fast) {
      this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
    }
    if (ttfb_.halfLife !== slow) {
      this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
    }
  }
  sample(durationMs, numBytes) {
    durationMs = Math.max(durationMs, this.minDelayMs_);
    const numBits = 8 * numBytes;
    const durationS = durationMs / 1e3;
    const bandwidthInBps = numBits / durationS;
    this.fast_.sample(durationS, bandwidthInBps);
    this.slow_.sample(durationS, bandwidthInBps);
  }
  sampleTTFB(ttfb) {
    const seconds = ttfb / 1e3;
    const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
    this.ttfb_.sample(weight, Math.max(ttfb, 5));
  }
  canEstimate() {
    return this.fast_.getTotalWeight() >= this.minWeight_;
  }
  getEstimate() {
    if (this.canEstimate()) {
      return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
    } else {
      return this.defaultEstimate_;
    }
  }
  getEstimateTTFB() {
    if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
      return this.ttfb_.getEstimate();
    } else {
      return this.defaultTTFB_;
    }
  }
  get defaultEstimate() {
    return this.defaultEstimate_;
  }
  destroy() {
  }
};
function _defineProperty(e, r2, t2) {
  return (r2 = _toPropertyKey(r2)) in e ? Object.defineProperty(e, r2, {
    value: t2,
    enumerable: true,
    configurable: true,
    writable: true
  }) : e[r2] = t2, e;
}
function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function(n) {
    for (var e = 1; e < arguments.length; e++) {
      var t2 = arguments[e];
      for (var r2 in t2) ({}).hasOwnProperty.call(t2, r2) && (n[r2] = t2[r2]);
    }
    return n;
  }, _extends.apply(null, arguments);
}
function ownKeys(e, r2) {
  var t2 = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t2.push.apply(t2, o);
  }
  return t2;
}
function _objectSpread2(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys(Object(t2), true).forEach(function(r3) {
      _defineProperty(e, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t2)) : ownKeys(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e;
}
function _toPrimitive(t2, r2) {
  if ("object" != typeof t2 || !t2) return t2;
  var e = t2[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t2, r2);
    if ("object" != typeof i) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t2);
}
function _toPropertyKey(t2) {
  var i = _toPrimitive(t2, "string");
  return "symbol" == typeof i ? i : i + "";
}
var Logger = class {
  constructor(label, logger4) {
    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 lb = `[${label}]:`;
    this.trace = noop;
    this.debug = logger4.debug.bind(null, lb);
    this.log = logger4.log.bind(null, lb);
    this.warn = logger4.warn.bind(null, lb);
    this.info = logger4.info.bind(null, lb);
    this.error = logger4.error.bind(null, lb);
  }
};
var noop = function noop2() {
};
var fakeLogger = {
  trace: noop,
  debug: noop,
  log: noop,
  warn: noop,
  info: noop,
  error: noop
};
function createLogger() {
  return _extends({}, fakeLogger);
}
function consolePrintFn(type2, id) {
  const func = self.console[type2];
  return func ? func.bind(self.console, `${id ? "[" + id + "] " : ""}[${type2}] >`) : noop;
}
function getLoggerFn(key, debugConfig, id) {
  return debugConfig[key] ? debugConfig[key].bind(debugConfig) : consolePrintFn(key, id);
}
var exportedLogger = createLogger();
function enableLogs(debugConfig, context, id) {
  const newLogger = createLogger();
  if (typeof console === "object" && debugConfig === true || typeof debugConfig === "object") {
    const keys3 = [
      // Remove out from list here to hard-disable a log-level
      // 'trace',
      "debug",
      "log",
      "info",
      "warn",
      "error"
    ];
    keys3.forEach((key) => {
      newLogger[key] = getLoggerFn(key, debugConfig, id);
    });
    try {
      newLogger.log(`Debug logs enabled for "${context}" in hls.js version ${"1.6.1"}`);
    } catch (e) {
      return createLogger();
    }
    keys3.forEach((key) => {
      exportedLogger[key] = getLoggerFn(key, debugConfig);
    });
  } else {
    _extends(exportedLogger, newLogger);
  }
  return newLogger;
}
var logger = exportedLogger;
function getMediaSource(preferManagedMediaSource = true) {
  if (typeof self === "undefined") return void 0;
  const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  return mms || self.MediaSource || self.WebKitMediaSource;
}
function isManagedMediaSource(source) {
  return typeof self !== "undefined" && source === self.ManagedMediaSource;
}
function isCompatibleTrackChange(currentTracks, requiredTracks) {
  const trackNames = Object.keys(currentTracks);
  const requiredTrackNames = Object.keys(requiredTracks);
  const trackCount = trackNames.length;
  const requiredTrackCount = requiredTrackNames.length;
  return !trackCount || !requiredTrackCount || trackCount === requiredTrackCount && !trackNames.some((name) => requiredTrackNames.indexOf(name) === -1);
}
function utf8ArrayToStr(array, exitOnNull = false) {
  if (typeof TextDecoder !== "undefined") {
    const decoder = new TextDecoder("utf-8");
    const decoded = decoder.decode(array);
    if (exitOnNull) {
      const idx = decoded.indexOf("\0");
      return idx !== -1 ? decoded.substring(0, idx) : decoded;
    }
    return decoded.replace(/\0/g, "");
  }
  const len = array.length;
  let c;
  let char2;
  let char3;
  let out = "";
  let i = 0;
  while (i < len) {
    c = array[i++];
    if (c === 0 && exitOnNull) {
      return out;
    } else if (c === 0 || c === 3) {
      continue;
    }
    switch (c >> 4) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        out += String.fromCharCode(c);
        break;
      case 12:
      case 13:
        char2 = array[i++];
        out += String.fromCharCode((c & 31) << 6 | char2 & 63);
        break;
      case 14:
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode((c & 15) << 12 | (char2 & 63) << 6 | (char3 & 63) << 0);
        break;
    }
  }
  return out;
}
var Hex = {
  hexDump: function(array) {
    let str = "";
    for (let i = 0; i < array.length; i++) {
      let h = array[i].toString(16);
      if (h.length < 2) {
        h = "0" + h;
      }
      str += h;
    }
    return str;
  }
};
function getDefaultExportFromCjs(x) {
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var urlToolkit = {
  exports: {}
};
var hasRequiredUrlToolkit;
function requireUrlToolkit() {
  if (hasRequiredUrlToolkit) return urlToolkit.exports;
  hasRequiredUrlToolkit = 1;
  (function(module, exports) {
    (function(root) {
      var URL_REGEX = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
      var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
      var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
      var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
      var URLToolkit2 = {
        // 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(baseURL, relativeURL, opts) {
          opts = opts || {};
          baseURL = baseURL.trim();
          relativeURL = relativeURL.trim();
          if (!relativeURL) {
            if (!opts.alwaysNormalize) {
              return baseURL;
            }
            var basePartsForNormalise = URLToolkit2.parseURL(baseURL);
            if (!basePartsForNormalise) {
              throw new Error("Error trying to parse base URL.");
            }
            basePartsForNormalise.path = URLToolkit2.normalizePath(basePartsForNormalise.path);
            return URLToolkit2.buildURLFromParts(basePartsForNormalise);
          }
          var relativeParts = URLToolkit2.parseURL(relativeURL);
          if (!relativeParts) {
            throw new Error("Error trying to parse relative URL.");
          }
          if (relativeParts.scheme) {
            if (!opts.alwaysNormalize) {
              return relativeURL;
            }
            relativeParts.path = URLToolkit2.normalizePath(relativeParts.path);
            return URLToolkit2.buildURLFromParts(relativeParts);
          }
          var baseParts = URLToolkit2.parseURL(baseURL);
          if (!baseParts) {
            throw new Error("Error trying to parse base URL.");
          }
          if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== "/") {
            var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
            baseParts.netLoc = pathParts[1];
            baseParts.path = pathParts[2];
          }
          if (baseParts.netLoc && !baseParts.path) {
            baseParts.path = "/";
          }
          var builtParts = {
            // 2c) Otherwise, the embedded URL inherits the scheme of
            // the base URL.
            scheme: baseParts.scheme,
            netLoc: relativeParts.netLoc,
            path: null,
            params: relativeParts.params,
            query: relativeParts.query,
            fragment: relativeParts.fragment
          };
          if (!relativeParts.netLoc) {
            builtParts.netLoc = baseParts.netLoc;
            if (relativeParts.path[0] !== "/") {
              if (!relativeParts.path) {
                builtParts.path = baseParts.path;
                if (!relativeParts.params) {
                  builtParts.params = baseParts.params;
                  if (!relativeParts.query) {
                    builtParts.query = baseParts.query;
                  }
                }
              } else {
                var baseURLPath = baseParts.path;
                var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf("/") + 1) + relativeParts.path;
                builtParts.path = URLToolkit2.normalizePath(newPath);
              }
            }
          }
          if (builtParts.path === null) {
            builtParts.path = opts.alwaysNormalize ? URLToolkit2.normalizePath(relativeParts.path) : relativeParts.path;
          }
          return URLToolkit2.buildURLFromParts(builtParts);
        },
        parseURL: function(url) {
          var parts = URL_REGEX.exec(url);
          if (!parts) {
            return null;
          }
          return {
            scheme: parts[1] || "",
            netLoc: parts[2] || "",
            path: parts[3] || "",
            params: parts[4] || "",
            query: parts[5] || "",
            fragment: parts[6] || ""
          };
        },
        normalizePath: function(path) {
          path = path.split("").reverse().join("").replace(SLASH_DOT_REGEX, "");
          while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, "")).length) {
          }
          return path.split("").reverse().join("");
        },
        buildURLFromParts: function(parts) {
          return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
        }
      };
      module.exports = URLToolkit2;
    })();
  })(urlToolkit);
  return urlToolkit.exports;
}
var urlToolkitExports = requireUrlToolkit();
var LoadStats = class {
  constructor() {
    this.aborted = false;
    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 ElementaryStreamTypes = {
  AUDIO: "audio",
  VIDEO: "video",
  AUDIOVIDEO: "audiovideo"
};
var BaseSegment = class {
  constructor(base) {
    this._byteRange = null;
    this._url = null;
    this._stats = null;
    this._streams = null;
    this.base = void 0;
    this.relurl = void 0;
    if (typeof base === "string") {
      base = {
        url: base
      };
    }
    this.base = base;
    makeEnumerable(this, "stats");
  }
  // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  setByteRange(value, previous) {
    const params = value.split("@", 2);
    let start2;
    if (params.length === 1) {
      start2 = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
    } else {
      start2 = parseInt(params[1]);
    }
    this._byteRange = [start2, parseInt(params[0]) + start2];
  }
  get baseurl() {
    return this.base.url;
  }
  get byteRange() {
    if (this._byteRange === null) {
      return [];
    }
    return this._byteRange;
  }
  get byteRangeStartOffset() {
    return this.byteRange[0];
  }
  get byteRangeEndOffset() {
    return this.byteRange[1];
  }
  get elementaryStreams() {
    if (this._streams === null) {
      this._streams = {
        [ElementaryStreamTypes.AUDIO]: null,
        [ElementaryStreamTypes.VIDEO]: null,
        [ElementaryStreamTypes.AUDIOVIDEO]: null
      };
    }
    return this._streams;
  }
  set elementaryStreams(value) {
    this._streams = value;
  }
  get hasStats() {
    return this._stats !== null;
  }
  get hasStreams() {
    return this._streams !== null;
  }
  get stats() {
    if (this._stats === null) {
      this._stats = new LoadStats();
    }
    return this._stats;
  }
  set stats(value) {
    this._stats = value;
  }
  get url() {
    if (!this._url && this.baseurl && this.relurl) {
      this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
        alwaysNormalize: true
      });
    }
    return this._url || "";
  }
  set url(value) {
    this._url = value;
  }
  clearElementaryStreamInfo() {
    const {
      elementaryStreams
    } = this;
    elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
    elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
    elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  }
};
function isMediaFragment(frag) {
  return frag.sn !== "initSegment";
}
var Fragment = class extends BaseSegment {
  constructor(type2, base) {
    super(base);
    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 = false;
    this.title = null;
    this.initSegment = null;
    this.endList = void 0;
    this.gap = void 0;
    this.urlId = 0;
    this.type = type2;
  }
  get byteLength() {
    if (this.hasStats) {
      const total = this.stats.total;
      if (total) {
        return total;
      }
    }
    if (this.byteRange) {
      const start2 = this.byteRange[0];
      const end = this.byteRange[1];
      if (isFiniteNumber(start2) && isFiniteNumber(end)) {
        return end - start2;
      }
    }
    return null;
  }
  get bitrate() {
    if (this.byteLength) {
      return this.byteLength * 8 / this.duration;
    }
    if (this._bitrate) {
      return this._bitrate;
    }
    return null;
  }
  set bitrate(value) {
    this._bitrate = value;
  }
  get decryptdata() {
    const {
      levelkeys
    } = this;
    if (!levelkeys && !this._decryptdata) {
      return null;
    }
    if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
      const key = this.levelkeys.identity;
      if (key) {
        this._decryptdata = key.getDecryptData(this.sn);
      } else {
        const keyFormats = Object.keys(this.levelkeys);
        if (keyFormats.length === 1) {
          return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
        }
      }
    }
    return this._decryptdata;
  }
  get end() {
    return this.start + this.duration;
  }
  get endProgramDateTime() {
    if (this.programDateTime === null) {
      return null;
    }
    const duration5 = !isFiniteNumber(this.duration) ? 0 : this.duration;
    return this.programDateTime + duration5 * 1e3;
  }
  get encrypted() {
    var _this$_decryptdata;
    if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
      return true;
    } else if (this.levelkeys) {
      const keyFormats = Object.keys(this.levelkeys);
      const len = keyFormats.length;
      if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
        return true;
      }
    }
    return false;
  }
  get programDateTime() {
    if (this._programDateTime === null && this.rawProgramDateTime) {
      this.programDateTime = Date.parse(this.rawProgramDateTime);
    }
    return this._programDateTime;
  }
  set programDateTime(value) {
    if (!isFiniteNumber(value)) {
      this._programDateTime = this.rawProgramDateTime = null;
      return;
    }
    this._programDateTime = value;
  }
  get ref() {
    if (!isMediaFragment(this)) {
      return null;
    }
    if (!this._ref) {
      this._ref = {
        base: this.base,
        start: this.start,
        duration: this.duration,
        sn: this.sn,
        programDateTime: this.programDateTime
      };
    }
    return this._ref;
  }
  addStart(value) {
    this.setStart(this.start + value);
  }
  setStart(value) {
    this.start = value;
    if (this._ref) {
      this._ref.start = value;
    }
  }
  setDuration(value) {
    this.duration = value;
    if (this._ref) {
      this._ref.duration = value;
    }
  }
  setKeyFormat(keyFormat) {
    if (this.levelkeys) {
      const key = this.levelkeys[keyFormat];
      if (key && !this._decryptdata) {
        this._decryptdata = key.getDecryptData(this.sn);
      }
    }
  }
  abortRequests() {
    var _this$loader, _this$keyLoader;
    (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
    (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  }
  setElementaryStreamInfo(type2, startPTS, endPTS, startDTS, endDTS, partial = false) {
    const {
      elementaryStreams
    } = this;
    const info = elementaryStreams[type2];
    if (!info) {
      elementaryStreams[type2] = {
        startPTS,
        endPTS,
        startDTS,
        endDTS,
        partial
      };
      return;
    }
    info.startPTS = Math.min(info.startPTS, startPTS);
    info.endPTS = Math.max(info.endPTS, endPTS);
    info.startDTS = Math.min(info.startDTS, startDTS);
    info.endDTS = Math.max(info.endDTS, endDTS);
  }
};
var Part = class extends BaseSegment {
  constructor(partAttrs, frag, base, index, previous) {
    super(base);
    this.fragOffset = 0;
    this.duration = 0;
    this.gap = false;
    this.independent = false;
    this.relurl = void 0;
    this.fragment = void 0;
    this.index = void 0;
    this.duration = partAttrs.decimalFloatingPoint("DURATION");
    this.gap = partAttrs.bool("GAP");
    this.independent = partAttrs.bool("INDEPENDENT");
    this.relurl = partAttrs.enumeratedString("URI");
    this.fragment = frag;
    this.index = index;
    const byteRange = partAttrs.enumeratedString("BYTERANGE");
    if (byteRange) {
      this.setByteRange(byteRange, previous);
    }
    if (previous) {
      this.fragOffset = previous.fragOffset + previous.duration;
    }
  }
  get start() {
    return this.fragment.start + this.fragOffset;
  }
  get end() {
    return this.start + this.duration;
  }
  get loaded() {
    const {
      elementaryStreams
    } = this;
    return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  }
};
function getOwnPropertyDescriptorFromPrototypeChain(object, property) {
  const prototype = Object.getPrototypeOf(object);
  if (prototype) {
    const propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, property);
    if (propertyDescriptor) {
      return propertyDescriptor;
    }
    return getOwnPropertyDescriptorFromPrototypeChain(prototype, property);
  }
}
function makeEnumerable(object, property) {
  const d2 = getOwnPropertyDescriptorFromPrototypeChain(object, property);
  if (d2) {
    d2.enumerable = true;
    Object.defineProperty(object, property, d2);
  }
}
var UINT32_MAX$1 = Math.pow(2, 32) - 1;
var push = [].push;
var RemuxerTrackIdConfig = {
  video: 1,
  audio: 2,
  id3: 3,
  text: 4
};
function bin2str(data) {
  return String.fromCharCode.apply(null, data);
}
function readUint16(buffer, offset) {
  const val = buffer[offset] << 8 | buffer[offset + 1];
  return val < 0 ? 65536 + val : val;
}
function readUint32(buffer, offset) {
  const val = readSint32(buffer, offset);
  return val < 0 ? 4294967296 + val : val;
}
function readUint64(buffer, offset) {
  let result = readUint32(buffer, offset);
  result *= Math.pow(2, 32);
  result += readUint32(buffer, offset + 4);
  return result;
}
function readSint32(buffer, offset) {
  return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
}
function writeUint32(buffer, offset, value) {
  buffer[offset] = value >> 24;
  buffer[offset + 1] = value >> 16 & 255;
  buffer[offset + 2] = value >> 8 & 255;
  buffer[offset + 3] = value & 255;
}
function hasMoofData(data) {
  const end = data.byteLength;
  for (let i = 0; i < end; ) {
    const size = readUint32(data, i);
    if (size > 8 && data[i + 4] === 109 && data[i + 5] === 111 && data[i + 6] === 111 && data[i + 7] === 102) {
      return true;
    }
    i = size > 1 ? i + size : end;
  }
  return false;
}
function findBox(data, path) {
  const results = [];
  if (!path.length) {
    return results;
  }
  const end = data.byteLength;
  for (let i = 0; i < end; ) {
    const size = readUint32(data, i);
    const type2 = bin2str(data.subarray(i + 4, i + 8));
    const endbox = size > 1 ? i + size : end;
    if (type2 === path[0]) {
      if (path.length === 1) {
        results.push(data.subarray(i + 8, endbox));
      } else {
        const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
        if (subresults.length) {
          push.apply(results, subresults);
        }
      }
    }
    i = endbox;
  }
  return results;
}
function parseSegmentIndex(sidx) {
  const references = [];
  const version6 = sidx[0];
  let index = 8;
  const timescale2 = readUint32(sidx, index);
  index += 4;
  let earliestPresentationTime = 0;
  let firstOffset = 0;
  if (version6 === 0) {
    earliestPresentationTime = readUint32(sidx, index);
    firstOffset = readUint32(sidx, index + 4);
    index += 8;
  } else {
    earliestPresentationTime = readUint64(sidx, index);
    firstOffset = readUint64(sidx, index + 8);
    index += 16;
  }
  index += 2;
  let startByte = sidx.length + firstOffset;
  const referencesCount = readUint16(sidx, index);
  index += 2;
  for (let i = 0; i < referencesCount; i++) {
    let referenceIndex = index;
    const referenceInfo = readUint32(sidx, referenceIndex);
    referenceIndex += 4;
    const referenceSize = referenceInfo & 2147483647;
    const referenceType = (referenceInfo & 2147483648) >>> 31;
    if (referenceType === 1) {
      logger.warn("SIDX has hierarchical references (not supported)");
      return null;
    }
    const subsegmentDuration = readUint32(sidx, referenceIndex);
    referenceIndex += 4;
    references.push({
      referenceSize,
      subsegmentDuration,
      // unscaled
      info: {
        duration: subsegmentDuration / timescale2,
        start: startByte,
        end: startByte + referenceSize - 1
      }
    });
    startByte += referenceSize;
    referenceIndex += 4;
    index = referenceIndex;
  }
  return {
    earliestPresentationTime,
    timescale: timescale2,
    version: version6,
    referencesCount,
    references
  };
}
function parseInitSegment(initSegment) {
  const result = [];
  const traks = findBox(initSegment, ["moov", "trak"]);
  for (let i = 0; i < traks.length; i++) {
    const trak = traks[i];
    const tkhd = findBox(trak, ["tkhd"])[0];
    if (tkhd) {
      let version6 = tkhd[0];
      const trackId = readUint32(tkhd, version6 === 0 ? 12 : 20);
      const mdhd = findBox(trak, ["mdia", "mdhd"])[0];
      if (mdhd) {
        version6 = mdhd[0];
        const timescale2 = readUint32(mdhd, version6 === 0 ? 12 : 20);
        const hdlr = findBox(trak, ["mdia", "hdlr"])[0];
        if (hdlr) {
          const hdlrType = bin2str(hdlr.subarray(8, 12));
          const type2 = {
            soun: ElementaryStreamTypes.AUDIO,
            vide: ElementaryStreamTypes.VIDEO
          }[hdlrType];
          const stsdBox = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
          const stsd = parseStsd(stsdBox);
          if (type2) {
            result[trackId] = {
              timescale: timescale2,
              type: type2,
              stsd
            };
            result[type2] = _objectSpread2({
              timescale: timescale2,
              id: trackId
            }, stsd);
          } else {
            result[trackId] = {
              timescale: timescale2,
              type: hdlrType,
              stsd
            };
          }
        }
      }
    }
  }
  const trex = findBox(initSegment, ["moov", "mvex", "trex"]);
  trex.forEach((trex2) => {
    const trackId = readUint32(trex2, 4);
    const track = result[trackId];
    if (track) {
      track.default = {
        duration: readUint32(trex2, 12),
        flags: readUint32(trex2, 20)
      };
    }
  });
  return result;
}
function parseStsd(stsd) {
  const sampleEntries = stsd.subarray(8);
  const sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  const fourCC = bin2str(sampleEntries.subarray(4, 8));
  let codec = fourCC;
  let supplemental;
  const encrypted = fourCC === "enca" || fourCC === "encv";
  if (encrypted) {
    const encBox = findBox(sampleEntries, [fourCC])[0];
    const encBoxChildren = encBox.subarray(fourCC === "enca" ? 28 : 78);
    const sinfs = findBox(encBoxChildren, ["sinf"]);
    sinfs.forEach((sinf) => {
      const schm = findBox(sinf, ["schm"])[0];
      if (schm) {
        const scheme = bin2str(schm.subarray(4, 8));
        if (scheme === "cbcs" || scheme === "cenc") {
          const frma = findBox(sinf, ["frma"])[0];
          if (frma) {
            codec = bin2str(frma);
          }
        }
      }
    });
  }
  const codecFourCC = codec;
  switch (codec) {
    case "avc1":
    case "avc2":
    case "avc3":
    case "avc4": {
      const avcCBox = findBox(sampleEntriesEnd, ["avcC"])[0];
      if (avcCBox && avcCBox.length > 3) {
        codec += "." + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
        supplemental = parseSupplementalDoViCodec(codecFourCC === "avc1" ? "dva1" : "dvav", sampleEntriesEnd);
      }
      break;
    }
    case "mp4a": {
      const codecBox = findBox(sampleEntries, [fourCC])[0];
      const esdsBox = findBox(codecBox.subarray(28), ["esds"])[0];
      if (esdsBox && esdsBox.length > 7) {
        let i = 4;
        if (esdsBox[i++] !== 3) {
          break;
        }
        i = skipBERInteger(esdsBox, i);
        i += 2;
        const flags = esdsBox[i++];
        if (flags & 128) {
          i += 2;
        }
        if (flags & 64) {
          i += esdsBox[i++];
        }
        if (esdsBox[i++] !== 4) {
          break;
        }
        i = skipBERInteger(esdsBox, i);
        const objectType = esdsBox[i++];
        if (objectType === 64) {
          codec += "." + toHex(objectType);
        } else {
          break;
        }
        i += 12;
        if (esdsBox[i++] !== 5) {
          break;
        }
        i = skipBERInteger(esdsBox, i);
        const firstByte = esdsBox[i++];
        let audioObjectType = (firstByte & 248) >> 3;
        if (audioObjectType === 31) {
          audioObjectType += 1 + ((firstByte & 7) << 3) + ((esdsBox[i] & 224) >> 5);
        }
        codec += "." + audioObjectType;
      }
      break;
    }
    case "hvc1":
    case "hev1": {
      const hvcCBox = findBox(sampleEntriesEnd, ["hvcC"])[0];
      if (hvcCBox && hvcCBox.length > 12) {
        const profileByte = hvcCBox[1];
        const profileSpace = ["", "A", "B", "C"][profileByte >> 6];
        const generalProfileIdc = profileByte & 31;
        const profileCompat = readUint32(hvcCBox, 2);
        const tierFlag = (profileByte & 32) >> 5 ? "H" : "L";
        const levelIDC = hvcCBox[12];
        const constraintIndicator = hvcCBox.subarray(6, 12);
        codec += "." + profileSpace + generalProfileIdc;
        codec += "." + profileCompat.toString(16).toUpperCase();
        codec += "." + tierFlag + levelIDC;
        let constraintString = "";
        for (let i = constraintIndicator.length; i--; ) {
          const byte = constraintIndicator[i];
          if (byte || constraintString) {
            const encodedByte = byte.toString(16).toUpperCase();
            constraintString = "." + encodedByte + constraintString;
          }
        }
        codec += constraintString;
      }
      supplemental = parseSupplementalDoViCodec(codecFourCC == "hev1" ? "dvhe" : "dvh1", sampleEntriesEnd);
      break;
    }
    case "dvh1":
    case "dvhe":
    case "dvav":
    case "dva1":
    case "dav1": {
      codec = parseSupplementalDoViCodec(codec, sampleEntriesEnd) || codec;
      break;
    }
    case "vp09": {
      const vpcCBox = findBox(sampleEntriesEnd, ["vpcC"])[0];
      if (vpcCBox && vpcCBox.length > 6) {
        const profile = vpcCBox[4];
        const level = vpcCBox[5];
        const bitDepth = vpcCBox[6] >> 4 & 15;
        codec += "." + addLeadingZero(profile) + "." + addLeadingZero(level) + "." + addLeadingZero(bitDepth);
      }
      break;
    }
    case "av01": {
      const av1CBox = findBox(sampleEntriesEnd, ["av1C"])[0];
      if (av1CBox && av1CBox.length > 2) {
        const profile = av1CBox[1] >>> 5;
        const level = av1CBox[1] & 31;
        const tierFlag = av1CBox[2] >>> 7 ? "H" : "M";
        const highBitDepth = (av1CBox[2] & 64) >> 6;
        const twelveBit = (av1CBox[2] & 32) >> 5;
        const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
        const monochrome = (av1CBox[2] & 16) >> 4;
        const chromaSubsamplingX = (av1CBox[2] & 8) >> 3;
        const chromaSubsamplingY = (av1CBox[2] & 4) >> 2;
        const chromaSamplePosition = av1CBox[2] & 3;
        const colorPrimaries = 1;
        const transferCharacteristics = 1;
        const matrixCoefficients = 1;
        const videoFullRangeFlag = 0;
        codec += "." + profile + "." + addLeadingZero(level) + tierFlag + "." + addLeadingZero(bitDepth) + "." + monochrome + "." + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + "." + addLeadingZero(colorPrimaries) + "." + addLeadingZero(transferCharacteristics) + "." + addLeadingZero(matrixCoefficients) + "." + videoFullRangeFlag;
        supplemental = parseSupplementalDoViCodec("dav1", sampleEntriesEnd);
      }
      break;
    }
  }
  return {
    codec,
    encrypted,
    supplemental
  };
}
function parseSupplementalDoViCodec(fourCC, sampleEntriesEnd) {
  const dvvCResult = findBox(sampleEntriesEnd, ["dvvC"]);
  const dvXCBox = dvvCResult.length ? dvvCResult[0] : findBox(sampleEntriesEnd, ["dvcC"])[0];
  if (dvXCBox) {
    const doViProfile = dvXCBox[2] >> 1 & 127;
    const doViLevel = dvXCBox[2] << 5 & 32 | dvXCBox[3] >> 3 & 31;
    return fourCC + "." + addLeadingZero(doViProfile) + "." + addLeadingZero(doViLevel);
  }
}
function skipBERInteger(bytes, i) {
  const limit = i + 5;
  while (bytes[i++] & 128 && i < limit) {
  }
  return i;
}
function toHex(x) {
  return ("0" + x.toString(16).toUpperCase()).slice(-2);
}
function addLeadingZero(num) {
  return (num < 10 ? "0" : "") + num;
}
function patchEncyptionData(initSegment, decryptdata) {
  if (!initSegment || !decryptdata) {
    return initSegment;
  }
  const keyId = decryptdata.keyId;
  if (keyId && decryptdata.isCommonEncryption) {
    const traks = findBox(initSegment, ["moov", "trak"]);
    traks.forEach((trak) => {
      const stsd = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
      const sampleEntries = stsd.subarray(8);
      let encBoxes = findBox(sampleEntries, ["enca"]);
      const isAudio = encBoxes.length > 0;
      if (!isAudio) {
        encBoxes = findBox(sampleEntries, ["encv"]);
      }
      encBoxes.forEach((enc) => {
        const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
        const sinfBoxes = findBox(encBoxChildren, ["sinf"]);
        sinfBoxes.forEach((sinf) => {
          const tenc = parseSinf(sinf);
          if (tenc) {
            const tencKeyId = tenc.subarray(8, 24);
            if (!tencKeyId.some((b) => b !== 0)) {
              logger.log(`[eme] Patching keyId in 'enc${isAudio ? "a" : "v"}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`);
              tenc.set(keyId, 8);
            }
          }
        });
      });
    });
  }
  return initSegment;
}
function parseSinf(sinf) {
  const schm = findBox(sinf, ["schm"])[0];
  if (schm) {
    const scheme = bin2str(schm.subarray(4, 8));
    if (scheme === "cbcs" || scheme === "cenc") {
      return findBox(sinf, ["schi", "tenc"])[0];
    }
  }
  return null;
}
function getStartDTS(initData, fmp4) {
  return findBox(fmp4, ["moof", "traf"]).reduce((result, traf) => {
    const tfdt = findBox(traf, ["tfdt"])[0];
    const version6 = tfdt[0];
    const start2 = findBox(traf, ["tfhd"]).reduce((result2, tfhd) => {
      const id = readUint32(tfhd, 4);
      const track = initData[id];
      if (track) {
        let baseTime = readUint32(tfdt, 4);
        if (version6 === 1) {
          if (baseTime === UINT32_MAX$1) {
            logger.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);
            return result2;
          }
          baseTime *= UINT32_MAX$1 + 1;
          baseTime += readUint32(tfdt, 8);
        }
        const scale = track.timescale || 9e4;
        const startTime = baseTime / scale;
        if (isFiniteNumber(startTime) && (result2 === null || startTime < result2)) {
          return startTime;
        }
      }
      return result2;
    }, null);
    if (start2 !== null && isFiniteNumber(start2) && (result === null || start2 < result)) {
      return start2;
    }
    return result;
  }, null);
}
function getDuration(data, initData) {
  let rawDuration = 0;
  let videoDuration = 0;
  let audioDuration = 0;
  const trafs = findBox(data, ["moof", "traf"]);
  for (let i = 0; i < trafs.length; i++) {
    const traf = trafs[i];
    const tfhd = findBox(traf, ["tfhd"])[0];
    const id = readUint32(tfhd, 4);
    const track = initData[id];
    if (!track) {
      continue;
    }
    const trackDefault = track.default;
    const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
    let sampleDuration = trackDefault == null ? void 0 : trackDefault.duration;
    if (tfhdFlags & 8) {
      if (tfhdFlags & 2) {
        sampleDuration = readUint32(tfhd, 12);
      } else {
        sampleDuration = readUint32(tfhd, 8);
      }
    }
    const timescale2 = track.timescale || 9e4;
    const truns = findBox(traf, ["trun"]);
    for (let j = 0; j < truns.length; j++) {
      rawDuration = computeRawDurationFromSamples(truns[j]);
      if (!rawDuration && sampleDuration) {
        const sampleCount = readUint32(truns[j], 4);
        rawDuration = sampleDuration * sampleCount;
      }
      if (track.type === ElementaryStreamTypes.VIDEO) {
        videoDuration += rawDuration / timescale2;
      } else if (track.type === ElementaryStreamTypes.AUDIO) {
        audioDuration += rawDuration / timescale2;
      }
    }
  }
  if (videoDuration === 0 && audioDuration === 0) {
    let sidxMinStart = Infinity;
    let sidxMaxEnd = 0;
    let sidxDuration = 0;
    const sidxs = findBox(data, ["sidx"]);
    for (let i = 0; i < sidxs.length; i++) {
      const sidx = parseSegmentIndex(sidxs[i]);
      if (sidx != null && sidx.references) {
        sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
        const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0);
        sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
        sidxDuration = sidxMaxEnd - sidxMinStart;
      }
    }
    if (sidxDuration && isFiniteNumber(sidxDuration)) {
      return sidxDuration;
    }
  }
  if (videoDuration) {
    return videoDuration;
  }
  return audioDuration;
}
function computeRawDurationFromSamples(trun) {
  const flags = readUint32(trun, 0);
  let offset = 8;
  if (flags & 1) {
    offset += 4;
  }
  if (flags & 4) {
    offset += 4;
  }
  let duration5 = 0;
  const sampleCount = readUint32(trun, 4);
  for (let i = 0; i < sampleCount; i++) {
    if (flags & 256) {
      const sampleDuration = readUint32(trun, offset);
      duration5 += sampleDuration;
      offset += 4;
    }
    if (flags & 512) {
      offset += 4;
    }
    if (flags & 1024) {
      offset += 4;
    }
    if (flags & 2048) {
      offset += 4;
    }
  }
  return duration5;
}
function offsetStartDTS(initData, fmp4, timeOffset) {
  findBox(fmp4, ["moof", "traf"]).forEach((traf) => {
    findBox(traf, ["tfhd"]).forEach((tfhd) => {
      const id = readUint32(tfhd, 4);
      const track = initData[id];
      if (!track) {
        return;
      }
      const timescale2 = track.timescale || 9e4;
      findBox(traf, ["tfdt"]).forEach((tfdt) => {
        const version6 = tfdt[0];
        const offset = timeOffset * timescale2;
        if (offset) {
          let baseMediaDecodeTime = readUint32(tfdt, 4);
          if (version6 === 0) {
            baseMediaDecodeTime -= offset;
            baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
            writeUint32(tfdt, 4, baseMediaDecodeTime);
          } else {
            baseMediaDecodeTime *= Math.pow(2, 32);
            baseMediaDecodeTime += readUint32(tfdt, 8);
            baseMediaDecodeTime -= offset;
            baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
            const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX$1 + 1));
            const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX$1 + 1));
            writeUint32(tfdt, 4, upper);
            writeUint32(tfdt, 8, lower);
          }
        }
      });
    });
  });
}
function segmentValidRange(data) {
  const segmentedRange = {
    valid: null,
    remainder: null
  };
  const moofs = findBox(data, ["moof"]);
  if (moofs.length < 2) {
    segmentedRange.remainder = data;
    return segmentedRange;
  }
  const last = moofs[moofs.length - 1];
  segmentedRange.valid = data.slice(0, last.byteOffset - 8);
  segmentedRange.remainder = data.slice(last.byteOffset - 8);
  return segmentedRange;
}
function appendUint8Array(data1, data2) {
  const temp = new Uint8Array(data1.length + data2.length);
  temp.set(data1);
  temp.set(data2, data1.length);
  return temp;
}
function parseSamples(timeOffset, track) {
  const seiSamples = [];
  const videoData = track.samples;
  const timescale2 = track.timescale;
  const trackId = track.id;
  let isHEVCFlavor = false;
  const moofs = findBox(videoData, ["moof"]);
  moofs.map((moof) => {
    const moofOffset = moof.byteOffset - 8;
    const trafs = findBox(moof, ["traf"]);
    trafs.map((traf) => {
      const baseTime = findBox(traf, ["tfdt"]).map((tfdt) => {
        const version6 = tfdt[0];
        let result = readUint32(tfdt, 4);
        if (version6 === 1) {
          result *= Math.pow(2, 32);
          result += readUint32(tfdt, 8);
        }
        return result / timescale2;
      })[0];
      if (baseTime !== void 0) {
        timeOffset = baseTime;
      }
      return findBox(traf, ["tfhd"]).map((tfhd) => {
        const id = readUint32(tfhd, 4);
        const tfhdFlags = readUint32(tfhd, 0) & 16777215;
        const baseDataOffsetPresent = (tfhdFlags & 1) !== 0;
        const sampleDescriptionIndexPresent = (tfhdFlags & 2) !== 0;
        const defaultSampleDurationPresent = (tfhdFlags & 8) !== 0;
        let defaultSampleDuration = 0;
        const defaultSampleSizePresent = (tfhdFlags & 16) !== 0;
        let defaultSampleSize = 0;
        const defaultSampleFlagsPresent = (tfhdFlags & 32) !== 0;
        let tfhdOffset = 8;
        if (id === trackId) {
          if (baseDataOffsetPresent) {
            tfhdOffset += 8;
          }
          if (sampleDescriptionIndexPresent) {
            tfhdOffset += 4;
          }
          if (defaultSampleDurationPresent) {
            defaultSampleDuration = readUint32(tfhd, tfhdOffset);
            tfhdOffset += 4;
          }
          if (defaultSampleSizePresent) {
            defaultSampleSize = readUint32(tfhd, tfhdOffset);
            tfhdOffset += 4;
          }
          if (defaultSampleFlagsPresent) {
            tfhdOffset += 4;
          }
          if (track.type === "video") {
            isHEVCFlavor = isHEVC(track.codec);
          }
          findBox(traf, ["trun"]).map((trun) => {
            const version6 = trun[0];
            const flags = readUint32(trun, 0) & 16777215;
            const dataOffsetPresent = (flags & 1) !== 0;
            let dataOffset = 0;
            const firstSampleFlagsPresent = (flags & 4) !== 0;
            const sampleDurationPresent = (flags & 256) !== 0;
            let sampleDuration = 0;
            const sampleSizePresent = (flags & 512) !== 0;
            let sampleSize = 0;
            const sampleFlagsPresent = (flags & 1024) !== 0;
            const sampleCompositionOffsetsPresent = (flags & 2048) !== 0;
            let compositionOffset = 0;
            const sampleCount = readUint32(trun, 4);
            let trunOffset = 8;
            if (dataOffsetPresent) {
              dataOffset = readUint32(trun, trunOffset);
              trunOffset += 4;
            }
            if (firstSampleFlagsPresent) {
              trunOffset += 4;
            }
            let sampleOffset = dataOffset + moofOffset;
            for (let ix = 0; ix < sampleCount; ix++) {
              if (sampleDurationPresent) {
                sampleDuration = readUint32(trun, trunOffset);
                trunOffset += 4;
              } else {
                sampleDuration = defaultSampleDuration;
              }
              if (sampleSizePresent) {
                sampleSize = readUint32(trun, trunOffset);
                trunOffset += 4;
              } else {
                sampleSize = defaultSampleSize;
              }
              if (sampleFlagsPresent) {
                trunOffset += 4;
              }
              if (sampleCompositionOffsetsPresent) {
                if (version6 === 0) {
                  compositionOffset = readUint32(trun, trunOffset);
                } else {
                  compositionOffset = readSint32(trun, trunOffset);
                }
                trunOffset += 4;
              }
              if (track.type === ElementaryStreamTypes.VIDEO) {
                let naluTotalSize = 0;
                while (naluTotalSize < sampleSize) {
                  const naluSize = readUint32(videoData, sampleOffset);
                  sampleOffset += 4;
                  if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
                    const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
                    parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale2, seiSamples);
                  }
                  sampleOffset += naluSize;
                  naluTotalSize += naluSize + 4;
                }
              }
              timeOffset += sampleDuration / timescale2;
            }
          });
        }
      });
    });
  });
  return seiSamples;
}
function isHEVC(codec) {
  if (!codec) {
    return false;
  }
  const baseCodec = codec.substring(0, 4);
  return baseCodec === "hvc1" || baseCodec === "hev1" || // Dolby Vision
  baseCodec === "dvh1" || baseCodec === "dvhe";
}
function isSEIMessage(isHEVCFlavor, naluHeader) {
  if (isHEVCFlavor) {
    const naluType = naluHeader >> 1 & 63;
    return naluType === 39 || naluType === 40;
  } else {
    const naluType = naluHeader & 31;
    return naluType === 6;
  }
}
function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  const data = discardEPB(unescapedData);
  let seiPtr = 0;
  seiPtr += headerSize;
  let payloadType = 0;
  let payloadSize = 0;
  let b = 0;
  while (seiPtr < data.length) {
    payloadType = 0;
    do {
      if (seiPtr >= data.length) {
        break;
      }
      b = data[seiPtr++];
      payloadType += b;
    } while (b === 255);
    payloadSize = 0;
    do {
      if (seiPtr >= data.length) {
        break;
      }
      b = data[seiPtr++];
      payloadSize += b;
    } while (b === 255);
    const leftOver = data.length - seiPtr;
    let payPtr = seiPtr;
    if (payloadSize < leftOver) {
      seiPtr += payloadSize;
    } else if (payloadSize > leftOver) {
      logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);
      break;
    }
    if (payloadType === 4) {
      const countryCode = data[payPtr++];
      if (countryCode === 181) {
        const providerCode = readUint16(data, payPtr);
        payPtr += 2;
        if (providerCode === 49) {
          const userStructure = readUint32(data, payPtr);
          payPtr += 4;
          if (userStructure === 1195456820) {
            const userDataType = data[payPtr++];
            if (userDataType === 3) {
              const firstByte = data[payPtr++];
              const totalCCs = 31 & firstByte;
              const enabled = 64 & firstByte;
              const totalBytes = enabled ? 2 + totalCCs * 3 : 0;
              const byteArray = new Uint8Array(totalBytes);
              if (enabled) {
                byteArray[0] = firstByte;
                for (let i = 1; i < totalBytes; i++) {
                  byteArray[i] = data[payPtr++];
                }
              }
              samples.push({
                type: userDataType,
                payloadType,
                pts,
                bytes: byteArray
              });
            }
          }
        }
      }
    } else if (payloadType === 5) {
      if (payloadSize > 16) {
        const uuidStrArray = [];
        for (let i = 0; i < 16; i++) {
          const _b = data[payPtr++].toString(16);
          uuidStrArray.push(_b.length == 1 ? "0" + _b : _b);
          if (i === 3 || i === 5 || i === 7 || i === 9) {
            uuidStrArray.push("-");
          }
        }
        const length = payloadSize - 16;
        const userDataBytes = new Uint8Array(length);
        for (let i = 0; i < length; i++) {
          userDataBytes[i] = data[payPtr++];
        }
        samples.push({
          payloadType,
          pts,
          uuid: uuidStrArray.join(""),
          userData: utf8ArrayToStr(userDataBytes),
          userDataBytes
        });
      }
    }
  }
}
function discardEPB(data) {
  const length = data.byteLength;
  const EPBPositions = [];
  let i = 1;
  while (i < length - 2) {
    if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 3) {
      EPBPositions.push(i + 2);
      i += 2;
    } else {
      i++;
    }
  }
  if (EPBPositions.length === 0) {
    return data;
  }
  const newLength = length - EPBPositions.length;
  const newData = new Uint8Array(newLength);
  let sourceIndex = 0;
  for (i = 0; i < newLength; sourceIndex++, i++) {
    if (sourceIndex === EPBPositions[0]) {
      sourceIndex++;
      EPBPositions.shift();
    }
    newData[i] = data[sourceIndex];
  }
  return newData;
}
function parseEmsg(data) {
  const version6 = data[0];
  let schemeIdUri = "";
  let value = "";
  let timeScale = 0;
  let presentationTimeDelta = 0;
  let presentationTime = 0;
  let eventDuration = 0;
  let id = 0;
  let offset = 0;
  if (version6 === 0) {
    while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
      schemeIdUri += bin2str(data.subarray(offset, offset + 1));
      offset += 1;
    }
    schemeIdUri += bin2str(data.subarray(offset, offset + 1));
    offset += 1;
    while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
      value += bin2str(data.subarray(offset, offset + 1));
      offset += 1;
    }
    value += bin2str(data.subarray(offset, offset + 1));
    offset += 1;
    timeScale = readUint32(data, 12);
    presentationTimeDelta = readUint32(data, 16);
    eventDuration = readUint32(data, 20);
    id = readUint32(data, 24);
    offset = 28;
  } else if (version6 === 1) {
    offset += 4;
    timeScale = readUint32(data, offset);
    offset += 4;
    const leftPresentationTime = readUint32(data, offset);
    offset += 4;
    const rightPresentationTime = readUint32(data, offset);
    offset += 4;
    presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;
    if (!isSafeInteger(presentationTime)) {
      presentationTime = Number.MAX_SAFE_INTEGER;
      logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box");
    }
    eventDuration = readUint32(data, offset);
    offset += 4;
    id = readUint32(data, offset);
    offset += 4;
    while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
      schemeIdUri += bin2str(data.subarray(offset, offset + 1));
      offset += 1;
    }
    schemeIdUri += bin2str(data.subarray(offset, offset + 1));
    offset += 1;
    while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
      value += bin2str(data.subarray(offset, offset + 1));
      offset += 1;
    }
    value += bin2str(data.subarray(offset, offset + 1));
    offset += 1;
  }
  const payload = data.subarray(offset, data.byteLength);
  return {
    schemeIdUri,
    value,
    timeScale,
    presentationTime,
    presentationTimeDelta,
    eventDuration,
    id,
    payload
  };
}
function mp4Box(type2, ...payload) {
  const len = payload.length;
  let size = 8;
  let i = len;
  while (i--) {
    size += payload[i].byteLength;
  }
  const result = new Uint8Array(size);
  result[0] = size >> 24 & 255;
  result[1] = size >> 16 & 255;
  result[2] = size >> 8 & 255;
  result[3] = size & 255;
  result.set(type2, 4);
  for (i = 0, size = 8; i < len; i++) {
    result.set(payload[i], size);
    size += payload[i].byteLength;
  }
  return result;
}
function mp4pssh(systemId, keyids, data) {
  if (systemId.byteLength !== 16) {
    throw new RangeError("Invalid system id");
  }
  let version6;
  let kids;
  {
    version6 = 0;
    kids = new Uint8Array();
  }
  let kidCount;
  if (version6 > 0) {
    kidCount = new Uint8Array(4);
    if (keyids.length > 0) {
      new DataView(kidCount.buffer).setUint32(0, keyids.length, false);
    }
  } else {
    kidCount = new Uint8Array();
  }
  const dataSize = new Uint8Array(4);
  if (data && data.byteLength > 0) {
    new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);
  }
  return mp4Box(
    [112, 115, 115, 104],
    new Uint8Array([
      version6,
      0,
      0,
      0
      // Flags
    ]),
    systemId,
    // 16 bytes
    kidCount,
    kids,
    dataSize,
    data || new Uint8Array()
  );
}
function parseMultiPssh(initData) {
  const results = [];
  if (initData instanceof ArrayBuffer) {
    const length = initData.byteLength;
    let offset = 0;
    while (offset + 32 < length) {
      const view2 = new DataView(initData, offset);
      const pssh = parsePssh(view2);
      results.push(pssh);
      offset += pssh.size;
    }
  }
  return results;
}
function parsePssh(view2) {
  const size = view2.getUint32(0);
  const offset = view2.byteOffset;
  const length = view2.byteLength;
  if (length < size) {
    return {
      offset,
      size: length
    };
  }
  const type2 = view2.getUint32(4);
  if (type2 !== 1886614376) {
    return {
      offset,
      size
    };
  }
  const version6 = view2.getUint32(8) >>> 24;
  if (version6 !== 0 && version6 !== 1) {
    return {
      offset,
      size
    };
  }
  const buffer = view2.buffer;
  const systemId = Hex.hexDump(new Uint8Array(buffer, offset + 12, 16));
  const dataSizeOrKidCount = view2.getUint32(28);
  let kids = null;
  let data = null;
  if (version6 === 0) {
    if (size - 32 < dataSizeOrKidCount || dataSizeOrKidCount < 22) {
      return {
        offset,
        size
      };
    }
    data = new Uint8Array(buffer, offset + 32, dataSizeOrKidCount);
  } else if (version6 === 1) {
    if (!dataSizeOrKidCount || length < offset + 32 + dataSizeOrKidCount * 16 + 16) {
      return {
        offset,
        size
      };
    }
    kids = [];
    for (let i = 0; i < dataSizeOrKidCount; i++) {
      kids.push(new Uint8Array(buffer, offset + 32 + i * 16, 16));
    }
  }
  return {
    version: version6,
    systemId,
    kids,
    data,
    offset,
    size
  };
}
var userAgentHevcSupportIsInaccurate = () => {
  return /\(Windows.+Firefox\//i.test(navigator.userAgent);
};
var sampleEntryCodesISO = {
  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 isCodecType(codec, type2) {
  const typeCodes = sampleEntryCodesISO[type2];
  return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
}
function areCodecsMediaSourceSupported(codecs, type2, preferManagedMediaSource = true) {
  return !codecs.split(",").some((codec) => !isCodecMediaSourceSupported(codec, type2, preferManagedMediaSource));
}
function isCodecMediaSourceSupported(codec, type2, preferManagedMediaSource = true) {
  var _MediaSource$isTypeSu;
  const MediaSource2 = getMediaSource(preferManagedMediaSource);
  return (_MediaSource$isTypeSu = MediaSource2 == null ? void 0 : MediaSource2.isTypeSupported(mimeTypeForCodec(codec, type2))) != null ? _MediaSource$isTypeSu : false;
}
function mimeTypeForCodec(codec, type2) {
  return `${type2}/mp4;codecs=${codec}`;
}
function videoCodecPreferenceValue(videoCodec) {
  if (videoCodec) {
    const fourCC = videoCodec.substring(0, 4);
    return sampleEntryCodesISO.video[fourCC];
  }
  return 2;
}
function codecsSetSelectionPreferenceValue(codecSet) {
  const limitedHevcSupport = userAgentHevcSupportIsInaccurate();
  return codecSet.split(",").reduce((num, fourCC) => {
    const lowerPriority = limitedHevcSupport && isHEVC(fourCC);
    const preferenceValue = lowerPriority ? 9 : sampleEntryCodesISO.video[fourCC];
    if (preferenceValue) {
      return (preferenceValue * 2 + num) / (num ? 3 : 2);
    }
    return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  }, 0);
}
var CODEC_COMPATIBLE_NAMES = {};
function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {
  if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
    return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  }
  const codecsToCheck = {
    // 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"]
  }[lowerCaseCodec];
  for (let i = 0; i < codecsToCheck.length; i++) {
    var _getMediaSource;
    if (isCodecMediaSourceSupported(codecsToCheck[i], "audio", preferManagedMediaSource)) {
      CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
      return codecsToCheck[i];
    } else if (codecsToCheck[i] === "mp3" && (_getMediaSource = getMediaSource(preferManagedMediaSource)) != null && _getMediaSource.isTypeSupported("audio/mpeg")) {
      return "";
    }
  }
  return lowerCaseCodec;
}
var AUDIO_CODEC_REGEXP = /flac|opus|mp4a\.40\.34/i;
function getCodecCompatibleName(codec, preferManagedMediaSource = true) {
  return codec.replace(AUDIO_CODEC_REGEXP, (m) => getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource));
}
function replaceVideoCodec(originalCodecs, newVideoCodec) {
  const codecs = [];
  if (originalCodecs) {
    const allCodecs = originalCodecs.split(",");
    for (let i = 0; i < allCodecs.length; i++) {
      if (!isCodecType(allCodecs[i], "video")) {
        codecs.push(allCodecs[i]);
      }
    }
  }
  if (newVideoCodec) {
    codecs.push(newVideoCodec);
  }
  return codecs.join(",");
}
function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  if (parsedCodec && (parsedCodec.length > 4 || ["ac-3", "ec-3", "alac", "fLaC", "Opus"].indexOf(parsedCodec) !== -1)) {
    return parsedCodec;
  }
  if (levelCodec) {
    const levelCodecs = levelCodec.split(",");
    if (levelCodecs.length > 1) {
      if (parsedCodec) {
        for (let i = levelCodecs.length; i--; ) {
          if (levelCodecs[i].substring(0, 4) === parsedCodec.substring(0, 4)) {
            return levelCodecs[i];
          }
        }
      }
      return levelCodecs[0];
    }
  }
  return levelCodec || parsedCodec;
}
function convertAVC1ToAVCOTI(videoCodecs) {
  const codecs = videoCodecs.split(",");
  for (let i = 0; i < codecs.length; i++) {
    const avcdata = codecs[i].split(".");
    if (avcdata.length > 2) {
      let result = avcdata.shift() + ".";
      result += parseInt(avcdata.shift()).toString(16);
      result += ("000" + parseInt(avcdata.shift()).toString(16)).slice(-4);
      codecs[i] = result;
    }
  }
  return codecs.join(",");
}
function fillInMissingAV01Params(videoCodec) {
  if (videoCodec.startsWith("av01.")) {
    const av1params = videoCodec.split(".");
    const placeholders = ["0", "111", "01", "01", "01", "0"];
    for (let i = av1params.length; i > 4 && i < 10; i++) {
      av1params[i] = placeholders[i - 4];
    }
    return av1params.join(".");
  }
  return videoCodec;
}
function getM2TSSupportedAudioTypes(preferManagedMediaSource) {
  const MediaSource2 = getMediaSource(preferManagedMediaSource) || {
    isTypeSupported: () => false
  };
  return {
    mpeg: MediaSource2.isTypeSupported("audio/mpeg"),
    mp3: MediaSource2.isTypeSupported('audio/mp4; codecs="mp3"'),
    ac3: MediaSource2.isTypeSupported('audio/mp4; codecs="ac-3"')
  };
}
function getCodecsForMimeType(mimeType) {
  return mimeType.replace(/^.+codecs=["']?([^"']+).*$/, "$1");
}
var SUPPORTED_INFO_DEFAULT = {
  supported: true,
  configurations: [],
  decodingInfoResults: [{
    supported: true,
    powerEfficient: true,
    smooth: true
  }]
};
function getUnsupportedResult(error, configurations) {
  return {
    supported: false,
    configurations,
    decodingInfoResults: [{
      supported: false,
      smooth: false,
      powerEfficient: false
    }],
    error
  };
}
var SUPPORTED_INFO_CACHE = {};
function requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) {
  const audioGroups = level.audioCodec ? level.audioGroups : null;
  const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  const maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2;
  let audioChannels = null;
  if (audioGroups != null && audioGroups.length) {
    try {
      if (audioGroups.length === 1 && audioGroups[0]) {
        audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;
      } else {
        audioChannels = audioGroups.reduce((acc, groupId) => {
          if (groupId) {
            const audioTrackGroup = audioTracksByGroup.groups[groupId];
            if (!audioTrackGroup) {
              throw new Error(`Audio track group ${groupId} not found`);
            }
            Object.keys(audioTrackGroup.channels).forEach((key) => {
              acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];
            });
          }
          return acc;
        }, {
          2: 0
        });
      }
    } catch (error) {
      return true;
    }
  }
  return level.videoCodec !== void 0 && (level.width > 1920 && level.height > 1088 || level.height > 1920 && level.width > 1088 || level.frameRate > Math.max(currentFrameRate, 30) || level.videoRange !== "SDR" && level.videoRange !== currentVideoRange || level.bitrate > Math.max(currentBw, 8e6)) || !!audioChannels && isFiniteNumber(maxChannels) && Object.keys(audioChannels).some((channels) => parseInt(channels) > maxChannels);
}
function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities) {
  const videoCodecs = level.videoCodec;
  const audioCodecs = level.audioCodec;
  if (!videoCodecs && !audioCodecs || !mediaCapabilities) {
    return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  }
  const configurations = [];
  if (videoCodecs) {
    const baseVideoConfiguration = {
      width: level.width,
      height: level.height,
      bitrate: Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate)),
      // Assume a framerate of 30fps since MediaCapabilities will not accept Level default of 0.
      framerate: level.frameRate || 30
    };
    const videoRange = level.videoRange;
    if (videoRange !== "SDR") {
      baseVideoConfiguration.transferFunction = videoRange.toLowerCase();
    }
    const videoCodecsArray = videoCodecs.split(",");
    const ua = navigator.userAgent;
    if (videoCodecsArray.some((videoCodec) => isHEVC(videoCodec)) && userAgentHevcSupportIsInaccurate()) {
      return Promise.resolve(getUnsupportedResult(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${ua})`), configurations));
    }
    configurations.push.apply(configurations, videoCodecsArray.map((videoCodec) => ({
      type: "media-source",
      video: _objectSpread2(_objectSpread2({}, baseVideoConfiguration), {}, {
        contentType: mimeTypeForCodec(fillInMissingAV01Params(videoCodec), "video")
      })
    })));
  }
  if (audioCodecs && level.audioGroups) {
    level.audioGroups.forEach((audioGroupId) => {
      var _audioTracksByGroup$g;
      if (!audioGroupId) {
        return;
      }
      (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks.forEach((audioTrack) => {
        if (audioTrack.groupId === audioGroupId) {
          const channels = audioTrack.channels || "";
          const channelsNumber = parseFloat(channels);
          if (isFiniteNumber(channelsNumber) && channelsNumber > 2) {
            configurations.push.apply(configurations, audioCodecs.split(",").map((audioCodec) => ({
              type: "media-source",
              audio: {
                contentType: mimeTypeForCodec(audioCodec, "audio"),
                channels: "" + channelsNumber
                // spatialRendering:
                //   audioCodec === 'ec-3' && channels.indexOf('JOC'),
              }
            })));
          }
        }
      });
    });
  }
  return Promise.all(configurations.map((configuration) => {
    const decodingInfoKey = getMediaDecodingInfoKey(configuration);
    return SUPPORTED_INFO_CACHE[decodingInfoKey] || (SUPPORTED_INFO_CACHE[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  })).then((decodingInfoResults) => ({
    supported: !decodingInfoResults.some((info) => !info.supported),
    configurations,
    decodingInfoResults
  })).catch((error) => ({
    supported: false,
    configurations,
    decodingInfoResults: [],
    error
  }));
}
function getMediaDecodingInfoKey(config) {
  const {
    audio,
    video
  } = config;
  const mediaConfig = video || audio;
  if (mediaConfig) {
    const codec = getCodecsForMimeType(mediaConfig.contentType);
    if (video) {
      return `r${video.height}x${video.width}f${Math.ceil(video.framerate)}${video.transferFunction || "sd"}_${codec}_${Math.ceil(video.bitrate / 1e5)}`;
    }
    if (audio) {
      return `c${audio.channels}${audio.spatialRendering ? "s" : "n"}_${codec}`;
    }
  }
  return "";
}
var HdcpLevels = ["NONE", "TYPE-0", "TYPE-1", null];
function isHdcpLevel(value) {
  return HdcpLevels.indexOf(value) > -1;
}
var VideoRangeValues = ["SDR", "PQ", "HLG"];
function isVideoRange(value) {
  return !!value && VideoRangeValues.indexOf(value) > -1;
}
var HlsSkip = {
  No: "",
  Yes: "YES",
  v2: "v2"
};
function getSkipValue(details) {
  const {
    canSkipUntil,
    canSkipDateRanges,
    age
  } = details;
  const playlistRecentEnough = age < canSkipUntil / 2;
  if (canSkipUntil && playlistRecentEnough) {
    if (canSkipDateRanges) {
      return HlsSkip.v2;
    }
    return HlsSkip.Yes;
  }
  return HlsSkip.No;
}
var HlsUrlParameters = class {
  constructor(msn, part, skip) {
    this.msn = void 0;
    this.part = void 0;
    this.skip = void 0;
    this.msn = msn;
    this.part = part;
    this.skip = skip;
  }
  addDirectives(uri) {
    const url = new self.URL(uri);
    if (this.msn !== void 0) {
      url.searchParams.set("_HLS_msn", this.msn.toString());
    }
    if (this.part !== void 0) {
      url.searchParams.set("_HLS_part", this.part.toString());
    }
    if (this.skip) {
      url.searchParams.set("_HLS_skip", this.skip);
    }
    return url.href;
  }
};
var Level = class {
  constructor(data) {
    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 = [data.url];
    this._attrs = [data.attrs];
    this.bitrate = data.bitrate;
    if (data.details) {
      this.details = data.details;
    }
    this.id = data.id || 0;
    this.name = data.name;
    this.width = data.width || 0;
    this.height = data.height || 0;
    this.frameRate = data.attrs.optionalFloat("FRAME-RATE", 0);
    this._avgBitrate = data.attrs.decimalInteger("AVERAGE-BANDWIDTH");
    this.audioCodec = data.audioCodec;
    this.videoCodec = data.videoCodec;
    this.codecSet = [data.videoCodec, data.audioCodec].filter((c) => !!c).map((s) => s.substring(0, 4)).join(",");
    if ("supplemental" in data) {
      var _data$supplemental;
      this.supplemental = data.supplemental;
      const supplementalVideo = (_data$supplemental = data.supplemental) == null ? void 0 : _data$supplemental.videoCodec;
      if (supplementalVideo && supplementalVideo !== data.videoCodec) {
        this.codecSet += `,${supplementalVideo.substring(0, 4)}`;
      }
    }
    this.addGroupId("audio", data.attrs.AUDIO);
    this.addGroupId("text", data.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(groupId) {
    return hasGroup(this._audioGroups, groupId);
  }
  hasSubtitleGroup(groupId) {
    return hasGroup(this._subtitleGroups, groupId);
  }
  get audioGroups() {
    return this._audioGroups;
  }
  get subtitleGroups() {
    return this._subtitleGroups;
  }
  addGroupId(type2, groupId) {
    if (!groupId) {
      return;
    }
    if (type2 === "audio") {
      let audioGroups = this._audioGroups;
      if (!audioGroups) {
        audioGroups = this._audioGroups = [];
      }
      if (audioGroups.indexOf(groupId) === -1) {
        audioGroups.push(groupId);
      }
    } else if (type2 === "text") {
      let subtitleGroups = this._subtitleGroups;
      if (!subtitleGroups) {
        subtitleGroups = this._subtitleGroups = [];
      }
      if (subtitleGroups.indexOf(groupId) === -1) {
        subtitleGroups.push(groupId);
      }
    }
  }
  // Deprecated methods (retained for backwards compatibility)
  get urlId() {
    return 0;
  }
  set urlId(value) {
  }
  get audioGroupIds() {
    return this.audioGroups ? [this.audioGroupId] : void 0;
  }
  get textGroupIds() {
    return this.subtitleGroups ? [this.textGroupId] : void 0;
  }
  get audioGroupId() {
    var _this$audioGroups;
    return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  }
  get textGroupId() {
    var _this$subtitleGroups;
    return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  }
  addFallback() {
  }
};
function hasGroup(groups, groupId) {
  if (!groupId || !groups) {
    return false;
  }
  return groups.indexOf(groupId) !== -1;
}
function isHdrSupported() {
  if (typeof matchMedia === "function") {
    const mediaQueryList = matchMedia("(dynamic-range: high)");
    const badQuery = matchMedia("bad query");
    if (mediaQueryList.media !== badQuery.media) {
      return mediaQueryList.matches === true;
    }
  }
  return false;
}
function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  let preferHDR = false;
  let allowedVideoRanges = [];
  if (currentVideoRange) {
    preferHDR = currentVideoRange !== "SDR";
    allowedVideoRanges = [currentVideoRange];
  }
  if (videoPreference) {
    allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
    const allowAutoPreferHDR = allowedVideoRanges.join("") !== "SDR" && !videoPreference.videoCodec;
    preferHDR = videoPreference.preferHDR !== void 0 ? videoPreference.preferHDR : allowAutoPreferHDR && isHdrSupported();
    if (!preferHDR) {
      allowedVideoRanges = ["SDR"];
    }
  }
  return {
    preferHDR,
    allowedVideoRanges
  };
}
var omitCircularRefsReplacer = (replacer) => {
  const known = /* @__PURE__ */ new WeakSet();
  return (_, value) => {
    if (replacer) {
      value = replacer(_, value);
    }
    if (typeof value === "object" && value !== null) {
      if (known.has(value)) {
        return;
      }
      known.add(value);
    }
    return value;
  };
};
var stringify = (object, replacer) => JSON.stringify(object, omitCircularRefsReplacer(replacer));
function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  const codecSets = Object.keys(codecTiers);
  const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  const videoCodecPreference = videoPreference == null ? void 0 : videoPreference.videoCodec;
  const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  let hasStereo = false;
  let hasCurrentVideoRange = false;
  let minHeight = Infinity;
  let minFramerate = Infinity;
  let minBitrate = Infinity;
  let minIndex = Infinity;
  let selectedScore = 0;
  let videoRanges = [];
  const {
    preferHDR,
    allowedVideoRanges
  } = getVideoSelectionOptions(currentVideoRange, videoPreference);
  for (let i = codecSets.length; i--; ) {
    const tier = codecTiers[codecSets[i]];
    hasStereo || (hasStereo = tier.channels[2] > 0);
    minHeight = Math.min(minHeight, tier.minHeight);
    minFramerate = Math.min(minFramerate, tier.minFramerate);
    minBitrate = Math.min(minBitrate, tier.minBitrate);
    const matchingVideoRanges = allowedVideoRanges.filter((range3) => tier.videoRanges[range3] > 0);
    if (matchingVideoRanges.length > 0) {
      hasCurrentVideoRange = true;
    }
  }
  minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  const maxHeight = Math.max(1080, minHeight);
  const maxFramerate = Math.max(30, minFramerate);
  minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  currentBw = Math.max(minBitrate, currentBw);
  if (!hasCurrentVideoRange) {
    currentVideoRange = void 0;
  }
  const hasMultipleSets = codecSets.length > 1;
  const codecSet = codecSets.reduce((selected, candidate) => {
    const candidateTier = codecTiers[candidate];
    if (candidate === selected) {
      return selected;
    }
    videoRanges = hasCurrentVideoRange ? allowedVideoRanges.filter((range3) => candidateTier.videoRanges[range3] > 0) : [];
    if (hasMultipleSets) {
      if (candidateTier.minBitrate > currentBw) {
        logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);
        return selected;
      }
      if (!candidateTier.hasDefaultAudio) {
        logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);
        return selected;
      }
      if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
        logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`);
        return selected;
      }
      if (channelsPreference && !preferStereo) {
        if (!candidateTier.channels[channelsPreference]) {
          logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);
          return selected;
        }
      } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels["2"] === 0) {
        logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);
        return selected;
      }
      if (candidateTier.minHeight > maxHeight) {
        logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);
        return selected;
      }
      if (candidateTier.minFramerate > maxFramerate) {
        logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);
        return selected;
      }
      if (!videoRanges.some((range3) => candidateTier.videoRanges[range3] > 0)) {
        logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${stringify(videoRanges)} found`);
        return selected;
      }
      if (videoCodecPreference && candidate.indexOf(videoCodecPreference.substring(0, 4)) % 5 !== 0) {
        logStartCodecCandidateIgnored(candidate, `video codec preference "${videoCodecPreference}" not found`);
        return selected;
      }
      if (candidateTier.maxScore < selectedScore) {
        logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);
        return selected;
      }
    }
    if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
      return selected;
    }
    minIndex = candidateTier.minIndex;
    selectedScore = candidateTier.maxScore;
    return candidate;
  }, void 0);
  return {
    codecSet,
    videoRanges,
    preferHDR,
    minFramerate,
    minBitrate,
    minIndex
  };
}
function logStartCodecCandidateIgnored(codeSet, reason) {
  logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`);
}
function getAudioTracksByGroup(allAudioTracks) {
  return allAudioTracks.reduce((audioTracksByGroup, track) => {
    let trackGroup = audioTracksByGroup.groups[track.groupId];
    if (!trackGroup) {
      trackGroup = audioTracksByGroup.groups[track.groupId] = {
        tracks: [],
        channels: {
          2: 0
        },
        hasDefault: false,
        hasAutoSelect: false
      };
    }
    trackGroup.tracks.push(track);
    const channelsKey = track.channels || "2";
    trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
    trackGroup.hasDefault = trackGroup.hasDefault || track.default;
    trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
    if (trackGroup.hasDefault) {
      audioTracksByGroup.hasDefaultAudio = true;
    }
    if (trackGroup.hasAutoSelect) {
      audioTracksByGroup.hasAutoSelectAudio = true;
    }
    return audioTracksByGroup;
  }, {
    hasDefaultAudio: false,
    hasAutoSelectAudio: false,
    groups: {}
  });
}
function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level, index) => {
    if (!level.codecSet) {
      return tiers;
    }
    const audioGroups = level.audioGroups;
    let tier = tiers[level.codecSet];
    if (!tier) {
      tiers[level.codecSet] = tier = {
        minBitrate: Infinity,
        minHeight: Infinity,
        minFramerate: Infinity,
        minIndex: index,
        maxScore: 0,
        videoRanges: {
          SDR: 0
        },
        channels: {
          "2": 0
        },
        hasDefaultAudio: !audioGroups,
        fragmentError: 0
      };
    }
    tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
    const lesserWidthOrHeight = Math.min(level.height, level.width);
    tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
    tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
    tier.minIndex = Math.min(tier.minIndex, index);
    tier.maxScore = Math.max(tier.maxScore, level.score);
    tier.fragmentError += level.fragmentError;
    tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
    if (audioGroups) {
      audioGroups.forEach((audioGroupId) => {
        if (!audioGroupId) {
          return;
        }
        const audioGroup = audioTracksByGroup.groups[audioGroupId];
        if (!audioGroup) {
          return;
        }
        tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio;
        Object.keys(audioGroup.channels).forEach((channels) => {
          tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels];
        });
      });
    }
    return tiers;
  }, {});
}
function getBasicSelectionOption(option) {
  if (!option) {
    return option;
  }
  const {
    lang,
    assocLang,
    characteristics,
    channels,
    audioCodec
  } = option;
  return {
    lang,
    assocLang,
    characteristics,
    channels,
    audioCodec
  };
}
function findMatchingOption(option, tracks, matchPredicate) {
  if ("attrs" in option) {
    const index = tracks.indexOf(option);
    if (index !== -1) {
      return index;
    }
  }
  for (let i = 0; i < tracks.length; i++) {
    const track = tracks[i];
    if (matchesOption(option, track, matchPredicate)) {
      return i;
    }
  }
  return -1;
}
function matchesOption(option, track, matchPredicate) {
  const {
    groupId,
    name,
    lang,
    assocLang,
    default: isDefault
  } = option;
  const forced = option.forced;
  return (groupId === void 0 || track.groupId === groupId) && (name === void 0 || track.name === name) && (lang === void 0 || languagesMatch(lang, track.lang)) && (lang === void 0 || track.assocLang === assocLang) && (isDefault === void 0 || track.default === isDefault) && (forced === void 0 || track.forced === forced) && (!("characteristics" in option) || characteristicsMatch(option.characteristics || "", track.characteristics)) && (matchPredicate === void 0 || matchPredicate(option, track));
}
function languagesMatch(languageA, languageB = "--") {
  if (languageA.length === languageB.length) {
    return languageA === languageB;
  }
  return languageA.startsWith(languageB) || languageB.startsWith(languageA);
}
function characteristicsMatch(characteristicsA, characteristicsB = "") {
  const arrA = characteristicsA.split(",");
  const arrB = characteristicsB.split(",");
  return arrA.length === arrB.length && !arrA.some((el) => arrB.indexOf(el) === -1);
}
function audioMatchPredicate(option, track) {
  const {
    audioCodec,
    channels
  } = option;
  return (audioCodec === void 0 || (track.audioCodec || "").substring(0, 4) === audioCodec.substring(0, 4)) && (channels === void 0 || channels === (track.channels || "2"));
}
function findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) {
  const currentLevel = levels[searchIndex];
  const variants = levels.reduce((variantMap, level, index) => {
    const uri = level.uri;
    const renditions2 = variantMap[uri] || (variantMap[uri] = []);
    renditions2.push(index);
    return variantMap;
  }, {});
  const renditions = variants[currentLevel.uri];
  if (renditions.length > 1) {
    searchIndex = Math.max.apply(Math, renditions);
  }
  const currentVideoRange = currentLevel.videoRange;
  const currentFrameRate = currentLevel.frameRate;
  const currentVideoCodec = currentLevel.codecSet.substring(0, 4);
  const matchingVideo = searchDownAndUpList(levels, searchIndex, (level) => {
    if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) {
      return false;
    }
    const audioGroups = level.audioGroups;
    const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
    return findMatchingOption(option, tracks, matchPredicate) > -1;
  });
  if (matchingVideo > -1) {
    return matchingVideo;
  }
  return searchDownAndUpList(levels, searchIndex, (level) => {
    const audioGroups = level.audioGroups;
    const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
    return findMatchingOption(option, tracks, matchPredicate) > -1;
  });
}
function searchDownAndUpList(arr, searchIndex, predicate) {
  for (let i = searchIndex; i > -1; i--) {
    if (predicate(arr[i])) {
      return i;
    }
  }
  for (let i = searchIndex + 1; i < arr.length; i++) {
    if (predicate(arr[i])) {
      return i;
    }
  }
  return -1;
}
function useAlternateAudio(audioTrackUrl, hls) {
  var _hls$loadLevelObj;
  return !!audioTrackUrl && audioTrackUrl !== ((_hls$loadLevelObj = hls.loadLevelObj) == null ? void 0 : _hls$loadLevelObj.uri);
}
var AbrController = class extends Logger {
  constructor(_hls) {
    super("abr", _hls.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.bwEstimator = void 0;
    this._abandonRulesCheck = (levelLoaded) => {
      var _ref;
      const {
        fragCurrent: frag,
        partCurrent: part,
        hls
      } = this;
      const {
        autoLevelEnabled,
        media
      } = hls;
      if (!frag || !media) {
        return;
      }
      const now2 = performance.now();
      const stats = part ? part.stats : frag.stats;
      const duration5 = part ? part.duration : frag.duration;
      const timeLoading = now2 - stats.loading.start;
      const minAutoLevel = hls.minAutoLevel;
      const loadingFragForLevel = frag.level;
      const currentAutoLevel = this._nextAutoLevel;
      if (stats.aborted || stats.loaded && stats.loaded === stats.total || loadingFragForLevel <= minAutoLevel) {
        this.clearTimer();
        this._nextAutoLevel = -1;
        return;
      }
      if (!autoLevelEnabled) {
        return;
      }
      const fragBlockingSwitch = currentAutoLevel > -1 && currentAutoLevel !== loadingFragForLevel;
      const levelChange = !!levelLoaded || fragBlockingSwitch;
      if (!levelChange && (media.paused || !media.playbackRate || !media.readyState)) {
        return;
      }
      const bufferInfo = hls.mainForwardBufferInfo;
      if (!levelChange && bufferInfo === null) {
        return;
      }
      const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
      const playbackRate = Math.abs(media.playbackRate);
      if (timeLoading <= Math.max(ttfbEstimate, 1e3 * (duration5 / (playbackRate * 2)))) {
        return;
      }
      const bufferStarvationDelay = bufferInfo ? bufferInfo.len / playbackRate : 0;
      const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
      const loadedFirstByte = stats.loaded && ttfb > -1;
      const bwEstimate = this.getBwEstimate();
      const levels = hls.levels;
      const level = levels[loadingFragForLevel];
      const expectedLen = Math.max(stats.loaded, Math.round(duration5 * (frag.bitrate || level.averageBitrate) / 8));
      let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
      if (timeStreaming < 1 && loadedFirstByte) {
        timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
      }
      const loadRate = loadedFirstByte ? stats.loaded * 1e3 / timeStreaming : 0;
      const ttfbSeconds = ttfbEstimate / 1e3;
      const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbSeconds;
      if (fragLoadedDelay <= bufferStarvationDelay) {
        return;
      }
      const bwe = loadRate ? loadRate * 8 : bwEstimate;
      const live = ((_ref = (levelLoaded == null ? void 0 : levelLoaded.details) || this.hls.latestLevelDetails) == null ? void 0 : _ref.live) === true;
      const abrBandWidthUpFactor = this.hls.config.abrBandWidthUpFactor;
      let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
      let nextLoadLevel;
      for (nextLoadLevel = loadingFragForLevel - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
        const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
        const requiresLevelLoad = !levels[nextLoadLevel].details || live;
        fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbSeconds, bwe, duration5 * levelNextBitrate, requiresLevelLoad);
        if (fragLevelNextLoadedDelay < Math.min(bufferStarvationDelay, duration5 + ttfbSeconds)) {
          break;
        }
      }
      if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
        return;
      }
      if (fragLevelNextLoadedDelay > duration5 * 10) {
        return;
      }
      if (loadedFirstByte) {
        this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
      } else {
        this.bwEstimator.sampleTTFB(timeLoading);
      }
      const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
      if (this.getBwEstimate() * abrBandWidthUpFactor > nextLoadLevelBitrate) {
        this.resetEstimator(nextLoadLevelBitrate);
      }
      const bestSwitchLevel = this.findBestLevel(nextLoadLevelBitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
      if (bestSwitchLevel > -1) {
        nextLoadLevel = bestSwitchLevel;
      }
      this.warn(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of level ${loadingFragForLevel} is loading too slowly;
      Fragment duration: ${frag.duration.toFixed(3)}
      Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
      Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
      Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s
      TTFB estimate: ${ttfb | 0} ms
      Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : "Unknown"} bps
      New BW estimate: ${this.getBwEstimate() | 0} bps
      Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
      hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
      this.clearTimer();
      const abortAndSwitch = () => {
        this.clearTimer();
        if (this.fragCurrent === frag && this.hls.loadLevel === nextLoadLevel && nextLoadLevel > 0) {
          const bufferStarvationDelay2 = this.getStarvationDelay();
          this.warn(`Aborting inflight request ${nextLoadLevel > 0 ? "and switching down" : ""}
      Fragment duration: ${frag.duration.toFixed(3)} s
      Time to underbuffer: ${bufferStarvationDelay2.toFixed(3)} s`);
          frag.abortRequests();
          this.fragCurrent = this.partCurrent = null;
          if (nextLoadLevel > minAutoLevel) {
            let lowestSwitchLevel = this.findBestLevel(this.hls.levels[minAutoLevel].bitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay2, 1, 1);
            if (lowestSwitchLevel === -1) {
              lowestSwitchLevel = minAutoLevel;
            }
            this.hls.nextLoadLevel = this.hls.nextAutoLevel = lowestSwitchLevel;
            this.resetEstimator(this.hls.levels[lowestSwitchLevel].bitrate);
          }
        }
      };
      if (fragBlockingSwitch || fragLoadedDelay > fragLevelNextLoadedDelay * 2) {
        abortAndSwitch();
      } else {
        this.timer = self.setInterval(abortAndSwitch, fragLevelNextLoadedDelay * 1e3);
      }
      hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
        frag,
        part,
        stats
      });
    };
    this.hls = _hls;
    this.bwEstimator = this.initEstimator();
    this.registerListeners();
  }
  resetEstimator(abrEwmaDefaultEstimate) {
    if (abrEwmaDefaultEstimate) {
      this.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
      this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
    }
    this.firstSelection = -1;
    this.bwEstimator = this.initEstimator();
  }
  initEstimator() {
    const config = this.hls.config;
    return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  }
  registerListeners() {
    const {
      hls
    } = this;
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
    hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
    hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
    hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
    hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
    hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
    hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
    hls.on(Events.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls
    } = this;
    if (!hls) {
      return;
    }
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
    hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
    hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
    hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
    hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
    hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
    hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
    hls.off(Events.ERROR, this.onError, this);
  }
  destroy() {
    this.unregisterListeners();
    this.clearTimer();
    this.hls = this._abandonRulesCheck = null;
    this.fragCurrent = this.partCurrent = null;
  }
  onManifestLoading(event, data) {
    this.lastLoadedFragLevel = -1;
    this.firstSelection = -1;
    this.lastLevelLoadSec = 0;
    this.fragCurrent = this.partCurrent = null;
    this.onLevelsUpdated();
    this.clearTimer();
  }
  onLevelsUpdated() {
    if (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(event, data) {
    const frag = data.frag;
    if (this.ignoreFragment(frag)) {
      return;
    }
    if (!frag.bitrateTest) {
      var _data$part;
      this.fragCurrent = frag;
      this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
    }
    this.clearTimer();
    this.timer = self.setInterval(this._abandonRulesCheck, 100);
  }
  onLevelSwitching(event, data) {
    this.clearTimer();
  }
  onError(event, data) {
    if (data.fatal) {
      return;
    }
    switch (data.details) {
      case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
      case ErrorDetails.BUFFER_APPEND_ERROR:
        this.lastLoadedFragLevel = -1;
        this.firstSelection = -1;
        break;
      case ErrorDetails.FRAG_LOAD_TIMEOUT: {
        const frag = data.frag;
        const {
          fragCurrent,
          partCurrent: part
        } = this;
        if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
          const now2 = performance.now();
          const stats = part ? part.stats : frag.stats;
          const timeLoading = now2 - stats.loading.start;
          const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
          const loadedFirstByte = stats.loaded && ttfb > -1;
          if (loadedFirstByte) {
            const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
            this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
          } else {
            this.bwEstimator.sampleTTFB(timeLoading);
          }
        }
        break;
      }
    }
  }
  getTimeToLoadFrag(timeToFirstByteSec, bandwidth2, fragSizeBits, isSwitch) {
    const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth2;
    const playlistLoadSec = isSwitch ? timeToFirstByteSec + this.lastLevelLoadSec : 0;
    return fragLoadSec + playlistLoadSec;
  }
  onLevelLoaded(event, data) {
    const config = this.hls.config;
    const {
      loading
    } = data.stats;
    const timeLoadingMs = loading.end - loading.first;
    if (isFiniteNumber(timeLoadingMs)) {
      this.lastLevelLoadSec = timeLoadingMs / 1e3;
    }
    if (data.details.live) {
      this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
    } else {
      this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
    }
    if (this.timer > -1) {
      this._abandonRulesCheck(data.levelInfo);
    }
  }
  onFragLoaded(event, {
    frag,
    part
  }) {
    const stats = part ? part.stats : frag.stats;
    if (frag.type === PlaylistLevelType.MAIN) {
      this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
    }
    if (this.ignoreFragment(frag)) {
      return;
    }
    this.clearTimer();
    if (frag.level === this._nextAutoLevel) {
      this._nextAutoLevel = -1;
    }
    this.firstSelection = -1;
    if (this.hls.config.abrMaxWithRealBitrate) {
      const duration5 = part ? part.duration : frag.duration;
      const level = this.hls.levels[frag.level];
      const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
      const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration5;
      level.loaded = {
        bytes: loadedBytes,
        duration: loadedDuration
      };
      level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
    }
    if (frag.bitrateTest) {
      const fragBufferedData = {
        stats,
        frag,
        part,
        id: frag.type
      };
      this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
      frag.bitrateTest = false;
    } else {
      this.lastLoadedFragLevel = frag.level;
    }
  }
  onFragBuffered(event, data) {
    const {
      frag,
      part
    } = data;
    const stats = part != null && part.stats.loaded ? part.stats : frag.stats;
    if (stats.aborted) {
      return;
    }
    if (this.ignoreFragment(frag)) {
      return;
    }
    const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
    this.bwEstimator.sample(processingMs, stats.loaded);
    stats.bwEstimate = this.getBwEstimate();
    if (frag.bitrateTest) {
      this.bitrateTestDelay = processingMs / 1e3;
    } else {
      this.bitrateTestDelay = 0;
    }
  }
  ignoreFragment(frag) {
    return frag.type !== PlaylistLevelType.MAIN || frag.sn === "initSegment";
  }
  clearTimer() {
    if (this.timer > -1) {
      self.clearInterval(this.timer);
      this.timer = -1;
    }
  }
  get firstAutoLevel() {
    const {
      maxAutoLevel,
      minAutoLevel
    } = this.hls;
    const bwEstimate = this.getBwEstimate();
    const maxStartDelay = this.hls.config.maxStarvationDelay;
    const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
    if (abrAutoLevel > -1) {
      return abrAutoLevel;
    }
    const firstLevel = this.hls.firstLevel;
    const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
    this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);
    return clamped;
  }
  get forcedAutoLevel() {
    if (this.nextAutoLevelKey) {
      return -1;
    }
    return this._nextAutoLevel;
  }
  // return next auto level
  get nextAutoLevel() {
    const forcedAutoLevel = this.forcedAutoLevel;
    const bwEstimator = this.bwEstimator;
    const useEstimate = bwEstimator.canEstimate();
    const loadedFirstFrag = this.lastLoadedFragLevel > -1;
    if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
      return forcedAutoLevel;
    }
    const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
    if (forcedAutoLevel !== -1) {
      const levels = this.hls.levels;
      if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
        return forcedAutoLevel;
      }
    }
    this._nextAutoLevel = nextABRAutoLevel;
    this.nextAutoLevelKey = this.getAutoLevelKey();
    return nextABRAutoLevel;
  }
  getAutoLevelKey() {
    return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  }
  getNextABRAutoLevel() {
    const {
      fragCurrent,
      partCurrent,
      hls
    } = this;
    if (hls.levels.length <= 1) {
      return hls.loadLevel;
    }
    const {
      maxAutoLevel,
      config,
      minAutoLevel
    } = hls;
    const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
    const avgbw = this.getBwEstimate();
    const bufferStarvationDelay = this.getStarvationDelay();
    let bwFactor = config.abrBandWidthFactor;
    let bwUpFactor = config.abrBandWidthUpFactor;
    if (bufferStarvationDelay) {
      const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
      if (_bestLevel >= 0) {
        this.rebufferNotice = -1;
        return _bestLevel;
      }
    }
    let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
    if (!bufferStarvationDelay) {
      const bitrateTestDelay = this.bitrateTestDelay;
      if (bitrateTestDelay) {
        const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
        maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
        this.info(`bitrate test took ${Math.round(1e3 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1e3 * maxStarvationDelay)} ms`);
        bwFactor = bwUpFactor = 1;
      }
    }
    const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
    if (this.rebufferNotice !== bestLevel) {
      this.rebufferNotice = bestLevel;
      this.info(`${bufferStarvationDelay ? "rebuffering expected" : "buffer is empty"}, optimal quality level ${bestLevel}`);
    }
    if (bestLevel > -1) {
      return bestLevel;
    }
    const minLevel = hls.levels[minAutoLevel];
    const autoLevel = hls.loadLevelObj;
    if (autoLevel && (minLevel == null ? void 0 : minLevel.bitrate) < autoLevel.bitrate) {
      return minAutoLevel;
    }
    return hls.loadLevel;
  }
  getStarvationDelay() {
    const hls = this.hls;
    const media = hls.media;
    if (!media) {
      return Infinity;
    }
    const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1;
    const bufferInfo = hls.mainForwardBufferInfo;
    return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  }
  getBwEstimate() {
    return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  }
  findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
    var _this$hls$latestLevel;
    const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
    const lastLoadedFragLevel = this.lastLoadedFragLevel;
    const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
    const {
      fragCurrent,
      partCurrent
    } = this;
    const {
      levels,
      allAudioTracks,
      loadLevel,
      config
    } = this.hls;
    if (levels.length === 1) {
      return 0;
    }
    const level = levels[selectionBaseLevel];
    const live = !!((_this$hls$latestLevel = this.hls.latestLevelDetails) != null && _this$hls$latestLevel.live);
    const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
    let currentCodecSet;
    let currentVideoRange = "SDR";
    let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
    const {
      audioPreference,
      videoPreference
    } = config;
    const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
    let minStartIndex = -1;
    if (firstSelection) {
      if (this.firstSelection !== -1) {
        return this.firstSelection;
      }
      const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
      const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
      const {
        codecSet,
        videoRanges,
        minFramerate,
        minBitrate,
        minIndex,
        preferHDR
      } = startTier;
      minStartIndex = minIndex;
      currentCodecSet = codecSet;
      currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
      currentFrameRate = minFramerate;
      currentBw = Math.max(currentBw, minBitrate);
      this.log(`picked start tier ${stringify(startTier)}`);
    } else {
      currentCodecSet = level == null ? void 0 : level.codecSet;
      currentVideoRange = level == null ? void 0 : level.videoRange;
    }
    const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
    const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1e3;
    const levelsSkipped = [];
    for (let i = maxAutoLevel; i >= minAutoLevel; i--) {
      var _levelInfo$supportedR;
      const levelInfo = levels[i];
      const upSwitch = i > selectionBaseLevel;
      if (!levelInfo) {
        continue;
      }
      if (config.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) {
        const mediaCapabilities = navigator.mediaCapabilities;
        if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === "function" && (requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) || isHEVC(levelInfo.videoCodec))) {
          levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities);
          levelInfo.supportedPromise.then((decodingInfo) => {
            if (!this.hls) {
              return;
            }
            levelInfo.supportedResult = decodingInfo;
            const levels2 = this.hls.levels;
            const index = levels2.indexOf(levelInfo);
            if (decodingInfo.error) {
              this.warn(`MediaCapabilities decodingInfo error: "${decodingInfo.error}" for level ${index} ${stringify(decodingInfo)}`);
            } else if (!decodingInfo.supported) {
              this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${index} ${stringify(decodingInfo)}`);
              if (index > -1 && levels2.length > 1) {
                this.log(`Removing unsupported level ${index}`);
                this.hls.removeLevel(index);
                if (this.hls.loadLevel === -1) {
                  this.hls.nextLoadLevel = 0;
                }
              }
            }
          });
        } else {
          levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;
        }
      }
      if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || levelInfo.supportedResult && !((_levelInfo$supportedR = levelInfo.supportedResult.decodingInfoResults) != null && _levelInfo$supportedR[0].smooth)) {
        if (!firstSelection || i !== minStartIndex) {
          levelsSkipped.push(i);
          continue;
        }
      }
      const levelDetails = levelInfo.details;
      const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
      let adjustedbw;
      if (!upSwitch) {
        adjustedbw = bwFactor * currentBw;
      } else {
        adjustedbw = bwUpFactor * currentBw;
      }
      const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levelInfo.averageBitrate : levelInfo.maxBitrate;
      const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === void 0);
      const canSwitchWithinTolerance = (
        // if adjusted bw is greater than level bitrate AND
        adjustedbw >= bitrate && // no level change, or new level has no error history
        (i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.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
        (fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)
      );
      if (canSwitchWithinTolerance) {
        const forcedAutoLevel = this.forcedAutoLevel;
        if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
          if (levelsSkipped.length) {
            this.trace(`Skipped level(s) ${levelsSkipped.join(",")} of ${maxAutoLevel} max with CODECS and VIDEO-RANGE:"${levels[levelsSkipped[0]].codecs}" ${levels[levelsSkipped[0]].videoRange}; not compatible with "${currentCodecSet}" ${currentVideoRange}`);
          }
          this.info(`switch candidate:${selectionBaseLevel}->${i} adjustedbw(${Math.round(adjustedbw)})-bitrate=${Math.round(adjustedbw - bitrate)} ttfb:${ttfbEstimateSec.toFixed(1)} avgDuration:${avgDuration.toFixed(1)} maxFetchDuration:${maxFetchDuration.toFixed(1)} fetchDuration:${fetchDuration.toFixed(1)} firstSelection:${firstSelection} codecSet:${levelInfo.codecSet} videoRange:${levelInfo.videoRange} hls.loadLevel:${loadLevel}`);
        }
        if (firstSelection) {
          this.firstSelection = i;
        }
        return i;
      }
    }
    return -1;
  }
  set nextAutoLevel(nextLevel) {
    const value = this.deriveNextAutoLevel(nextLevel);
    if (this._nextAutoLevel !== value) {
      this.nextAutoLevelKey = "";
      this._nextAutoLevel = value;
    }
  }
  deriveNextAutoLevel(nextLevel) {
    const {
      maxAutoLevel,
      minAutoLevel
    } = this.hls;
    return Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  }
};
var BinarySearch = {
  /**
   * 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(list, comparisonFn) {
    let minIndex = 0;
    let maxIndex = list.length - 1;
    let currentIndex = null;
    let currentElement = null;
    while (minIndex <= maxIndex) {
      currentIndex = (minIndex + maxIndex) / 2 | 0;
      currentElement = list[currentIndex];
      const comparisonResult = comparisonFn(currentElement);
      if (comparisonResult > 0) {
        minIndex = currentIndex + 1;
      } else if (comparisonResult < 0) {
        maxIndex = currentIndex - 1;
      } else {
        return currentElement;
      }
    }
    return null;
  }
};
function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
    return null;
  }
  const startPDT = fragments[0].programDateTime;
  if (PDTValue < (startPDT || 0)) {
    return null;
  }
  const endPDT = fragments[fragments.length - 1].endProgramDateTime;
  if (PDTValue >= (endPDT || 0)) {
    return null;
  }
  maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
  for (let seg = 0; seg < fragments.length; ++seg) {
    const frag = fragments[seg];
    if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
      return frag;
    }
  }
  return null;
}
function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 5e-3) {
  let fragNext = null;
  if (fragPrevious) {
    fragNext = fragments[1 + fragPrevious.sn - fragments[0].sn] || null;
    const bufferEdgeError = fragPrevious.endDTS - bufferEnd;
    if (bufferEdgeError > 0 && bufferEdgeError < 15e-7) {
      bufferEnd += 15e-7;
    }
    if (fragNext && fragPrevious.level !== fragNext.level && fragNext.end <= fragPrevious.end) {
      fragNext = fragments[2 + fragPrevious.sn - fragments[0].sn] || null;
    }
  } else if (bufferEnd === 0 && fragments[0].start === 0) {
    fragNext = fragments[0];
  }
  if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
    return fragNext;
  }
  const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
    return foundFragment;
  }
  return fragNext;
}
function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
    const firstDuration = fragPrevious.tagList.reduce((duration5, tag) => {
      if (tag[0] === "INF") {
        duration5 += parseFloat(tag[1]);
      }
      return duration5;
    }, nextFragLookupTolerance);
    return fragNext.start <= firstDuration;
  }
  return false;
}
function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {
  if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
    return 0;
  }
  const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
    return 1;
  } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
    return -1;
  }
  return 0;
}
function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1e3;
  const endProgramDateTime = candidate.endProgramDateTime || 0;
  return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
}
function findFragWithCC(fragments, cc) {
  return BinarySearch.search(fragments, (candidate) => {
    if (candidate.cc < cc) {
      return 1;
    } else if (candidate.cc > cc) {
      return -1;
    } else {
      return 0;
    }
  });
}
function findNearestWithCC(details, cc, fragment) {
  if (details) {
    if (details.startCC <= cc && details.endCC >= cc) {
      const start2 = fragment.start;
      const end = fragment.end;
      let fragments = details.fragments;
      if (!fragment.relurl) {
        const {
          fragmentHint
        } = details;
        if (fragmentHint) {
          fragments = fragments.concat(fragmentHint);
        }
      }
      return BinarySearch.search(fragments, (candidate) => {
        if (candidate.cc < cc || candidate.end <= start2) {
          return 1;
        } else if (candidate.cc > cc || candidate.start >= end) {
          return -1;
        } else {
          return 0;
        }
      });
    }
  }
  return null;
}
function isTimeoutError(error) {
  switch (error.details) {
    case ErrorDetails.FRAG_LOAD_TIMEOUT:
    case ErrorDetails.KEY_LOAD_TIMEOUT:
    case ErrorDetails.LEVEL_LOAD_TIMEOUT:
    case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
      return true;
  }
  return false;
}
function getRetryConfig(loadPolicy, error) {
  const isTimeout = isTimeoutError(error);
  return loadPolicy.default[`${isTimeout ? "timeout" : "error"}Retry`];
}
function getRetryDelay(retryConfig, retryCount) {
  const backoffFactor = retryConfig.backoff === "linear" ? 1 : Math.pow(2, retryCount);
  return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
}
function getLoaderConfigWithoutReties(loderConfig) {
  return _objectSpread2(_objectSpread2({}, loderConfig), {
    errorRetry: null,
    timeoutRetry: null
  });
}
function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  if (!retryConfig) {
    return false;
  }
  const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
}
function retryForHttpStatus(httpStatus) {
  return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
}
var NetworkErrorAction = {
  DoNothing: 0,
  SendEndCallback: 1,
  SendAlternateToPenaltyBox: 2,
  RemoveAlternatePermanently: 3,
  InsertDiscontinuity: 4,
  RetryRequest: 5
};
var ErrorActionFlags = {
  None: 0,
  MoveAllAlternatesMatchingHost: 1,
  MoveAllAlternatesMatchingHDCP: 2,
  SwitchToSDR: 4
};
var ErrorController = class extends Logger {
  constructor(hls) {
    super("error-controller", hls.logger);
    this.hls = void 0;
    this.playlistError = 0;
    this.penalizedRenditions = {};
    this.hls = hls;
    this.registerListeners();
  }
  registerListeners() {
    const hls = this.hls;
    hls.on(Events.ERROR, this.onError, this);
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  }
  unregisterListeners() {
    const hls = this.hls;
    if (!hls) {
      return;
    }
    hls.off(Events.ERROR, this.onError, this);
    hls.off(Events.ERROR, this.onErrorOut, this);
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  }
  destroy() {
    this.unregisterListeners();
    this.hls = null;
    this.penalizedRenditions = {};
  }
  startLoad(startPosition) {
  }
  stopLoad() {
    this.playlistError = 0;
  }
  getVariantLevelIndex(frag) {
    return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  }
  onManifestLoading() {
    this.playlistError = 0;
    this.penalizedRenditions = {};
  }
  onLevelUpdated() {
    this.playlistError = 0;
  }
  onError(event, data) {
    var _data$frag;
    if (data.fatal) {
      return;
    }
    const hls = this.hls;
    const context = data.context;
    switch (data.details) {
      case ErrorDetails.FRAG_LOAD_ERROR:
      case ErrorDetails.FRAG_LOAD_TIMEOUT:
      case ErrorDetails.KEY_LOAD_ERROR:
      case ErrorDetails.KEY_LOAD_TIMEOUT:
        data.errorAction = this.getFragRetryOrSwitchAction(data);
        return;
      case ErrorDetails.FRAG_PARSING_ERROR:
        if ((_data$frag = data.frag) != null && _data$frag.gap) {
          data.errorAction = createDoNothingErrorAction();
          return;
        }
      // falls through
      case ErrorDetails.FRAG_GAP:
      case ErrorDetails.FRAG_DECRYPT_ERROR: {
        data.errorAction = this.getFragRetryOrSwitchAction(data);
        data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
        return;
      }
      case ErrorDetails.LEVEL_EMPTY_ERROR:
      case ErrorDetails.LEVEL_PARSING_ERROR:
        {
          var _data$context, _data$context$levelDe;
          const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
          if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
            data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
          } else {
            data.levelRetry = false;
            data.errorAction = this.getLevelSwitchAction(data, levelIndex);
          }
        }
        return;
      case ErrorDetails.LEVEL_LOAD_ERROR:
      case ErrorDetails.LEVEL_LOAD_TIMEOUT:
        if (typeof (context == null ? void 0 : context.level) === "number") {
          data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
        }
        return;
      case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
      case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
      case ErrorDetails.SUBTITLE_LOAD_ERROR:
      case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
        if (context) {
          const level = hls.loadLevelObj;
          if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
            data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
            data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
            data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
            return;
          }
        }
        return;
      case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
        {
          const level = hls.loadLevelObj;
          const restrictedHdcpLevel = level == null ? void 0 : level.attrs["HDCP-LEVEL"];
          if (restrictedHdcpLevel) {
            data.errorAction = {
              action: NetworkErrorAction.SendAlternateToPenaltyBox,
              flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
              hdcpLevel: restrictedHdcpLevel
            };
          } else {
            this.keySystemError(data);
          }
        }
        return;
      case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
      case ErrorDetails.REMUX_ALLOC_ERROR:
      case ErrorDetails.BUFFER_APPEND_ERROR:
        if (!data.errorAction) {
          var _data$level;
          data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
        }
        return;
      case ErrorDetails.INTERNAL_EXCEPTION:
      case ErrorDetails.BUFFER_APPENDING_ERROR:
      case ErrorDetails.BUFFER_FULL_ERROR:
      case ErrorDetails.LEVEL_SWITCH_ERROR:
      case ErrorDetails.BUFFER_STALLED_ERROR:
      case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
      case ErrorDetails.BUFFER_NUDGE_ON_STALL:
        data.errorAction = createDoNothingErrorAction();
        return;
    }
    if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
      this.keySystemError(data);
    }
  }
  keySystemError(data) {
    const levelIndex = this.getVariantLevelIndex(data.frag);
    data.levelRetry = false;
    data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  }
  getPlaylistRetryOrSwitchAction(data, levelIndex) {
    const hls = this.hls;
    const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
    const retryCount = this.playlistError++;
    const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
    if (retry) {
      return {
        action: NetworkErrorAction.RetryRequest,
        flags: ErrorActionFlags.None,
        retryConfig,
        retryCount
      };
    }
    const errorAction = this.getLevelSwitchAction(data, levelIndex);
    if (retryConfig) {
      errorAction.retryConfig = retryConfig;
      errorAction.retryCount = retryCount;
    }
    return errorAction;
  }
  getFragRetryOrSwitchAction(data) {
    const hls = this.hls;
    const variantLevelIndex = this.getVariantLevelIndex(data.frag);
    const level = hls.levels[variantLevelIndex];
    const {
      fragLoadPolicy,
      keyLoadPolicy
    } = hls.config;
    const retryConfig = getRetryConfig(data.details.startsWith("key") ? keyLoadPolicy : fragLoadPolicy, data);
    const fragmentErrors = hls.levels.reduce((acc, level2) => acc + level2.fragmentError, 0);
    if (level) {
      if (data.details !== ErrorDetails.FRAG_GAP) {
        level.fragmentError++;
      }
      const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
      if (retry) {
        return {
          action: NetworkErrorAction.RetryRequest,
          flags: ErrorActionFlags.None,
          retryConfig,
          retryCount: fragmentErrors
        };
      }
    }
    const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
    if (retryConfig) {
      errorAction.retryConfig = retryConfig;
      errorAction.retryCount = fragmentErrors;
    }
    return errorAction;
  }
  getLevelSwitchAction(data, levelIndex) {
    const hls = this.hls;
    if (levelIndex === null || levelIndex === void 0) {
      levelIndex = hls.loadLevel;
    }
    const level = this.hls.levels[levelIndex];
    if (level) {
      var _data$frag2, _data$context2;
      const errorDetails = data.details;
      level.loadError++;
      if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
        level.fragmentError++;
      }
      let nextLevel = -1;
      const {
        levels,
        loadLevel,
        minAutoLevel,
        maxAutoLevel
      } = hls;
      if (!hls.autoLevelEnabled) {
        hls.loadLevel = -1;
      }
      const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
      const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === "audio" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
      const findAudioCodecAlternate = isAudioCodecError && levels.some(({
        audioCodec
      }) => level.audioCodec !== audioCodec);
      const isVideoCodecError = data.sourceBufferName === "video" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
      const findVideoCodecAlternate = isVideoCodecError && levels.some(({
        codecSet,
        audioCodec
      }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);
      const {
        type: playlistErrorType,
        groupId: playlistErrorGroupId
      } = (_data$context2 = data.context) != null ? _data$context2 : {};
      for (let i = levels.length; i--; ) {
        const candidate = (i + loadLevel) % levels.length;
        if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
          var _level$audioGroups, _level$subtitleGroups;
          const levelCandidate = levels[candidate];
          if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
            const levelDetails = levels[candidate].details;
            if (levelDetails) {
              const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
              if (fragCandidate != null && fragCandidate.gap) {
                continue;
              }
            }
          } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
            continue;
          } else if (fragErrorType === PlaylistLevelType.AUDIO && (_level$audioGroups = level.audioGroups) != null && _level$audioGroups.some((groupId) => levelCandidate.hasAudioGroup(groupId)) || fragErrorType === PlaylistLevelType.SUBTITLE && (_level$subtitleGroups = level.subtitleGroups) != null && _level$subtitleGroups.some((groupId) => levelCandidate.hasSubtitleGroup(groupId)) || findAudioCodecAlternate && level.audioCodec === levelCandidate.audioCodec || !findAudioCodecAlternate && level.audioCodec !== levelCandidate.audioCodec || findVideoCodecAlternate && level.codecSet === levelCandidate.codecSet) {
            continue;
          }
          nextLevel = candidate;
          break;
        }
      }
      if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
        data.levelRetry = true;
        this.playlistError = 0;
        return {
          action: NetworkErrorAction.SendAlternateToPenaltyBox,
          flags: ErrorActionFlags.None,
          nextAutoLevel: nextLevel
        };
      }
    }
    return {
      action: NetworkErrorAction.SendAlternateToPenaltyBox,
      flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
    };
  }
  onErrorOut(event, data) {
    var _data$errorAction;
    switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
      case NetworkErrorAction.DoNothing:
        break;
      case NetworkErrorAction.SendAlternateToPenaltyBox:
        this.sendAlternateToPenaltyBox(data);
        if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
          data.fatal = true;
        } else if (/MediaSource readyState: ended/.test(data.error.message)) {
          this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`);
          this.hls.recoverMediaError();
        }
        break;
      case NetworkErrorAction.RetryRequest:
        break;
    }
    if (data.fatal) {
      this.hls.stopLoad();
      return;
    }
  }
  sendAlternateToPenaltyBox(data) {
    const hls = this.hls;
    const errorAction = data.errorAction;
    if (!errorAction) {
      return;
    }
    const {
      flags,
      hdcpLevel,
      nextAutoLevel
    } = errorAction;
    switch (flags) {
      case ErrorActionFlags.None:
        this.switchLevel(data, nextAutoLevel);
        break;
      case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
        if (hdcpLevel) {
          hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
          errorAction.resolved = true;
        }
        this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`);
        break;
    }
    if (!errorAction.resolved) {
      this.switchLevel(data, nextAutoLevel);
    }
  }
  switchLevel(data, levelIndex) {
    if (levelIndex !== void 0 && data.errorAction) {
      this.warn(`switching to level ${levelIndex} after ${data.details}`);
      this.hls.nextAutoLevel = levelIndex;
      data.errorAction.resolved = true;
      this.hls.nextLoadLevel = this.hls.nextAutoLevel;
      if (data.details === ErrorDetails.BUFFER_ADD_CODEC_ERROR && data.mimeType && data.sourceBufferName !== "audiovideo") {
        const codec = getCodecsForMimeType(data.mimeType);
        const levels = this.hls.levels;
        for (let i = levels.length; i--; ) {
          if (levels[i][`${data.sourceBufferName}Codec`] === codec) {
            this.hls.removeLevel(i);
          }
        }
      }
    }
  }
};
function createDoNothingErrorAction(resolved) {
  const errorAction = {
    action: NetworkErrorAction.DoNothing,
    flags: ErrorActionFlags.None
  };
  if (resolved) {
    errorAction.resolved = true;
  }
  return errorAction;
}
var FragmentState = {
  NOT_LOADED: "NOT_LOADED",
  APPENDING: "APPENDING",
  PARTIAL: "PARTIAL",
  OK: "OK"
};
var FragmentTracker = class {
  constructor(hls) {
    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 = false;
    this.hls = hls;
    this._registerListeners();
  }
  _registerListeners() {
    const {
      hls
    } = this;
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
    hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
    hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  }
  _unregisterListeners() {
    const {
      hls
    } = this;
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
    hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
    hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  }
  destroy() {
    this._unregisterListeners();
    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(position, levelType) {
    const activeParts = this.activePartLists[levelType];
    if (activeParts) {
      for (let i = activeParts.length; i--; ) {
        const activePart = activeParts[i];
        if (!activePart) {
          break;
        }
        const appendedPTS = activePart.end;
        if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
          return activePart;
        }
      }
    }
    return this.getBufferedFrag(position, levelType);
  }
  /**
   * 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(position, levelType) {
    return this.getFragAtPos(position, levelType, true);
  }
  getFragAtPos(position, levelType, buffered) {
    const {
      fragments
    } = this;
    const keys3 = Object.keys(fragments);
    for (let i = keys3.length; i--; ) {
      const fragmentEntity = fragments[keys3[i]];
      if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && (!buffered || fragmentEntity.buffered)) {
        const frag = fragmentEntity.body;
        if (frag.start <= position && position <= frag.end) {
          return frag;
        }
      }
    }
    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(elementaryStream, timeRange, playlistType, appendedPart, removeAppending) {
    if (this.timeRanges) {
      this.timeRanges[elementaryStream] = timeRange;
    }
    const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
    Object.keys(this.fragments).forEach((key) => {
      const fragmentEntity = this.fragments[key];
      if (!fragmentEntity) {
        return;
      }
      if (appendedPartSn >= fragmentEntity.body.sn) {
        return;
      }
      if (!fragmentEntity.buffered && (!fragmentEntity.loaded || removeAppending)) {
        if (fragmentEntity.body.type === playlistType) {
          this.removeFragment(fragmentEntity.body);
        }
        return;
      }
      const esData = fragmentEntity.range[elementaryStream];
      if (!esData) {
        return;
      }
      if (esData.time.length === 0) {
        this.removeFragment(fragmentEntity.body);
        return;
      }
      esData.time.some((time) => {
        const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
        if (isNotBuffered) {
          this.removeFragment(fragmentEntity.body);
        }
        return isNotBuffered;
      });
    });
  }
  /**
   * Checks if the fragment passed in is loaded in the buffer properly
   * Partially loaded fragments will be registered as a partial fragment
   */
  detectPartialFragments(data) {
    const timeRanges = this.timeRanges;
    if (!timeRanges || data.frag.sn === "initSegment") {
      return;
    }
    const frag = data.frag;
    const fragKey = getFragmentKey(frag);
    const fragmentEntity = this.fragments[fragKey];
    if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
      return;
    }
    const isFragHint = !frag.relurl;
    Object.keys(timeRanges).forEach((elementaryStream) => {
      const streamInfo = frag.elementaryStreams[elementaryStream];
      if (!streamInfo) {
        return;
      }
      const timeRange = timeRanges[elementaryStream];
      const partial = isFragHint || streamInfo.partial === true;
      fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, data.part, partial, timeRange);
    });
    fragmentEntity.loaded = null;
    if (Object.keys(fragmentEntity.range).length) {
      fragmentEntity.buffered = true;
      const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
      if (endList) {
        this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
      }
      if (!isPartial(fragmentEntity)) {
        this.removeParts(frag.sn - 1, frag.type);
      }
    } else {
      this.removeFragment(fragmentEntity.body);
    }
  }
  removeParts(snToKeep, levelType) {
    const activeParts = this.activePartLists[levelType];
    if (!activeParts) {
      return;
    }
    this.activePartLists[levelType] = activeParts.filter((part) => part.fragment.sn >= snToKeep);
  }
  fragBuffered(frag, force) {
    const fragKey = getFragmentKey(frag);
    let fragmentEntity = this.fragments[fragKey];
    if (!fragmentEntity && force) {
      fragmentEntity = this.fragments[fragKey] = {
        body: frag,
        appendedPTS: null,
        loaded: null,
        buffered: false,
        range: /* @__PURE__ */ Object.create(null)
      };
      if (frag.gap) {
        this.hasGaps = true;
      }
    }
    if (fragmentEntity) {
      fragmentEntity.loaded = null;
      fragmentEntity.buffered = true;
    }
  }
  getBufferedTimes(fragment, part, partial, timeRange) {
    const buffered = {
      time: [],
      partial
    };
    const startPTS = fragment.start;
    const endPTS = fragment.end;
    const minEndPTS = fragment.minEndPTS || endPTS;
    const maxStartPTS = fragment.maxStartPTS || startPTS;
    for (let i = 0; i < timeRange.length; i++) {
      const startTime = timeRange.start(i) - this.bufferPadding;
      const endTime = timeRange.end(i) + this.bufferPadding;
      if (maxStartPTS >= startTime && minEndPTS <= endTime) {
        buffered.time.push({
          startPTS: Math.max(startPTS, timeRange.start(i)),
          endPTS: Math.min(endPTS, timeRange.end(i))
        });
        break;
      } else if (startPTS < endTime && endPTS > startTime) {
        const start2 = Math.max(startPTS, timeRange.start(i));
        const end = Math.min(endPTS, timeRange.end(i));
        if (end > start2) {
          buffered.partial = true;
          buffered.time.push({
            startPTS: start2,
            endPTS: end
          });
        }
      } else if (endPTS <= startTime) {
        break;
      }
    }
    return buffered;
  }
  /**
   * Gets the partial fragment for a certain time
   */
  getPartialFragment(time) {
    let bestFragment = null;
    let timePadding;
    let startTime;
    let endTime;
    let bestOverlap = 0;
    const {
      bufferPadding,
      fragments
    } = this;
    Object.keys(fragments).forEach((key) => {
      const fragmentEntity = fragments[key];
      if (!fragmentEntity) {
        return;
      }
      if (isPartial(fragmentEntity)) {
        startTime = fragmentEntity.body.start - bufferPadding;
        endTime = fragmentEntity.body.end + bufferPadding;
        if (time >= startTime && time <= endTime) {
          timePadding = Math.min(time - startTime, endTime - time);
          if (bestOverlap <= timePadding) {
            bestFragment = fragmentEntity.body;
            bestOverlap = timePadding;
          }
        }
      }
    });
    return bestFragment;
  }
  isEndListAppended(type2) {
    const lastFragmentEntity = this.endListFragments[type2];
    return lastFragmentEntity !== void 0 && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  }
  getState(fragment) {
    const fragKey = getFragmentKey(fragment);
    const fragmentEntity = this.fragments[fragKey];
    if (fragmentEntity) {
      if (!fragmentEntity.buffered) {
        return FragmentState.APPENDING;
      } else if (isPartial(fragmentEntity)) {
        return FragmentState.PARTIAL;
      } else {
        return FragmentState.OK;
      }
    }
    return FragmentState.NOT_LOADED;
  }
  isTimeBuffered(startPTS, endPTS, timeRange) {
    let startTime;
    let endTime;
    for (let i = 0; i < timeRange.length; i++) {
      startTime = timeRange.start(i) - this.bufferPadding;
      endTime = timeRange.end(i) + this.bufferPadding;
      if (startPTS >= startTime && endPTS <= endTime) {
        return true;
      }
      if (endPTS <= startTime) {
        return false;
      }
    }
    return false;
  }
  onManifestLoading() {
    this.removeAllFragments();
  }
  onFragLoaded(event, data) {
    if (data.frag.sn === "initSegment" || data.frag.bitrateTest) {
      return;
    }
    const frag = data.frag;
    const loaded = data.part ? null : data;
    const fragKey = getFragmentKey(frag);
    this.fragments[fragKey] = {
      body: frag,
      appendedPTS: null,
      loaded,
      buffered: false,
      range: /* @__PURE__ */ Object.create(null)
    };
  }
  onBufferAppended(event, data) {
    const {
      frag,
      part,
      timeRanges,
      type: type2
    } = data;
    if (frag.sn === "initSegment") {
      return;
    }
    const playlistType = frag.type;
    if (part) {
      let activeParts = this.activePartLists[playlistType];
      if (!activeParts) {
        this.activePartLists[playlistType] = activeParts = [];
      }
      activeParts.push(part);
    }
    this.timeRanges = timeRanges;
    const timeRange = timeRanges[type2];
    this.detectEvictedFragments(type2, timeRange, playlistType, part);
  }
  onFragBuffered(event, data) {
    this.detectPartialFragments(data);
  }
  hasFragment(fragment) {
    const fragKey = getFragmentKey(fragment);
    return !!this.fragments[fragKey];
  }
  hasFragments(type2) {
    const {
      fragments
    } = this;
    const keys3 = Object.keys(fragments);
    if (!type2) {
      return keys3.length > 0;
    }
    for (let i = keys3.length; i--; ) {
      const fragmentEntity = fragments[keys3[i]];
      if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === type2) {
        return true;
      }
    }
    return false;
  }
  hasParts(type2) {
    var _this$activePartLists;
    return !!((_this$activePartLists = this.activePartLists[type2]) != null && _this$activePartLists.length);
  }
  removeFragmentsInRange(start2, end, playlistType, withGapOnly, unbufferedOnly) {
    if (withGapOnly && !this.hasGaps) {
      return;
    }
    Object.keys(this.fragments).forEach((key) => {
      const fragmentEntity = this.fragments[key];
      if (!fragmentEntity) {
        return;
      }
      const frag = fragmentEntity.body;
      if (frag.type !== playlistType || withGapOnly && !frag.gap) {
        return;
      }
      if (frag.start < end && frag.end > start2 && (fragmentEntity.buffered || unbufferedOnly)) {
        this.removeFragment(frag);
      }
    });
  }
  removeFragment(fragment) {
    const fragKey = getFragmentKey(fragment);
    fragment.clearElementaryStreamInfo();
    const activeParts = this.activePartLists[fragment.type];
    if (activeParts) {
      const snToRemove = fragment.sn;
      this.activePartLists[fragment.type] = activeParts.filter((part) => part.fragment.sn !== snToRemove);
    }
    delete this.fragments[fragKey];
    if (fragment.endList) {
      delete this.endListFragments[fragment.type];
    }
  }
  removeAllFragments() {
    var _this$hls, _this$hls$latestLevel;
    this.fragments = /* @__PURE__ */ Object.create(null);
    this.endListFragments = /* @__PURE__ */ Object.create(null);
    this.activePartLists = /* @__PURE__ */ Object.create(null);
    this.hasGaps = false;
    const partlist = (_this$hls = this.hls) == null ? void 0 : (_this$hls$latestLevel = _this$hls.latestLevelDetails) == null ? void 0 : _this$hls$latestLevel.partList;
    if (partlist) {
      partlist.forEach((part) => part.clearElementaryStreamInfo());
    }
  }
};
function isPartial(fragmentEntity) {
  var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  return fragmentEntity.buffered && (fragmentEntity.body.gap || ((_fragmentEntity$range = fragmentEntity.range.video) == null ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) == null ? void 0 : _fragmentEntity$range2.partial) || ((_fragmentEntity$range3 = fragmentEntity.range.audiovideo) == null ? void 0 : _fragmentEntity$range3.partial));
}
function getFragmentKey(fragment) {
  return `${fragment.type}_${fragment.level}_${fragment.sn}`;
}
var DecrypterAesMode = {
  cbc: 0,
  ctr: 1
};
var AESCrypto = class {
  constructor(subtle, iv, aesMode) {
    this.subtle = void 0;
    this.aesIV = void 0;
    this.aesMode = void 0;
    this.subtle = subtle;
    this.aesIV = iv;
    this.aesMode = aesMode;
  }
  decrypt(data, key) {
    switch (this.aesMode) {
      case DecrypterAesMode.cbc:
        return this.subtle.decrypt({
          name: "AES-CBC",
          iv: this.aesIV
        }, key, data);
      case DecrypterAesMode.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
          key,
          data
        );
      default:
        throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`);
    }
  }
};
function removePadding(array) {
  const outputBytes = array.byteLength;
  const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  if (paddingBytes) {
    return array.slice(0, outputBytes - paddingBytes);
  }
  return array;
}
var AESDecryptor = class {
  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_(arrayBuffer) {
    const view2 = new DataView(arrayBuffer);
    const newArray = new Uint32Array(4);
    for (let i = 0; i < 4; i++) {
      newArray[i] = view2.getUint32(i * 4);
    }
    return newArray;
  }
  initTable() {
    const sBox = this.sBox;
    const invSBox = this.invSBox;
    const subMix = this.subMix;
    const subMix0 = subMix[0];
    const subMix1 = subMix[1];
    const subMix2 = subMix[2];
    const subMix3 = subMix[3];
    const invSubMix = this.invSubMix;
    const invSubMix0 = invSubMix[0];
    const invSubMix1 = invSubMix[1];
    const invSubMix2 = invSubMix[2];
    const invSubMix3 = invSubMix[3];
    const d2 = new Uint32Array(256);
    let x = 0;
    let xi = 0;
    let i = 0;
    for (i = 0; i < 256; i++) {
      if (i < 128) {
        d2[i] = i << 1;
      } else {
        d2[i] = i << 1 ^ 283;
      }
    }
    for (i = 0; i < 256; i++) {
      let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
      sx = sx >>> 8 ^ sx & 255 ^ 99;
      sBox[x] = sx;
      invSBox[sx] = x;
      const x2 = d2[x];
      const x4 = d2[x2];
      const x8 = d2[x4];
      let t2 = d2[sx] * 257 ^ sx * 16843008;
      subMix0[x] = t2 << 24 | t2 >>> 8;
      subMix1[x] = t2 << 16 | t2 >>> 16;
      subMix2[x] = t2 << 8 | t2 >>> 24;
      subMix3[x] = t2;
      t2 = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008;
      invSubMix0[sx] = t2 << 24 | t2 >>> 8;
      invSubMix1[sx] = t2 << 16 | t2 >>> 16;
      invSubMix2[sx] = t2 << 8 | t2 >>> 24;
      invSubMix3[sx] = t2;
      if (!x) {
        x = xi = 1;
      } else {
        x = x2 ^ d2[d2[d2[x8 ^ x2]]];
        xi ^= d2[d2[xi]];
      }
    }
  }
  expandKey(keyBuffer) {
    const key = this.uint8ArrayToUint32Array_(keyBuffer);
    let sameKey = true;
    let offset = 0;
    while (offset < key.length && sameKey) {
      sameKey = key[offset] === this.key[offset];
      offset++;
    }
    if (sameKey) {
      return;
    }
    this.key = key;
    const keySize = this.keySize = key.length;
    if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
      throw new Error("Invalid aes key size=" + keySize);
    }
    const ksRows = this.ksRows = (keySize + 6 + 1) * 4;
    let ksRow;
    let invKsRow;
    const keySchedule = this.keySchedule = new Uint32Array(ksRows);
    const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
    const sbox = this.sBox;
    const rcon = this.rcon;
    const invSubMix = this.invSubMix;
    const invSubMix0 = invSubMix[0];
    const invSubMix1 = invSubMix[1];
    const invSubMix2 = invSubMix[2];
    const invSubMix3 = invSubMix[3];
    let prev;
    let t2;
    for (ksRow = 0; ksRow < ksRows; ksRow++) {
      if (ksRow < keySize) {
        prev = keySchedule[ksRow] = key[ksRow];
        continue;
      }
      t2 = prev;
      if (ksRow % keySize === 0) {
        t2 = t2 << 8 | t2 >>> 24;
        t2 = sbox[t2 >>> 24] << 24 | sbox[t2 >>> 16 & 255] << 16 | sbox[t2 >>> 8 & 255] << 8 | sbox[t2 & 255];
        t2 ^= rcon[ksRow / keySize | 0] << 24;
      } else if (keySize > 6 && ksRow % keySize === 4) {
        t2 = sbox[t2 >>> 24] << 24 | sbox[t2 >>> 16 & 255] << 16 | sbox[t2 >>> 8 & 255] << 8 | sbox[t2 & 255];
      }
      keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t2) >>> 0;
    }
    for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
      ksRow = ksRows - invKsRow;
      if (invKsRow & 3) {
        t2 = keySchedule[ksRow];
      } else {
        t2 = keySchedule[ksRow - 4];
      }
      if (invKsRow < 4 || ksRow <= 4) {
        invKeySchedule[invKsRow] = t2;
      } else {
        invKeySchedule[invKsRow] = invSubMix0[sbox[t2 >>> 24]] ^ invSubMix1[sbox[t2 >>> 16 & 255]] ^ invSubMix2[sbox[t2 >>> 8 & 255]] ^ invSubMix3[sbox[t2 & 255]];
      }
      invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
    }
  }
  // Adding this as a method greatly improves performance.
  networkToHostOrderSwap(word) {
    return word << 24 | (word & 65280) << 8 | (word & 16711680) >> 8 | word >>> 24;
  }
  decrypt(inputArrayBuffer, offset, aesIV) {
    const nRounds = this.keySize + 6;
    const invKeySchedule = this.invKeySchedule;
    const invSBOX = this.invSBox;
    const invSubMix = this.invSubMix;
    const invSubMix0 = invSubMix[0];
    const invSubMix1 = invSubMix[1];
    const invSubMix2 = invSubMix[2];
    const invSubMix3 = invSubMix[3];
    const initVector = this.uint8ArrayToUint32Array_(aesIV);
    let initVector0 = initVector[0];
    let initVector1 = initVector[1];
    let initVector2 = initVector[2];
    let initVector3 = initVector[3];
    const inputInt32 = new Int32Array(inputArrayBuffer);
    const outputInt32 = new Int32Array(inputInt32.length);
    let t0, t1, t2, t3;
    let s0, s1, s2, s3;
    let inputWords0, inputWords1, inputWords2, inputWords3;
    let ksRow, i;
    const swapWord = this.networkToHostOrderSwap;
    while (offset < inputInt32.length) {
      inputWords0 = swapWord(inputInt32[offset]);
      inputWords1 = swapWord(inputInt32[offset + 1]);
      inputWords2 = swapWord(inputInt32[offset + 2]);
      inputWords3 = swapWord(inputInt32[offset + 3]);
      s0 = inputWords0 ^ invKeySchedule[0];
      s1 = inputWords3 ^ invKeySchedule[1];
      s2 = inputWords2 ^ invKeySchedule[2];
      s3 = inputWords1 ^ invKeySchedule[3];
      ksRow = 4;
      for (i = 1; i < nRounds; i++) {
        t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 255] ^ invSubMix2[s2 >> 8 & 255] ^ invSubMix3[s3 & 255] ^ invKeySchedule[ksRow];
        t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 255] ^ invSubMix2[s3 >> 8 & 255] ^ invSubMix3[s0 & 255] ^ invKeySchedule[ksRow + 1];
        t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 255] ^ invSubMix2[s0 >> 8 & 255] ^ invSubMix3[s1 & 255] ^ invKeySchedule[ksRow + 2];
        t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 255] ^ invSubMix2[s1 >> 8 & 255] ^ invSubMix3[s2 & 255] ^ invKeySchedule[ksRow + 3];
        s0 = t0;
        s1 = t1;
        s2 = t2;
        s3 = t3;
        ksRow = ksRow + 4;
      }
      t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 255] << 16 ^ invSBOX[s2 >> 8 & 255] << 8 ^ invSBOX[s3 & 255] ^ invKeySchedule[ksRow];
      t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 255] << 16 ^ invSBOX[s3 >> 8 & 255] << 8 ^ invSBOX[s0 & 255] ^ invKeySchedule[ksRow + 1];
      t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 255] << 16 ^ invSBOX[s0 >> 8 & 255] << 8 ^ invSBOX[s1 & 255] ^ invKeySchedule[ksRow + 2];
      t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 255] << 16 ^ invSBOX[s1 >> 8 & 255] << 8 ^ invSBOX[s2 & 255] ^ invKeySchedule[ksRow + 3];
      outputInt32[offset] = swapWord(t0 ^ initVector0);
      outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
      outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
      outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
      initVector0 = inputWords0;
      initVector1 = inputWords1;
      initVector2 = inputWords2;
      initVector3 = inputWords3;
      offset = offset + 4;
    }
    return outputInt32.buffer;
  }
};
var FastAESKey = class {
  constructor(subtle, key, aesMode) {
    this.subtle = void 0;
    this.key = void 0;
    this.aesMode = void 0;
    this.subtle = subtle;
    this.key = key;
    this.aesMode = aesMode;
  }
  expandKey() {
    const subtleAlgoName = getSubtleAlgoName(this.aesMode);
    return this.subtle.importKey("raw", this.key, {
      name: subtleAlgoName
    }, false, ["encrypt", "decrypt"]);
  }
};
function getSubtleAlgoName(aesMode) {
  switch (aesMode) {
    case DecrypterAesMode.cbc:
      return "AES-CBC";
    case DecrypterAesMode.ctr:
      return "AES-CTR";
    default:
      throw new Error(`[FastAESKey] invalid aes mode ${aesMode}`);
  }
}
var CHUNK_SIZE = 16;
var Decrypter = class {
  constructor(config, {
    removePKCS7Padding = true
  } = {}) {
    this.logEnabled = true;
    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 = config.enableSoftwareAES;
    this.removePKCS7Padding = removePKCS7Padding;
    if (removePKCS7Padding) {
      try {
        const browserCrypto = self.crypto;
        if (browserCrypto) {
          this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
        }
      } catch (e) {
      }
    }
    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,
      remainderData
    } = this;
    if (!currentResult || remainderData) {
      this.reset();
      return null;
    }
    const data = new Uint8Array(currentResult);
    this.reset();
    if (this.removePKCS7Padding) {
      return removePadding(data);
    }
    return data;
  }
  reset() {
    this.currentResult = null;
    this.currentIV = null;
    this.remainderData = null;
    if (this.softwareDecrypter) {
      this.softwareDecrypter = null;
    }
  }
  decrypt(data, key, iv, aesMode) {
    if (this.useSoftware) {
      return new Promise((resolve, reject) => {
        const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
        this.softwareDecrypt(dataView, key, iv, aesMode);
        const decryptResult = this.flush();
        if (decryptResult) {
          resolve(decryptResult.buffer);
        } else {
          reject(new Error("[softwareDecrypt] Failed to decrypt data"));
        }
      });
    }
    return this.webCryptoDecrypt(new Uint8Array(data), key, iv, aesMode);
  }
  // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  // data is handled in the flush() call
  softwareDecrypt(data, key, iv, aesMode) {
    const {
      currentIV,
      currentResult,
      remainderData
    } = this;
    if (aesMode !== DecrypterAesMode.cbc || key.byteLength !== 16) {
      logger.warn("SoftwareDecrypt: can only handle AES-128-CBC");
      return null;
    }
    this.logOnce("JS AES decrypt");
    if (remainderData) {
      data = appendUint8Array(remainderData, data);
      this.remainderData = null;
    }
    const currentChunk = this.getValidChunk(data);
    if (!currentChunk.length) {
      return null;
    }
    if (currentIV) {
      iv = currentIV;
    }
    let softwareDecrypter = this.softwareDecrypter;
    if (!softwareDecrypter) {
      softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
    }
    softwareDecrypter.expandKey(key);
    const result = currentResult;
    this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
    this.currentIV = currentChunk.slice(-16).buffer;
    if (!result) {
      return null;
    }
    return result;
  }
  webCryptoDecrypt(data, key, iv, aesMode) {
    if (this.key !== key || !this.fastAesKey) {
      if (!this.subtle) {
        return Promise.resolve(this.onWebCryptoError(data, key, iv, aesMode));
      }
      this.key = key;
      this.fastAesKey = new FastAESKey(this.subtle, key, aesMode);
    }
    return this.fastAesKey.expandKey().then((aesKey) => {
      if (!this.subtle) {
        return Promise.reject(new Error("web crypto not initialized"));
      }
      this.logOnce("WebCrypto AES decrypt");
      const crypto2 = new AESCrypto(this.subtle, new Uint8Array(iv), aesMode);
      return crypto2.decrypt(data.buffer, aesKey);
    }).catch((err) => {
      logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);
      return this.onWebCryptoError(data, key, iv, aesMode);
    });
  }
  onWebCryptoError(data, key, iv, aesMode) {
    const enableSoftwareAES = this.enableSoftwareAES;
    if (enableSoftwareAES) {
      this.useSoftware = true;
      this.logEnabled = true;
      this.softwareDecrypt(data, key, iv, aesMode);
      const decryptResult = this.flush();
      if (decryptResult) {
        return decryptResult.buffer;
      }
    }
    throw new Error("WebCrypto" + (enableSoftwareAES ? " and softwareDecrypt" : "") + ": failed to decrypt data");
  }
  getValidChunk(data) {
    let currentChunk = data;
    const splitPoint = data.length - data.length % CHUNK_SIZE;
    if (splitPoint !== data.length) {
      currentChunk = data.slice(0, splitPoint);
      this.remainderData = data.slice(splitPoint);
    }
    return currentChunk;
  }
  logOnce(msg) {
    if (!this.logEnabled) {
      return;
    }
    logger.log(`[decrypter]: ${msg}`);
    this.logEnabled = false;
  }
};
var MIN_CHUNK_SIZE = Math.pow(2, 17);
var FragmentLoader = class {
  constructor(config) {
    this.config = void 0;
    this.loader = null;
    this.partLoadTimeout = -1;
    this.config = config;
  }
  destroy() {
    if (this.loader) {
      this.loader.destroy();
      this.loader = null;
    }
  }
  abort() {
    if (this.loader) {
      this.loader.abort();
    }
  }
  load(frag, onProgress) {
    const url = frag.url;
    if (!url) {
      return Promise.reject(new LoadError({
        type: ErrorTypes.NETWORK_ERROR,
        details: ErrorDetails.FRAG_LOAD_ERROR,
        fatal: false,
        frag,
        error: new Error(`Fragment does not have a ${url ? "part list" : "url"}`),
        networkDetails: null
      }));
    }
    this.abort();
    const config = this.config;
    const FragmentILoader = config.fLoader;
    const DefaultILoader = config.loader;
    return new Promise((resolve, reject) => {
      if (this.loader) {
        this.loader.destroy();
      }
      if (frag.gap) {
        if (frag.tagList.some((tags) => tags[0] === "GAP")) {
          reject(createGapLoadError(frag));
          return;
        } else {
          frag.gap = false;
        }
      }
      const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
      const loaderContext = createLoaderContext(frag);
      frag.loader = loader;
      const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
      const loaderConfig = {
        loadPolicy,
        timeout: loadPolicy.maxLoadTimeMs,
        maxRetry: 0,
        retryDelay: 0,
        maxRetryDelay: 0,
        highWaterMark: frag.sn === "initSegment" ? Infinity : MIN_CHUNK_SIZE
      };
      frag.stats = loader.stats;
      const callbacks = {
        onSuccess: (response, stats, context, networkDetails) => {
          this.resetLoader(frag, loader);
          let payload = response.data;
          if (context.resetIV && frag.decryptdata) {
            frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
            payload = payload.slice(16);
          }
          resolve({
            frag,
            part: null,
            payload,
            networkDetails
          });
        },
        onError: (response, context, networkDetails, stats) => {
          this.resetLoader(frag, loader);
          reject(new LoadError({
            type: ErrorTypes.NETWORK_ERROR,
            details: ErrorDetails.FRAG_LOAD_ERROR,
            fatal: false,
            frag,
            response: _objectSpread2({
              url,
              data: void 0
            }, response),
            error: new Error(`HTTP Error ${response.code} ${response.text}`),
            networkDetails,
            stats
          }));
        },
        onAbort: (stats, context, networkDetails) => {
          this.resetLoader(frag, loader);
          reject(new LoadError({
            type: ErrorTypes.NETWORK_ERROR,
            details: ErrorDetails.INTERNAL_ABORTED,
            fatal: false,
            frag,
            error: new Error("Aborted"),
            networkDetails,
            stats
          }));
        },
        onTimeout: (stats, context, networkDetails) => {
          this.resetLoader(frag, loader);
          reject(new LoadError({
            type: ErrorTypes.NETWORK_ERROR,
            details: ErrorDetails.FRAG_LOAD_TIMEOUT,
            fatal: false,
            frag,
            error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
            networkDetails,
            stats
          }));
        }
      };
      if (onProgress) {
        callbacks.onProgress = (stats, context, data, networkDetails) => onProgress({
          frag,
          part: null,
          payload: data,
          networkDetails
        });
      }
      loader.load(loaderContext, loaderConfig, callbacks);
    });
  }
  loadPart(frag, part, onProgress) {
    this.abort();
    const config = this.config;
    const FragmentILoader = config.fLoader;
    const DefaultILoader = config.loader;
    return new Promise((resolve, reject) => {
      if (this.loader) {
        this.loader.destroy();
      }
      if (frag.gap || part.gap) {
        reject(createGapLoadError(frag, part));
        return;
      }
      const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
      const loaderContext = createLoaderContext(frag, part);
      frag.loader = loader;
      const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
      const loaderConfig = {
        loadPolicy,
        timeout: loadPolicy.maxLoadTimeMs,
        maxRetry: 0,
        retryDelay: 0,
        maxRetryDelay: 0,
        highWaterMark: MIN_CHUNK_SIZE
      };
      part.stats = loader.stats;
      loader.load(loaderContext, loaderConfig, {
        onSuccess: (response, stats, context, networkDetails) => {
          this.resetLoader(frag, loader);
          this.updateStatsFromPart(frag, part);
          const partLoadedData = {
            frag,
            part,
            payload: response.data,
            networkDetails
          };
          onProgress(partLoadedData);
          resolve(partLoadedData);
        },
        onError: (response, context, networkDetails, stats) => {
          this.resetLoader(frag, loader);
          reject(new LoadError({
            type: ErrorTypes.NETWORK_ERROR,
            details: ErrorDetails.FRAG_LOAD_ERROR,
            fatal: false,
            frag,
            part,
            response: _objectSpread2({
              url: loaderContext.url,
              data: void 0
            }, response),
            error: new Error(`HTTP Error ${response.code} ${response.text}`),
            networkDetails,
            stats
          }));
        },
        onAbort: (stats, context, networkDetails) => {
          frag.stats.aborted = part.stats.aborted;
          this.resetLoader(frag, loader);
          reject(new LoadError({
            type: ErrorTypes.NETWORK_ERROR,
            details: ErrorDetails.INTERNAL_ABORTED,
            fatal: false,
            frag,
            part,
            error: new Error("Aborted"),
            networkDetails,
            stats
          }));
        },
        onTimeout: (stats, context, networkDetails) => {
          this.resetLoader(frag, loader);
          reject(new LoadError({
            type: ErrorTypes.NETWORK_ERROR,
            details: ErrorDetails.FRAG_LOAD_TIMEOUT,
            fatal: false,
            frag,
            part,
            error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
            networkDetails,
            stats
          }));
        }
      });
    });
  }
  updateStatsFromPart(frag, part) {
    const fragStats = frag.stats;
    const partStats = part.stats;
    const partTotal = partStats.total;
    fragStats.loaded += partStats.loaded;
    if (partTotal) {
      const estTotalParts = Math.round(frag.duration / part.duration);
      const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
      const estRemainingParts = estTotalParts - estLoadedParts;
      const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
      fragStats.total = fragStats.loaded + estRemainingBytes;
    } else {
      fragStats.total = Math.max(fragStats.loaded, fragStats.total);
    }
    const fragLoading = fragStats.loading;
    const partLoading = partStats.loading;
    if (fragLoading.start) {
      fragLoading.first += partLoading.first - partLoading.start;
    } else {
      fragLoading.start = partLoading.start;
      fragLoading.first = partLoading.first;
    }
    fragLoading.end = partLoading.end;
  }
  resetLoader(frag, loader) {
    frag.loader = null;
    if (this.loader === loader) {
      self.clearTimeout(this.partLoadTimeout);
      this.loader = null;
    }
    loader.destroy();
  }
};
function createLoaderContext(frag, part = null) {
  const segment = part || frag;
  const loaderContext = {
    frag,
    part,
    responseType: "arraybuffer",
    url: segment.url,
    headers: {},
    rangeStart: 0,
    rangeEnd: 0
  };
  const start2 = segment.byteRangeStartOffset;
  const end = segment.byteRangeEndOffset;
  if (isFiniteNumber(start2) && isFiniteNumber(end)) {
    var _frag$decryptdata;
    let byteRangeStart = start2;
    let byteRangeEnd = end;
    if (frag.sn === "initSegment" && isMethodFullSegmentAesCbc((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method)) {
      const fragmentLen = end - start2;
      if (fragmentLen % 16) {
        byteRangeEnd = end + (16 - fragmentLen % 16);
      }
      if (start2 !== 0) {
        loaderContext.resetIV = true;
        byteRangeStart = start2 - 16;
      }
    }
    loaderContext.rangeStart = byteRangeStart;
    loaderContext.rangeEnd = byteRangeEnd;
  }
  return loaderContext;
}
function createGapLoadError(frag, part) {
  const error = new Error(`GAP ${frag.gap ? "tag" : "attribute"} found`);
  const errorData = {
    type: ErrorTypes.MEDIA_ERROR,
    details: ErrorDetails.FRAG_GAP,
    fatal: false,
    frag,
    error,
    networkDetails: null
  };
  if (part) {
    errorData.part = part;
  }
  (part ? part : frag).stats.aborted = true;
  return new LoadError(errorData);
}
function isMethodFullSegmentAesCbc(method) {
  return method === "AES-128" || method === "AES-256";
}
var LoadError = class extends Error {
  constructor(data) {
    super(data.error.message);
    this.data = void 0;
    this.data = data;
  }
};
var TaskLoop = class extends Logger {
  constructor(label, logger4) {
    super(label, logger4);
    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(millis) {
    if (!this._tickInterval) {
      this._tickCallCount = 0;
      this._tickInterval = self.setInterval(this._boundTick, millis);
      return true;
    }
    return false;
  }
  /**
   * @returns True when interval was cleared, false when none was set (no effect)
   */
  clearInterval() {
    if (this._tickInterval) {
      self.clearInterval(this._tickInterval);
      this._tickInterval = null;
      return true;
    }
    return false;
  }
  /**
   * @returns True when timeout was cleared, false when none was set (no effect)
   */
  clearNextTick() {
    if (this._tickTimer) {
      self.clearTimeout(this._tickTimer);
      this._tickTimer = null;
      return true;
    }
    return false;
  }
  /**
   * 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++;
    if (this._tickCallCount === 1) {
      this.doTick();
      if (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() {
  }
};
var ChunkMetadata = class {
  constructor(level, sn, id, size = 0, part = -1, partial = false) {
    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 = getNewPerformanceTiming();
    this.buffering = {
      audio: getNewPerformanceTiming(),
      video: getNewPerformanceTiming(),
      audiovideo: getNewPerformanceTiming()
    };
    this.level = level;
    this.sn = sn;
    this.id = id;
    this.size = size;
    this.part = part;
    this.partial = partial;
  }
};
function getNewPerformanceTiming() {
  return {
    start: 0,
    executeStart: 0,
    executeEnd: 0,
    end: 0
  };
}
var noopBuffered = {
  length: 0,
  start: () => 0,
  end: () => 0
};
var BufferHelper = class _BufferHelper {
  /**
   * Return true if `media`'s buffered include `position`
   */
  static isBuffered(media, position) {
    if (media) {
      const buffered = _BufferHelper.getBuffered(media);
      for (let i = buffered.length; i--; ) {
        if (position >= buffered.start(i) && position <= buffered.end(i)) {
          return true;
        }
      }
    }
    return false;
  }
  static bufferedRanges(media) {
    if (media) {
      const timeRanges = _BufferHelper.getBuffered(media);
      return _BufferHelper.timeRangesToArray(timeRanges);
    }
    return [];
  }
  static timeRangesToArray(timeRanges) {
    const buffered = [];
    for (let i = 0; i < timeRanges.length; i++) {
      buffered.push({
        start: timeRanges.start(i),
        end: timeRanges.end(i)
      });
    }
    return buffered;
  }
  static bufferInfo(media, pos, maxHoleDuration) {
    if (media) {
      const buffered = _BufferHelper.bufferedRanges(media);
      if (buffered.length) {
        return _BufferHelper.bufferedInfo(buffered, pos, maxHoleDuration);
      }
    }
    return {
      len: 0,
      start: pos,
      end: pos,
      bufferedIndex: -1
    };
  }
  static bufferedInfo(buffered, pos, maxHoleDuration) {
    pos = Math.max(0, pos);
    if (buffered.length > 1) {
      buffered.sort((a, b) => a.start - b.start || b.end - a.end);
    }
    let bufferedIndex = -1;
    let buffered2 = [];
    if (maxHoleDuration) {
      for (let i = 0; i < buffered.length; i++) {
        if (pos >= buffered[i].start && pos <= buffered[i].end) {
          bufferedIndex = i;
        }
        const buf2len = buffered2.length;
        if (buf2len) {
          const buf2end = buffered2[buf2len - 1].end;
          if (buffered[i].start - buf2end < maxHoleDuration) {
            if (buffered[i].end > buf2end) {
              buffered2[buf2len - 1].end = buffered[i].end;
            }
          } else {
            buffered2.push(buffered[i]);
          }
        } else {
          buffered2.push(buffered[i]);
        }
      }
    } else {
      buffered2 = buffered;
    }
    let bufferLen = 0;
    let nextStart;
    let bufferStart = pos;
    let bufferEnd = pos;
    for (let i = 0; i < buffered2.length; i++) {
      const start2 = buffered2[i].start;
      const end = buffered2[i].end;
      if (bufferedIndex === -1 && pos >= start2 && pos <= end) {
        bufferedIndex = i;
      }
      if (pos + maxHoleDuration >= start2 && pos < end) {
        bufferStart = start2;
        bufferEnd = end;
        bufferLen = bufferEnd - pos;
      } else if (pos + maxHoleDuration < start2) {
        nextStart = start2;
        break;
      }
    }
    return {
      len: bufferLen,
      start: bufferStart || 0,
      end: bufferEnd || 0,
      nextStart,
      buffered,
      bufferedIndex
    };
  }
  /**
   * Safe method to get buffered property.
   * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
   */
  static getBuffered(media) {
    try {
      return media.buffered || noopBuffered;
    } catch (e) {
      logger.log("failed to get media.buffered", e);
      return noopBuffered;
    }
  }
};
var VARIABLE_REPLACEMENT_REGEX = /\{\$([a-zA-Z0-9-_]+)\}/g;
function hasVariableReferences(str) {
  return VARIABLE_REPLACEMENT_REGEX.test(str);
}
function substituteVariables(parsed, value) {
  if (parsed.variableList !== null || parsed.hasVariableRefs) {
    const variableList = parsed.variableList;
    return value.replace(VARIABLE_REPLACEMENT_REGEX, (variableReference) => {
      const variableName = variableReference.substring(2, variableReference.length - 1);
      const variableValue = variableList == null ? void 0 : variableList[variableName];
      if (variableValue === void 0) {
        parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${variableName}"`));
        return variableReference;
      }
      return variableValue;
    });
  }
  return value;
}
function addVariableDefinition(parsed, attr, parentUrl) {
  let variableList = parsed.variableList;
  if (!variableList) {
    parsed.variableList = variableList = {};
  }
  let NAME;
  let VALUE;
  if ("QUERYPARAM" in attr) {
    NAME = attr.QUERYPARAM;
    try {
      const searchParams = new self.URL(parentUrl).searchParams;
      if (searchParams.has(NAME)) {
        VALUE = searchParams.get(NAME);
      } else {
        throw new Error(`"${NAME}" does not match any query parameter in URI: "${parentUrl}"`);
      }
    } catch (error) {
      parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${error.message}`));
    }
  } else {
    NAME = attr.NAME;
    VALUE = attr.VALUE;
  }
  if (NAME in variableList) {
    parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${NAME}"`));
  } else {
    variableList[NAME] = VALUE || "";
  }
}
function importVariableDefinition(parsed, attr, sourceVariableList) {
  const IMPORT = attr.IMPORT;
  if (sourceVariableList && IMPORT in sourceVariableList) {
    let variableList = parsed.variableList;
    if (!variableList) {
      parsed.variableList = variableList = {};
    }
    variableList[IMPORT] = sourceVariableList[IMPORT];
  } else {
    parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${IMPORT}"`));
  }
}
var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
var ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
var AttrList = class _AttrList {
  constructor(attrs, parsed) {
    if (typeof attrs === "string") {
      attrs = _AttrList.parseAttrList(attrs, parsed);
    }
    _extends(this, attrs);
  }
  get clientAttrs() {
    return Object.keys(this).filter((attr) => attr.substring(0, 2) === "X-");
  }
  decimalInteger(attrName) {
    const intValue = parseInt(this[attrName], 10);
    if (intValue > Number.MAX_SAFE_INTEGER) {
      return Infinity;
    }
    return intValue;
  }
  hexadecimalInteger(attrName) {
    if (this[attrName]) {
      let stringValue = (this[attrName] || "0x").slice(2);
      stringValue = (stringValue.length & 1 ? "0" : "") + stringValue;
      const value = new Uint8Array(stringValue.length / 2);
      for (let i = 0; i < stringValue.length / 2; i++) {
        value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
      }
      return value;
    }
    return null;
  }
  hexadecimalIntegerAsNumber(attrName) {
    const intValue = parseInt(this[attrName], 16);
    if (intValue > Number.MAX_SAFE_INTEGER) {
      return Infinity;
    }
    return intValue;
  }
  decimalFloatingPoint(attrName) {
    return parseFloat(this[attrName]);
  }
  optionalFloat(attrName, defaultValue) {
    const value = this[attrName];
    return value ? parseFloat(value) : defaultValue;
  }
  enumeratedString(attrName) {
    return this[attrName];
  }
  enumeratedStringList(attrName, dict) {
    const attrValue = this[attrName];
    return (attrValue ? attrValue.split(/[ ,]+/) : []).reduce((result, identifier) => {
      result[identifier.toLowerCase()] = true;
      return result;
    }, dict);
  }
  bool(attrName) {
    return this[attrName] === "YES";
  }
  decimalResolution(attrName) {
    const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
    if (res === null) {
      return void 0;
    }
    return {
      width: parseInt(res[1], 10),
      height: parseInt(res[2], 10)
    };
  }
  static parseAttrList(input, parsed) {
    let match;
    const attrs = {};
    const quote = '"';
    ATTR_LIST_REGEX.lastIndex = 0;
    while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
      const name = match[1].trim();
      let value = match[2];
      const quotedString = value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1;
      let hexadecimalSequence = false;
      if (quotedString) {
        value = value.slice(1, -1);
      } else {
        switch (name) {
          case "IV":
          case "SCTE35-CMD":
          case "SCTE35-IN":
          case "SCTE35-OUT":
            hexadecimalSequence = true;
        }
      }
      if (parsed && (quotedString || hexadecimalSequence)) {
        {
          value = substituteVariables(parsed, value);
        }
      } else if (!hexadecimalSequence && !quotedString) {
        switch (name) {
          case "CLOSED-CAPTIONS":
            if (value === "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":
            logger.warn(`${input}: attribute ${name} is missing quotes`);
        }
      }
      attrs[name] = value;
    }
    return attrs;
  }
};
var CLASS_INTERSTITIAL = "com.apple.hls.interstitial";
function isDateRangeCueAttribute(attrName) {
  return attrName !== "ID" && attrName !== "CLASS" && attrName !== "CUE" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
}
function isSCTE35Attribute(attrName) {
  return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN" || attrName === "SCTE35-CMD";
}
var DateRange = class {
  constructor(dateRangeAttr, dateRangeWithSameId, tagCount = 0) {
    var _dateRangeWithSameId$;
    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 = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagAnchor) || null;
    this.tagOrder = (_dateRangeWithSameId$ = dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagOrder) != null ? _dateRangeWithSameId$ : tagCount;
    if (dateRangeWithSameId) {
      const previousAttr = dateRangeWithSameId.attr;
      for (const key in previousAttr) {
        if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
          logger.warn(`DATERANGE tag attribute: "${key}" does not match for tags with ID: "${dateRangeAttr.ID}"`);
          this._badValueForSameId = key;
          break;
        }
      }
      dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
    }
    this.attr = dateRangeAttr;
    if (dateRangeWithSameId) {
      this._startDate = dateRangeWithSameId._startDate;
      this._cue = dateRangeWithSameId._cue;
      this._endDate = dateRangeWithSameId._endDate;
      this._dateAtEnd = dateRangeWithSameId._dateAtEnd;
    } else {
      this._startDate = new Date(dateRangeAttr["START-DATE"]);
    }
    if ("END-DATE" in this.attr) {
      const endDate = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.endDate) || new Date(this.attr["END-DATE"]);
      if (isFiniteNumber(endDate.getTime())) {
        this._endDate = endDate;
      }
    }
  }
  get id() {
    return this.attr.ID;
  }
  get class() {
    return this.attr.CLASS;
  }
  get cue() {
    const _cue = this._cue;
    if (_cue === void 0) {
      return this._cue = this.attr.enumeratedStringList(this.attr.CUE ? "CUE" : "X-CUE", {
        pre: false,
        post: false,
        once: false
      });
    }
    return _cue;
  }
  get startTime() {
    const {
      tagAnchor
    } = this;
    if (tagAnchor === null || tagAnchor.programDateTime === null) {
      logger.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${tagAnchor}`);
      return NaN;
    }
    return tagAnchor.start + (this.startDate.getTime() - tagAnchor.programDateTime) / 1e3;
  }
  get startDate() {
    return this._startDate;
  }
  get endDate() {
    const dateAtEnd = this._endDate || this._dateAtEnd;
    if (dateAtEnd) {
      return dateAtEnd;
    }
    const duration5 = this.duration;
    if (duration5 !== null) {
      return this._dateAtEnd = new Date(this._startDate.getTime() + duration5 * 1e3);
    }
    return null;
  }
  get duration() {
    if ("DURATION" in this.attr) {
      const duration5 = this.attr.decimalFloatingPoint("DURATION");
      if (isFiniteNumber(duration5)) {
        return duration5;
      }
    } else if (this._endDate) {
      return (this._endDate.getTime() - this._startDate.getTime()) / 1e3;
    }
    return null;
  }
  get plannedDuration() {
    if ("PLANNED-DURATION" in this.attr) {
      return this.attr.decimalFloatingPoint("PLANNED-DURATION");
    }
    return null;
  }
  get endOnNext() {
    return this.attr.bool("END-ON-NEXT");
  }
  get isInterstitial() {
    return this.class === CLASS_INTERSTITIAL;
  }
  get isValid() {
    return !!this.id && !this._badValueForSameId && isFiniteNumber(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);
  }
};
var DEFAULT_TARGET_DURATION = 10;
var LevelDetails = class {
  constructor(baseUrl) {
    this.PTSKnown = false;
    this.alignedSliding = false;
    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 = true;
    this.requestScheduled = -1;
    this.ageHeader = 0;
    this.advancedDateTime = void 0;
    this.updated = true;
    this.advanced = true;
    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 = false;
    this.canSkipUntil = 0;
    this.canSkipDateRanges = false;
    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 = false;
    this.appliedTimelineOffset = void 0;
    this.fragments = [];
    this.encryptedFragments = [];
    this.dateRanges = {};
    this.url = baseUrl;
  }
  reloaded(previous) {
    if (!previous) {
      this.advanced = true;
      this.updated = true;
      return;
    }
    const partSnDiff = this.lastPartSn - previous.lastPartSn;
    const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
    this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
    this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
    if (this.updated || this.advanced) {
      this.misses = Math.floor(previous.misses * 0.6);
    } else {
      this.misses = previous.misses + 1;
    }
  }
  get hasProgramDateTime() {
    if (this.fragments.length) {
      return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
    }
    return false;
  }
  get levelTargetDuration() {
    return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  }
  get drift() {
    const runTime = this.driftEndTime - this.driftStartTime;
    if (runTime > 0) {
      const runDuration = this.driftEnd - this.driftStart;
      return runDuration * 1e3 / runTime;
    }
    return 1;
  }
  get edge() {
    return this.partEnd || this.fragmentEnd;
  }
  get partEnd() {
    var _this$partList;
    if ((_this$partList = this.partList) != null && _this$partList.length) {
      return this.partList[this.partList.length - 1].end;
    }
    return this.fragmentEnd;
  }
  get fragmentEnd() {
    var _this$fragments;
    if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
      return this.fragments[this.fragments.length - 1].end;
    }
    return 0;
  }
  get fragmentStart() {
    var _this$fragments2;
    if ((_this$fragments2 = this.fragments) != null && _this$fragments2.length) {
      return this.fragments[0].start;
    }
    return 0;
  }
  get age() {
    if (this.advancedDateTime) {
      return Math.max(Date.now() - this.advancedDateTime, 0) / 1e3;
    }
    return 0;
  }
  get lastPartIndex() {
    var _this$partList2;
    if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
      return this.partList[this.partList.length - 1].index;
    }
    return -1;
  }
  get maxPartIndex() {
    const partList = this.partList;
    if (partList) {
      const lastIndex = this.lastPartIndex;
      if (lastIndex !== -1) {
        for (let i = partList.length; i--; ) {
          if (partList[i].index > lastIndex) {
            return partList[i].index;
          }
        }
        return lastIndex;
      }
    }
    return 0;
  }
  get lastPartSn() {
    var _this$partList3;
    if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
      return this.partList[this.partList.length - 1].fragment.sn;
    }
    return this.endSN;
  }
  get expired() {
    if (this.live && this.age && this.misses < 3) {
      const playlistWindowDuration = this.partEnd - this.fragmentStart;
      return this.age > Math.max(playlistWindowDuration, this.totalduration) + this.levelTargetDuration;
    }
    return false;
  }
};
function isFullSegmentEncryption(method) {
  return method === "AES-128" || method === "AES-256" || method === "AES-256-CTR";
}
function getAesModeFromFullSegmentMethod(method) {
  switch (method) {
    case "AES-128":
    case "AES-256":
      return DecrypterAesMode.cbc;
    case "AES-256-CTR":
      return DecrypterAesMode.ctr;
    default:
      throw new Error(`invalid full segment method ${method}`);
  }
}
function base64Decode(base64encodedStr) {
  return Uint8Array.from(atob(base64encodedStr), (c) => c.charCodeAt(0));
}
function strToUtf8array(str) {
  return Uint8Array.from(unescape(encodeURIComponent(str)), (c) => c.charCodeAt(0));
}
function getKeyIdBytes(str) {
  const keyIdbytes = strToUtf8array(str).subarray(0, 16);
  const paddedkeyIdbytes = new Uint8Array(16);
  paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);
  return paddedkeyIdbytes;
}
function changeEndianness(keyId) {
  const swap = function swap2(array, from3, to) {
    const cur = array[from3];
    array[from3] = array[to];
    array[to] = cur;
  };
  swap(keyId, 0, 3);
  swap(keyId, 1, 2);
  swap(keyId, 4, 5);
  swap(keyId, 6, 7);
}
function convertDataUriToArrayBytes(uri) {
  const colonsplit = uri.split(":");
  let keydata = null;
  if (colonsplit[0] === "data" && colonsplit.length === 2) {
    const semicolonsplit = colonsplit[1].split(";");
    const commasplit = semicolonsplit[semicolonsplit.length - 1].split(",");
    if (commasplit.length === 2) {
      const isbase64 = commasplit[0] === "base64";
      const data = commasplit[1];
      if (isbase64) {
        semicolonsplit.splice(-1, 1);
        keydata = base64Decode(data);
      } else {
        keydata = getKeyIdBytes(data);
      }
    }
  }
  return keydata;
}
var optionalSelf = typeof self !== "undefined" ? self : void 0;
var KeySystems = {
  CLEARKEY: "org.w3.clearkey",
  FAIRPLAY: "com.apple.fps",
  PLAYREADY: "com.microsoft.playready",
  WIDEVINE: "com.widevine.alpha"
};
var KeySystemFormats = {
  CLEARKEY: "org.w3.clearkey",
  FAIRPLAY: "com.apple.streamingkeydelivery",
  PLAYREADY: "com.microsoft.playready",
  WIDEVINE: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
};
function keySystemFormatToKeySystemDomain(format2) {
  switch (format2) {
    case KeySystemFormats.FAIRPLAY:
      return KeySystems.FAIRPLAY;
    case KeySystemFormats.PLAYREADY:
      return KeySystems.PLAYREADY;
    case KeySystemFormats.WIDEVINE:
      return KeySystems.WIDEVINE;
    case KeySystemFormats.CLEARKEY:
      return KeySystems.CLEARKEY;
  }
}
var KeySystemIds = {
  CENC: "1077efecc0b24d02ace33c1e52e2fb4b",
  CLEARKEY: "e2719d58a985b3c9781ab030af78d30e",
  PLAYREADY: "9a04f07998404286ab92e65be0885f95",
  WIDEVINE: "edef8ba979d64acea3c827dcd51d21ed"
};
function keySystemIdToKeySystemDomain(systemId) {
  if (systemId === KeySystemIds.WIDEVINE) {
    return KeySystems.WIDEVINE;
  } else if (systemId === KeySystemIds.PLAYREADY) {
    return KeySystems.PLAYREADY;
  } else if (systemId === KeySystemIds.CENC || systemId === KeySystemIds.CLEARKEY) {
    return KeySystems.CLEARKEY;
  }
}
function keySystemDomainToKeySystemFormat(keySystem) {
  switch (keySystem) {
    case KeySystems.FAIRPLAY:
      return KeySystemFormats.FAIRPLAY;
    case KeySystems.PLAYREADY:
      return KeySystemFormats.PLAYREADY;
    case KeySystems.WIDEVINE:
      return KeySystemFormats.WIDEVINE;
    case KeySystems.CLEARKEY:
      return KeySystemFormats.CLEARKEY;
  }
}
function getKeySystemsForConfig(config) {
  const {
    drmSystems,
    widevineLicenseUrl
  } = config;
  const keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter((keySystem) => !!drmSystems[keySystem]) : [];
  if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {
    keySystemsToAttempt.push(KeySystems.WIDEVINE);
  }
  return keySystemsToAttempt;
}
var requestMediaKeySystemAccess = function(_optionalSelf$navigat) {
  if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) {
    return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
  } else {
    return null;
  }
}();
function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
  let initDataTypes;
  switch (keySystem) {
    case KeySystems.FAIRPLAY:
      initDataTypes = ["cenc", "sinf"];
      break;
    case KeySystems.WIDEVINE:
    case KeySystems.PLAYREADY:
      initDataTypes = ["cenc"];
      break;
    case KeySystems.CLEARKEY:
      initDataTypes = ["cenc", "keyids"];
      break;
    default:
      throw new Error(`Unknown key-system: ${keySystem}`);
  }
  return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions);
}
function createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) {
  const baseConfig = {
    initDataTypes,
    persistentState: drmSystemOptions.persistentState || "optional",
    distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || "optional",
    sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || "temporary"],
    audioCapabilities: audioCodecs.map((codec) => ({
      contentType: `audio/mp4; codecs=${codec}`,
      robustness: drmSystemOptions.audioRobustness || "",
      encryptionScheme: drmSystemOptions.audioEncryptionScheme || null
    })),
    videoCapabilities: videoCodecs.map((codec) => ({
      contentType: `video/mp4; codecs=${codec}`,
      robustness: drmSystemOptions.videoRobustness || "",
      encryptionScheme: drmSystemOptions.videoEncryptionScheme || null
    }))
  };
  return [baseConfig];
}
function isPersistentSessionType(drmSystemOptions) {
  var _drmSystemOptions$ses;
  return drmSystemOptions.sessionType === "persistent-license" || !!((_drmSystemOptions$ses = drmSystemOptions.sessionTypes) != null && _drmSystemOptions$ses.some((type2) => type2 === "persistent-license"));
}
function parsePlayReadyWRM(keyBytes) {
  const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);
  const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));
  const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf("<"), keyByteStr.length);
  const parser6 = new DOMParser();
  const xmlDoc = parser6.parseFromString(xmlKeyBytes, "text/xml");
  const keyData = xmlDoc.getElementsByTagName("KID")[0];
  if (keyData) {
    const keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute("VALUE");
    if (keyId) {
      const keyIdArray = base64Decode(keyId).subarray(0, 16);
      changeEndianness(keyIdArray);
      return keyIdArray;
    }
  }
  return null;
}
var keyUriToKeyIdMap = {};
var LevelKey = class _LevelKey {
  static clearKeyUriToKeyIdMap() {
    keyUriToKeyIdMap = {};
  }
  constructor(method, uri, format2, formatversions = [1], iv = null) {
    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 = method;
    this.uri = uri;
    this.keyFormat = format2;
    this.keyFormatVersions = formatversions;
    this.iv = iv;
    this.encrypted = method ? method !== "NONE" : false;
    this.isCommonEncryption = this.encrypted && !isFullSegmentEncryption(method);
  }
  isSupported() {
    if (this.method) {
      if (isFullSegmentEncryption(this.method) || this.method === "NONE") {
        return true;
      }
      if (this.keyFormat === "identity") {
        return this.method === "SAMPLE-AES";
      } else {
        switch (this.keyFormat) {
          case KeySystemFormats.FAIRPLAY:
          case KeySystemFormats.WIDEVINE:
          case KeySystemFormats.PLAYREADY:
          case KeySystemFormats.CLEARKEY:
            return ["ISO-23001-7", "SAMPLE-AES", "SAMPLE-AES-CENC", "SAMPLE-AES-CTR"].indexOf(this.method) !== -1;
        }
      }
    }
    return false;
  }
  getDecryptData(sn) {
    if (!this.encrypted || !this.uri) {
      return null;
    }
    if (isFullSegmentEncryption(this.method) && this.uri && !this.iv) {
      if (typeof sn !== "number") {
        logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`);
        sn = 0;
      }
      const iv = createInitializationVector(sn);
      const decryptdata = new _LevelKey(this.method, this.uri, "identity", this.keyFormatVersions, iv);
      return decryptdata;
    }
    const keyBytes = convertDataUriToArrayBytes(this.uri);
    if (keyBytes) {
      switch (this.keyFormat) {
        case KeySystemFormats.WIDEVINE:
          this.pssh = keyBytes;
          if (keyBytes.length >= 22) {
            this.keyId = keyBytes.subarray(keyBytes.length - 22, keyBytes.length - 6);
          }
          break;
        case KeySystemFormats.PLAYREADY: {
          const PlayReadyKeySystemUUID = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]);
          this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);
          this.keyId = parsePlayReadyWRM(keyBytes);
          break;
        }
        default: {
          let keydata = keyBytes.subarray(0, 16);
          if (keydata.length !== 16) {
            const padded = new Uint8Array(16);
            padded.set(keydata, 16 - keydata.length);
            keydata = padded;
          }
          this.keyId = keydata;
          break;
        }
      }
    }
    if (!this.keyId || this.keyId.byteLength !== 16) {
      let keyId = keyUriToKeyIdMap[this.uri];
      if (!keyId) {
        const val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;
        keyId = new Uint8Array(16);
        const dv = new DataView(keyId.buffer, 12, 4);
        dv.setUint32(0, val);
        keyUriToKeyIdMap[this.uri] = keyId;
      }
      this.keyId = keyId;
    }
    return this;
  }
};
function createInitializationVector(segmentNumber) {
  const uint8View = new Uint8Array(16);
  for (let i = 12; i < 16; i++) {
    uint8View[i] = segmentNumber >> 8 * (15 - i) & 255;
  }
  return uint8View;
}
var MASTER_PLAYLIST_REGEX = /#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;
var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
var IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m;
var LEVEL_PLAYLIST_REGEX_FAST = 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");
var LEVEL_PLAYLIST_REGEX_SLOW = 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("|"));
var M3U8Parser = class _M3U8Parser {
  static findGroup(groups, mediaGroupId) {
    for (let i = 0; i < groups.length; i++) {
      const group = groups[i];
      if (group.id === mediaGroupId) {
        return group;
      }
    }
  }
  static resolve(url, baseUrl) {
    return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
      alwaysNormalize: true
    });
  }
  static isMediaPlaylist(str) {
    return IS_MEDIA_PLAYLIST.test(str);
  }
  static parseMasterPlaylist(string, baseurl) {
    const hasVariableRefs = hasVariableReferences(string);
    const parsed = {
      contentSteering: null,
      levels: [],
      playlistParsingError: null,
      sessionData: null,
      sessionKeys: null,
      startTimeOffset: null,
      variableList: null,
      hasVariableRefs
    };
    const levelsWithKnownCodecs = [];
    MASTER_PLAYLIST_REGEX.lastIndex = 0;
    let result;
    while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
      if (result[1]) {
        var _level$unknownCodecs;
        const attrs = new AttrList(result[1], parsed);
        const uri = substituteVariables(parsed, result[2]);
        const level = {
          attrs,
          bitrate: attrs.decimalInteger("BANDWIDTH") || attrs.decimalInteger("AVERAGE-BANDWIDTH"),
          name: attrs.NAME,
          url: _M3U8Parser.resolve(uri, baseurl)
        };
        const resolution = attrs.decimalResolution("RESOLUTION");
        if (resolution) {
          level.width = resolution.width;
          level.height = resolution.height;
        }
        setCodecs(attrs.CODECS, level);
        const supplementalCodecs = attrs["SUPPLEMENTAL-CODECS"];
        if (supplementalCodecs) {
          level.supplemental = {};
          setCodecs(supplementalCodecs, level.supplemental);
        }
        if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
          levelsWithKnownCodecs.push(level);
        }
        parsed.levels.push(level);
      } else if (result[3]) {
        const tag = result[3];
        const attributes = result[4];
        switch (tag) {
          case "SESSION-DATA": {
            const sessionAttrs = new AttrList(attributes, parsed);
            const dataId = sessionAttrs["DATA-ID"];
            if (dataId) {
              if (parsed.sessionData === null) {
                parsed.sessionData = {};
              }
              parsed.sessionData[dataId] = sessionAttrs;
            }
            break;
          }
          case "SESSION-KEY": {
            const sessionKey = parseKey(attributes, baseurl, parsed);
            if (sessionKey.encrypted && sessionKey.isSupported()) {
              if (parsed.sessionKeys === null) {
                parsed.sessionKeys = [];
              }
              parsed.sessionKeys.push(sessionKey);
            } else {
              logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`);
            }
            break;
          }
          case "DEFINE": {
            {
              const variableAttributes = new AttrList(attributes, parsed);
              addVariableDefinition(parsed, variableAttributes, baseurl);
            }
            break;
          }
          case "CONTENT-STEERING": {
            const contentSteeringAttributes = new AttrList(attributes, parsed);
            parsed.contentSteering = {
              uri: _M3U8Parser.resolve(contentSteeringAttributes["SERVER-URI"], baseurl),
              pathwayId: contentSteeringAttributes["PATHWAY-ID"] || "."
            };
            break;
          }
          case "START": {
            parsed.startTimeOffset = parseStartTimeOffset(attributes);
            break;
          }
        }
      }
    }
    const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
    parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
    if (parsed.levels.length === 0) {
      parsed.playlistParsingError = new Error("no levels found in manifest");
    }
    return parsed;
  }
  static parseMasterPlaylistMedia(string, baseurl, parsed) {
    let result;
    const results = {};
    const levels = parsed.levels;
    const groupsByType = {
      AUDIO: levels.map((level) => ({
        id: level.attrs.AUDIO,
        audioCodec: level.audioCodec
      })),
      SUBTITLES: levels.map((level) => ({
        id: level.attrs.SUBTITLES,
        textCodec: level.textCodec
      })),
      "CLOSED-CAPTIONS": []
    };
    let id = 0;
    MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
    while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
      const attrs = new AttrList(result[1], parsed);
      const type2 = attrs.TYPE;
      if (type2) {
        const groups = groupsByType[type2];
        const medias = results[type2] || [];
        results[type2] = medias;
        const lang = attrs.LANGUAGE;
        const assocLang = attrs["ASSOC-LANGUAGE"];
        const channels = attrs.CHANNELS;
        const characteristics = attrs.CHARACTERISTICS;
        const instreamId = attrs["INSTREAM-ID"];
        const media = {
          attrs,
          bitrate: 0,
          id: id++,
          groupId: attrs["GROUP-ID"] || "",
          name: attrs.NAME || lang || "",
          type: type2,
          default: attrs.bool("DEFAULT"),
          autoselect: attrs.bool("AUTOSELECT"),
          forced: attrs.bool("FORCED"),
          lang,
          url: attrs.URI ? _M3U8Parser.resolve(attrs.URI, baseurl) : ""
        };
        if (assocLang) {
          media.assocLang = assocLang;
        }
        if (channels) {
          media.channels = channels;
        }
        if (characteristics) {
          media.characteristics = characteristics;
        }
        if (instreamId) {
          media.instreamId = instreamId;
        }
        if (groups != null && groups.length) {
          const groupCodec = _M3U8Parser.findGroup(groups, media.groupId) || groups[0];
          assignCodec(media, groupCodec, "audioCodec");
          assignCodec(media, groupCodec, "textCodec");
        }
        medias.push(media);
      }
    }
    return results;
  }
  static parseLevelPlaylist(string, baseurl, id, type2, levelUrlId, multivariantVariableList) {
    var _LEVEL_PLAYLIST_REGEX;
    const base = {
      url: baseurl
    };
    const level = new LevelDetails(baseurl);
    const fragments = level.fragments;
    const programDateTimes = [];
    let currentInitSegment = null;
    let currentSN = 0;
    let currentPart = 0;
    let totalduration = 0;
    let discontinuityCounter = 0;
    let currentBitrate = 0;
    let prevFrag = null;
    let frag = new Fragment(type2, base);
    let result;
    let i;
    let levelkeys;
    let firstPdtIndex = -1;
    let createNextFrag = false;
    let nextByteRange = null;
    let serverControlAttrs;
    LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
    level.m3u8 = string;
    level.hasVariableRefs = hasVariableReferences(string);
    if (((_LEVEL_PLAYLIST_REGEX = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) == null ? void 0 : _LEVEL_PLAYLIST_REGEX[0]) !== "#EXTM3U") {
      level.playlistParsingError = new Error("Missing format identifier #EXTM3U");
      return level;
    }
    while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
      if (createNextFrag) {
        createNextFrag = false;
        frag = new Fragment(type2, base);
        frag.playlistOffset = totalduration;
        frag.start = totalduration;
        frag.sn = currentSN;
        frag.cc = discontinuityCounter;
        if (currentBitrate) {
          frag.bitrate = currentBitrate;
        }
        frag.level = id;
        if (currentInitSegment) {
          frag.initSegment = currentInitSegment;
          if (currentInitSegment.rawProgramDateTime) {
            frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
            currentInitSegment.rawProgramDateTime = null;
          }
          if (nextByteRange) {
            frag.setByteRange(nextByteRange);
            nextByteRange = null;
          }
        }
      }
      const duration5 = result[1];
      if (duration5) {
        frag.duration = parseFloat(duration5);
        const title = (" " + result[2]).slice(1);
        frag.title = title || null;
        frag.tagList.push(title ? ["INF", duration5, title] : ["INF", duration5]);
      } else if (result[3]) {
        if (isFiniteNumber(frag.duration)) {
          frag.playlistOffset = totalduration;
          frag.start = totalduration;
          if (levelkeys) {
            setFragLevelKeys(frag, levelkeys, level);
          }
          frag.sn = currentSN;
          frag.level = id;
          frag.cc = discontinuityCounter;
          fragments.push(frag);
          const uri = (" " + result[3]).slice(1);
          frag.relurl = substituteVariables(level, uri);
          assignProgramDateTime(frag, prevFrag, programDateTimes);
          prevFrag = frag;
          totalduration += frag.duration;
          currentSN++;
          currentPart = 0;
          createNextFrag = true;
        }
      } else {
        result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
        if (!result) {
          logger.warn("No matches on slow regex match for level playlist!");
          continue;
        }
        for (i = 1; i < result.length; i++) {
          if (result[i] !== void 0) {
            break;
          }
        }
        const tag = (" " + result[i]).slice(1);
        const value1 = (" " + result[i + 1]).slice(1);
        const value2 = result[i + 2] ? (" " + result[i + 2]).slice(1) : null;
        switch (tag) {
          case "BYTERANGE":
            if (prevFrag) {
              frag.setByteRange(value1, prevFrag);
            } else {
              frag.setByteRange(value1);
            }
            break;
          case "PROGRAM-DATE-TIME":
            frag.rawProgramDateTime = value1;
            frag.tagList.push(["PROGRAM-DATE-TIME", value1]);
            if (firstPdtIndex === -1) {
              firstPdtIndex = fragments.length;
            }
            break;
          case "PLAYLIST-TYPE":
            if (level.type) {
              assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
            }
            level.type = value1.toUpperCase();
            break;
          case "MEDIA-SEQUENCE":
            if (level.startSN !== 0) {
              assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
            } else if (fragments.length > 0) {
              assignMustAppearBeforeSegmentsError(level, tag, result);
            }
            currentSN = level.startSN = parseInt(value1);
            break;
          case "SKIP": {
            if (level.skippedSegments) {
              assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
            }
            const skipAttrs = new AttrList(value1, level);
            const skippedSegments = skipAttrs.decimalInteger("SKIPPED-SEGMENTS");
            if (isFiniteNumber(skippedSegments)) {
              level.skippedSegments += skippedSegments;
              for (let _i = skippedSegments; _i--; ) {
                fragments.push(null);
              }
              currentSN += skippedSegments;
            }
            const recentlyRemovedDateranges = skipAttrs.enumeratedString("RECENTLY-REMOVED-DATERANGES");
            if (recentlyRemovedDateranges) {
              level.recentlyRemovedDateranges = (level.recentlyRemovedDateranges || []).concat(recentlyRemovedDateranges.split("	"));
            }
            break;
          }
          case "TARGETDURATION":
            if (level.targetduration !== 0) {
              assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
            }
            level.targetduration = Math.max(parseInt(value1), 1);
            break;
          case "VERSION":
            if (level.version !== null) {
              assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
            }
            level.version = parseInt(value1);
            break;
          case "INDEPENDENT-SEGMENTS":
            break;
          case "ENDLIST":
            if (!level.live) {
              assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
            }
            level.live = false;
            break;
          case "#":
            if (value1 || value2) {
              frag.tagList.push(value2 ? [value1, value2] : [value1]);
            }
            break;
          case "DISCONTINUITY":
            discontinuityCounter++;
            frag.tagList.push(["DIS"]);
            break;
          case "GAP":
            frag.gap = true;
            frag.tagList.push([tag]);
            break;
          case "BITRATE":
            frag.tagList.push([tag, value1]);
            currentBitrate = parseInt(value1) * 1e3;
            if (isFiniteNumber(currentBitrate)) {
              frag.bitrate = currentBitrate;
            } else {
              currentBitrate = 0;
            }
            break;
          case "DATERANGE": {
            const dateRangeAttr = new AttrList(value1, level);
            const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID], level.dateRangeTagCount);
            level.dateRangeTagCount++;
            if (dateRange.isValid || level.skippedSegments) {
              level.dateRanges[dateRange.id] = dateRange;
            } else {
              logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`);
            }
            frag.tagList.push(["EXT-X-DATERANGE", value1]);
            break;
          }
          case "DEFINE": {
            {
              const variableAttributes = new AttrList(value1, level);
              if ("IMPORT" in variableAttributes) {
                importVariableDefinition(level, variableAttributes, multivariantVariableList);
              } else {
                addVariableDefinition(level, variableAttributes, baseurl);
              }
            }
            break;
          }
          case "DISCONTINUITY-SEQUENCE":
            if (level.startCC !== 0) {
              assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
            } else if (fragments.length > 0) {
              assignMustAppearBeforeSegmentsError(level, tag, result);
            }
            level.startCC = discontinuityCounter = parseInt(value1);
            break;
          case "KEY": {
            const levelKey = parseKey(value1, baseurl, level);
            if (levelKey.isSupported()) {
              if (levelKey.method === "NONE") {
                levelkeys = void 0;
                break;
              }
              if (!levelkeys) {
                levelkeys = {};
              }
              if (levelkeys[levelKey.keyFormat]) {
                levelkeys = _extends({}, levelkeys);
              }
              levelkeys[levelKey.keyFormat] = levelKey;
            } else {
              logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${value1}"`);
            }
            break;
          }
          case "START":
            level.startTimeOffset = parseStartTimeOffset(value1);
            break;
          case "MAP": {
            const mapAttrs = new AttrList(value1, level);
            if (frag.duration) {
              const init = new Fragment(type2, base);
              setInitSegment(init, mapAttrs, id, levelkeys);
              currentInitSegment = init;
              frag.initSegment = currentInitSegment;
              if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
                frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
              }
            } else {
              const end = frag.byteRangeEndOffset;
              if (end) {
                const start2 = frag.byteRangeStartOffset;
                nextByteRange = `${end - start2}@${start2}`;
              } else {
                nextByteRange = null;
              }
              setInitSegment(frag, mapAttrs, id, levelkeys);
              currentInitSegment = frag;
              createNextFrag = true;
            }
            currentInitSegment.cc = discontinuityCounter;
            break;
          }
          case "SERVER-CONTROL": {
            if (serverControlAttrs) {
              assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
            }
            serverControlAttrs = new AttrList(value1);
            level.canBlockReload = serverControlAttrs.bool("CAN-BLOCK-RELOAD");
            level.canSkipUntil = serverControlAttrs.optionalFloat("CAN-SKIP-UNTIL", 0);
            level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool("CAN-SKIP-DATERANGES");
            level.partHoldBack = serverControlAttrs.optionalFloat("PART-HOLD-BACK", 0);
            level.holdBack = serverControlAttrs.optionalFloat("HOLD-BACK", 0);
            break;
          }
          case "PART-INF": {
            if (level.partTarget) {
              assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
            }
            const partInfAttrs = new AttrList(value1);
            level.partTarget = partInfAttrs.decimalFloatingPoint("PART-TARGET");
            break;
          }
          case "PART": {
            let partList = level.partList;
            if (!partList) {
              partList = level.partList = [];
            }
            const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : void 0;
            const index = currentPart++;
            const partAttrs = new AttrList(value1, level);
            const part = new Part(partAttrs, frag, base, index, previousFragmentPart);
            partList.push(part);
            frag.duration += part.duration;
            break;
          }
          case "PRELOAD-HINT": {
            const preloadHintAttrs = new AttrList(value1, level);
            level.preloadHint = preloadHintAttrs;
            break;
          }
          case "RENDITION-REPORT": {
            const renditionReportAttrs = new AttrList(value1, level);
            level.renditionReports = level.renditionReports || [];
            level.renditionReports.push(renditionReportAttrs);
            break;
          }
          default:
            logger.warn(`line parsed but not handled: ${result}`);
            break;
        }
      }
    }
    if (prevFrag && !prevFrag.relurl) {
      fragments.pop();
      totalduration -= prevFrag.duration;
      if (level.partList) {
        level.fragmentHint = prevFrag;
      }
    } else if (level.partList) {
      assignProgramDateTime(frag, prevFrag, programDateTimes);
      frag.cc = discontinuityCounter;
      level.fragmentHint = frag;
      if (levelkeys) {
        setFragLevelKeys(frag, levelkeys, level);
      }
    }
    if (!level.targetduration) {
      level.playlistParsingError = new Error(`#EXT-X-TARGETDURATION is required`);
    }
    const fragmentLength = fragments.length;
    const firstFragment = fragments[0];
    const lastFragment = fragments[fragmentLength - 1];
    totalduration += level.skippedSegments * level.targetduration;
    if (totalduration > 0 && fragmentLength && lastFragment) {
      level.averagetargetduration = totalduration / fragmentLength;
      const lastSn = lastFragment.sn;
      level.endSN = lastSn !== "initSegment" ? lastSn : 0;
      if (!level.live) {
        lastFragment.endList = true;
      }
      if (firstFragment && level.startCC === void 0) {
        level.startCC = firstFragment.cc;
      }
      if (firstPdtIndex > 0) {
        backfillProgramDateTimes(fragments, firstPdtIndex);
        if (firstFragment) {
          programDateTimes.unshift(firstFragment);
        }
      }
    } else {
      level.endSN = 0;
      level.startCC = 0;
    }
    if (level.fragmentHint) {
      totalduration += level.fragmentHint.duration;
    }
    level.totalduration = totalduration;
    if (programDateTimes.length && level.dateRangeTagCount && firstFragment) {
      mapDateRanges(programDateTimes, level);
    }
    level.endCC = discontinuityCounter;
    return level;
  }
};
function mapDateRanges(programDateTimes, details) {
  const programDateTimeCount = programDateTimes.length;
  const lastProgramDateTime = programDateTimes[programDateTimeCount - 1];
  const playlistEnd3 = details.live ? Infinity : details.totalduration;
  const dateRangeIds = Object.keys(details.dateRanges);
  for (let i = dateRangeIds.length; i--; ) {
    const dateRange = details.dateRanges[dateRangeIds[i]];
    const startDateTime = dateRange.startDate.getTime();
    dateRange.tagAnchor = lastProgramDateTime.ref;
    for (let j = programDateTimeCount; j--; ) {
      const fragIndex = findFragmentWithStartDate(details, startDateTime, programDateTimes, j, playlistEnd3);
      if (fragIndex !== -1) {
        dateRange.tagAnchor = details.fragments[fragIndex].ref;
        break;
      }
    }
  }
}
function findFragmentWithStartDate(details, startDateTime, programDateTimes, index, endTime) {
  const pdtFragment = programDateTimes[index];
  if (pdtFragment) {
    const pdtStart = pdtFragment.programDateTime;
    if (startDateTime >= pdtStart || index === 0) {
      var _programDateTimes;
      const durationBetweenPdt = (((_programDateTimes = programDateTimes[index + 1]) == null ? void 0 : _programDateTimes.start) || endTime) - pdtFragment.start;
      if (startDateTime <= pdtStart + durationBetweenPdt * 1e3) {
        const startIndex = programDateTimes[index].sn - details.startSN;
        const fragments = details.fragments;
        if (fragments.length > programDateTimes.length) {
          const endSegment = programDateTimes[index + 1] || fragments[fragments.length - 1];
          const endIndex = endSegment.sn - details.startSN;
          for (let i = endIndex; i > startIndex; i--) {
            const fragStartDateTime = fragments[i].programDateTime;
            if (startDateTime >= fragStartDateTime && startDateTime < fragStartDateTime + fragments[i].duration * 1e3) {
              return i;
            }
          }
        }
        return startIndex;
      }
    }
  }
  return -1;
}
function parseKey(keyTagAttributes, baseurl, parsed) {
  var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  const keyAttrs = new AttrList(keyTagAttributes, parsed);
  const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : "";
  const decrypturi = keyAttrs.URI;
  const decryptiv = keyAttrs.hexadecimalInteger("IV");
  const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : "identity";
  if (decrypturi && keyAttrs.IV && !decryptiv) {
    logger.error(`Invalid IV: ${keyAttrs.IV}`);
  }
  const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : "";
  const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : "1").split("/").map(Number).filter(Number.isFinite);
  return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv);
}
function parseStartTimeOffset(startAttributes) {
  const startAttrs = new AttrList(startAttributes);
  const startTimeOffset = startAttrs.decimalFloatingPoint("TIME-OFFSET");
  if (isFiniteNumber(startTimeOffset)) {
    return startTimeOffset;
  }
  return null;
}
function setCodecs(codecsAttributeValue, level) {
  let codecs = (codecsAttributeValue || "").split(/[ ,]+/).filter((c) => c);
  ["video", "audio", "text"].forEach((type2) => {
    const filtered = codecs.filter((codec) => isCodecType(codec, type2));
    if (filtered.length) {
      level[`${type2}Codec`] = filtered.map((c) => c.split("/")[0]).join(",");
      codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);
    }
  });
  level.unknownCodecs = codecs;
}
function assignCodec(media, groupItem, codecProperty) {
  const codecValue = groupItem[codecProperty];
  if (codecValue) {
    media[codecProperty] = codecValue;
  }
}
function backfillProgramDateTimes(fragments, firstPdtIndex) {
  let fragPrev = fragments[firstPdtIndex];
  for (let i = firstPdtIndex; i--; ) {
    const frag = fragments[i];
    if (!frag) {
      return;
    }
    frag.programDateTime = fragPrev.programDateTime - frag.duration * 1e3;
    fragPrev = frag;
  }
}
function assignProgramDateTime(frag, prevFrag, programDateTimes) {
  if (frag.rawProgramDateTime) {
    programDateTimes.push(frag);
  } else if (prevFrag != null && prevFrag.programDateTime) {
    frag.programDateTime = prevFrag.endProgramDateTime;
  }
}
function setInitSegment(frag, mapAttrs, id, levelkeys) {
  frag.relurl = mapAttrs.URI;
  if (mapAttrs.BYTERANGE) {
    frag.setByteRange(mapAttrs.BYTERANGE);
  }
  frag.level = id;
  frag.sn = "initSegment";
  if (levelkeys) {
    frag.levelkeys = levelkeys;
  }
  frag.initSegment = null;
}
function setFragLevelKeys(frag, levelkeys, level) {
  frag.levelkeys = levelkeys;
  const {
    encryptedFragments
  } = level;
  if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some((format2) => levelkeys[format2].isCommonEncryption)) {
    encryptedFragments.push(frag);
  }
}
function assignMultipleMediaPlaylistTagOccuranceError(level, tag, result) {
  level.playlistParsingError = new Error(`#EXT-X-${tag} must not appear more than once (${result[0]})`);
}
function assignMustAppearBeforeSegmentsError(level, tag, result) {
  level.playlistParsingError = new Error(`#EXT-X-${tag} must appear before the first Media Segment (${result[0]})`);
}
function updateFromToPTS(fragFrom, fragTo) {
  const fragToPTS = fragTo.startPTS;
  if (isFiniteNumber(fragToPTS)) {
    let duration5 = 0;
    let frag;
    if (fragTo.sn > fragFrom.sn) {
      duration5 = fragToPTS - fragFrom.start;
      frag = fragFrom;
    } else {
      duration5 = fragFrom.start - fragToPTS;
      frag = fragTo;
    }
    if (frag.duration !== duration5) {
      frag.setDuration(duration5);
    }
  } else if (fragTo.sn > fragFrom.sn) {
    const contiguous = fragFrom.cc === fragTo.cc;
    if (contiguous && fragFrom.minEndPTS) {
      fragTo.setStart(fragFrom.start + (fragFrom.minEndPTS - fragFrom.start));
    } else {
      fragTo.setStart(fragFrom.start + fragFrom.duration);
    }
  } else {
    fragTo.setStart(Math.max(fragFrom.start - fragTo.duration, 0));
  }
}
function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  const parsedMediaDuration = endPTS - startPTS;
  if (parsedMediaDuration <= 0) {
    logger.warn("Fragment should have a positive duration", frag);
    endPTS = startPTS + frag.duration;
    endDTS = startDTS + frag.duration;
  }
  let maxStartPTS = startPTS;
  let minEndPTS = endPTS;
  const fragStartPts = frag.startPTS;
  const fragEndPts = frag.endPTS;
  if (isFiniteNumber(fragStartPts)) {
    const deltaPTS = Math.abs(fragStartPts - startPTS);
    if (!isFiniteNumber(frag.deltaPTS)) {
      frag.deltaPTS = deltaPTS;
    } else {
      frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
    }
    maxStartPTS = Math.max(startPTS, fragStartPts);
    startPTS = Math.min(startPTS, fragStartPts);
    startDTS = Math.min(startDTS, frag.startDTS);
    minEndPTS = Math.min(endPTS, fragEndPts);
    endPTS = Math.max(endPTS, fragEndPts);
    endDTS = Math.max(endDTS, frag.endDTS);
  }
  const drift = startPTS - frag.start;
  if (frag.start !== 0) {
    frag.setStart(startPTS);
  }
  frag.setDuration(endPTS - frag.start);
  frag.startPTS = startPTS;
  frag.maxStartPTS = maxStartPTS;
  frag.startDTS = startDTS;
  frag.endPTS = endPTS;
  frag.minEndPTS = minEndPTS;
  frag.endDTS = endDTS;
  const sn = frag.sn;
  if (!details || sn < details.startSN || sn > details.endSN) {
    return 0;
  }
  let i;
  const fragIdx = sn - details.startSN;
  const fragments = details.fragments;
  fragments[fragIdx] = frag;
  for (i = fragIdx; i > 0; i--) {
    updateFromToPTS(fragments[i], fragments[i - 1]);
  }
  for (i = fragIdx; i < fragments.length - 1; i++) {
    updateFromToPTS(fragments[i], fragments[i + 1]);
  }
  if (details.fragmentHint) {
    updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  }
  details.PTSKnown = details.alignedSliding = true;
  return drift;
}
function mergeDetails(oldDetails, newDetails) {
  if (oldDetails === newDetails) {
    return;
  }
  let currentInitSegment = null;
  const oldFragments = oldDetails.fragments;
  for (let i = oldFragments.length - 1; i >= 0; i--) {
    const oldInit = oldFragments[i].initSegment;
    if (oldInit) {
      currentInitSegment = oldInit;
      break;
    }
  }
  if (oldDetails.fragmentHint) {
    delete oldDetails.fragmentHint.endPTS;
  }
  let PTSFrag;
  mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag, newFragIndex, newFragments2) => {
    if (newDetails.skippedSegments) {
      if (newFrag.cc !== oldFrag.cc) {
        const ccOffset = oldFrag.cc - newFrag.cc;
        for (let i = newFragIndex; i < newFragments2.length; i++) {
          newFragments2[i].cc += ccOffset;
        }
      }
    }
    if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
      newFrag.setStart(newFrag.startPTS = oldFrag.startPTS);
      newFrag.startDTS = oldFrag.startDTS;
      newFrag.maxStartPTS = oldFrag.maxStartPTS;
      newFrag.endPTS = oldFrag.endPTS;
      newFrag.endDTS = oldFrag.endDTS;
      newFrag.minEndPTS = oldFrag.minEndPTS;
      newFrag.setDuration(oldFrag.endPTS - oldFrag.startPTS);
      if (newFrag.duration) {
        PTSFrag = newFrag;
      }
      newDetails.PTSKnown = newDetails.alignedSliding = true;
    }
    if (oldFrag.hasStreams) {
      newFrag.elementaryStreams = oldFrag.elementaryStreams;
    }
    newFrag.loader = oldFrag.loader;
    if (oldFrag.hasStats) {
      newFrag.stats = oldFrag.stats;
    }
    if (oldFrag.initSegment) {
      newFrag.initSegment = oldFrag.initSegment;
      currentInitSegment = oldFrag.initSegment;
    }
  });
  const newFragments = newDetails.fragments;
  const fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments;
  if (currentInitSegment) {
    fragmentsToCheck.forEach((frag) => {
      var _currentInitSegment;
      if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
        frag.initSegment = currentInitSegment;
      }
    });
  }
  if (newDetails.skippedSegments) {
    newDetails.deltaUpdateFailed = newFragments.some((frag) => !frag);
    if (newDetails.deltaUpdateFailed) {
      logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");
      for (let i = newDetails.skippedSegments; i--; ) {
        newFragments.shift();
      }
      newDetails.startSN = newFragments[0].sn;
    } else {
      newDetails.endCC = newFragments[newFragments.length - 1].cc;
      if (newDetails.canSkipDateRanges) {
        newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails);
      }
      const programDateTimes = oldDetails.fragments.filter((frag) => frag.rawProgramDateTime);
      if (oldDetails.hasProgramDateTime && !newDetails.hasProgramDateTime) {
        for (let i = 1; i < fragmentsToCheck.length; i++) {
          if (fragmentsToCheck[i].programDateTime === null) {
            assignProgramDateTime(fragmentsToCheck[i], fragmentsToCheck[i - 1], programDateTimes);
          }
        }
      }
      mapDateRanges(programDateTimes, newDetails);
    }
  }
  mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {
    newPart.elementaryStreams = oldPart.elementaryStreams;
    newPart.stats = oldPart.stats;
  });
  if (PTSFrag) {
    updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  } else {
    adjustSliding(oldDetails, newDetails);
  }
  if (newFragments.length) {
    newDetails.totalduration = newDetails.edge - newFragments[0].start;
  }
  newDetails.driftStartTime = oldDetails.driftStartTime;
  newDetails.driftStart = oldDetails.driftStart;
  const advancedDateTime = newDetails.advancedDateTime;
  if (newDetails.advanced && advancedDateTime) {
    const edge = newDetails.edge;
    if (!newDetails.driftStart) {
      newDetails.driftStartTime = advancedDateTime;
      newDetails.driftStart = edge;
    }
    newDetails.driftEndTime = advancedDateTime;
    newDetails.driftEnd = edge;
  } else {
    newDetails.driftEndTime = oldDetails.driftEndTime;
    newDetails.driftEnd = oldDetails.driftEnd;
    newDetails.advancedDateTime = oldDetails.advancedDateTime;
  }
  if (newDetails.requestScheduled === -1) {
    newDetails.requestScheduled = oldDetails.requestScheduled;
  }
}
function mergeDateRanges(oldDateRanges, newDetails) {
  const {
    dateRanges: deltaDateRanges,
    recentlyRemovedDateranges
  } = newDetails;
  const dateRanges = _extends({}, oldDateRanges);
  if (recentlyRemovedDateranges) {
    recentlyRemovedDateranges.forEach((id) => {
      delete dateRanges[id];
    });
  }
  const mergeIds = Object.keys(dateRanges);
  const mergeCount = mergeIds.length;
  if (mergeCount) {
    Object.keys(deltaDateRanges).forEach((id) => {
      const mergedDateRange = dateRanges[id];
      const dateRange = new DateRange(deltaDateRanges[id].attr, mergedDateRange);
      if (dateRange.isValid) {
        dateRanges[id] = dateRange;
        if (!mergedDateRange) {
          dateRange.tagOrder += mergeCount;
        }
      } else {
        logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${stringify(deltaDateRanges[id].attr)}"`);
      }
    });
  }
  return dateRanges;
}
function mapPartIntersection(oldParts, newParts, intersectionFn) {
  if (oldParts && newParts) {
    let delta = 0;
    for (let i = 0, len = oldParts.length; i <= len; i++) {
      const oldPart = oldParts[i];
      const newPart = newParts[i + delta];
      if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {
        intersectionFn(oldPart, newPart);
      } else {
        delta--;
      }
    }
  }
}
function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  const skippedSegments = newDetails.skippedSegments;
  const start2 = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  const delta = newDetails.startSN - oldDetails.startSN;
  const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  for (let i = start2; i <= end; i++) {
    const oldFrag = oldFrags[delta + i];
    let newFrag = newFrags[i];
    if (skippedSegments && !newFrag && oldFrag) {
      newFrag = newDetails.fragments[i] = oldFrag;
    }
    if (oldFrag && newFrag) {
      intersectionFn(oldFrag, newFrag, i, newFrags);
      if (oldFrag.url && oldFrag.url !== newFrag.url) {
        newDetails.playlistParsingError = getSequenceError(`media sequence mismatch ${newFrag.sn}:`, oldDetails, newDetails, oldFrag, newFrag);
        return;
      } else if (oldFrag.cc !== newFrag.cc) {
        newDetails.playlistParsingError = getSequenceError(`discontinuity sequence mismatch (${oldFrag.cc}!=${newFrag.cc})`, oldDetails, newDetails, oldFrag, newFrag);
        return;
      }
    }
  }
}
function getSequenceError(message, oldDetails, newDetails, oldFrag, newFrag) {
  return new Error(`${message} ${newFrag.url}
Playlist starting @${oldDetails.startSN}
${oldDetails.m3u8}

Playlist starting @${newDetails.startSN}
${newDetails.m3u8}`);
}
function adjustSliding(oldDetails, newDetails, matchingStableVariantOrRendition = true) {
  const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  const oldFragments = oldDetails.fragments;
  const advancedOrStable = delta >= 0;
  let sliding = 0;
  if (advancedOrStable && delta < oldFragments.length) {
    sliding = oldFragments[delta].start;
  } else if (advancedOrStable && newDetails.startSN === oldDetails.endSN + 1) {
    sliding = oldDetails.fragmentEnd;
  } else if (advancedOrStable && matchingStableVariantOrRendition) {
    sliding = oldDetails.fragmentStart + delta * newDetails.levelTargetDuration;
  } else if (!newDetails.skippedSegments && newDetails.fragmentStart === 0) {
    sliding = oldDetails.fragmentStart;
  } else {
    return;
  }
  addSliding(newDetails, sliding);
}
function addSliding(details, sliding) {
  if (sliding) {
    const fragments = details.fragments;
    for (let i = details.skippedSegments; i < fragments.length; i++) {
      fragments[i].addStart(sliding);
    }
    if (details.fragmentHint) {
      details.fragmentHint.addStart(sliding);
    }
  }
}
function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {
  let reloadInterval = 1e3 * newDetails.targetduration;
  if (newDetails.updated) {
    const fragments = newDetails.fragments;
    const liveEdgeMaxTargetDurations = 4;
    if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
      const lastSegmentDuration = fragments[fragments.length - 1].duration * 1e3;
      if (lastSegmentDuration < reloadInterval) {
        reloadInterval = lastSegmentDuration;
      }
    }
  } else {
    reloadInterval /= 2;
  }
  return Math.round(reloadInterval);
}
function getFragmentWithSN(details, sn, fragCurrent) {
  if (!details) {
    return null;
  }
  let fragment = details.fragments[sn - details.startSN];
  if (fragment) {
    return fragment;
  }
  fragment = details.fragmentHint;
  if (fragment && fragment.sn === sn) {
    return fragment;
  }
  if (sn < details.startSN && fragCurrent && fragCurrent.sn === sn) {
    return fragCurrent;
  }
  return null;
}
function getPartWith(details, sn, partIndex) {
  if (!details) {
    return null;
  }
  return findPart(details.partList, sn, partIndex);
}
function findPart(partList, sn, partIndex) {
  if (partList) {
    for (let i = partList.length; i--; ) {
      const part = partList[i];
      if (part.index === partIndex && part.fragment.sn === sn) {
        return part;
      }
    }
  }
  return null;
}
function reassignFragmentLevelIndexes(levels) {
  levels.forEach((level, index) => {
    var _level$details;
    (_level$details = level.details) == null ? void 0 : _level$details.fragments.forEach((fragment) => {
      fragment.level = index;
      if (fragment.initSegment) {
        fragment.initSegment.level = index;
      }
    });
  });
}
function findFirstFragWithCC(fragments, cc) {
  for (let i = 0, len = fragments.length; i < len; i++) {
    var _fragments$i;
    if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
      return fragments[i];
    }
  }
  return null;
}
function shouldAlignOnDiscontinuities(refDetails, details) {
  if (refDetails) {
    if (details.startCC < refDetails.endCC && details.endCC > refDetails.startCC) {
      return true;
    }
  }
  return false;
}
function adjustFragmentStart(frag, sliding) {
  if (frag) {
    const start2 = frag.start + sliding;
    frag.start = frag.startPTS = start2;
    frag.endPTS = start2 + frag.duration;
  }
}
function adjustSlidingStart(sliding, details) {
  const fragments = details.fragments;
  for (let i = 0, len = fragments.length; i < len; i++) {
    adjustFragmentStart(fragments[i], sliding);
  }
  if (details.fragmentHint) {
    adjustFragmentStart(details.fragmentHint, sliding);
  }
  details.alignedSliding = true;
}
function alignStream(switchDetails, details) {
  if (!switchDetails) {
    return;
  }
  alignDiscontinuities(details, switchDetails);
  if (!details.alignedSliding && switchDetails) {
    alignMediaPlaylistByPDT(details, switchDetails);
  }
  if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
    adjustSliding(switchDetails, details, false);
  }
}
function alignDiscontinuities(details, refDetails) {
  if (!shouldAlignOnDiscontinuities(refDetails, details)) {
    return;
  }
  const targetCC = Math.min(refDetails.endCC, details.endCC);
  const refFrag = findFirstFragWithCC(refDetails.fragments, targetCC);
  const frag = findFirstFragWithCC(details.fragments, targetCC);
  if (!refFrag || !frag) {
    return;
  }
  logger.log(`Aligning playlist at start of dicontinuity sequence ${targetCC}`);
  const delta = refFrag.start - frag.start;
  adjustSlidingStart(delta, details);
}
function alignMediaPlaylistByPDT(details, refDetails) {
  if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
    return;
  }
  const fragments = details.fragments;
  const refFragments = refDetails.fragments;
  if (!fragments.length || !refFragments.length) {
    return;
  }
  let refFrag;
  let frag;
  const targetCC = Math.min(refDetails.endCC, details.endCC);
  if (refDetails.startCC < targetCC && details.startCC < targetCC) {
    refFrag = findFirstFragWithCC(refFragments, targetCC);
    frag = findFirstFragWithCC(fragments, targetCC);
  }
  if (!refFrag || !frag) {
    refFrag = refFragments[Math.floor(refFragments.length / 2)];
    frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  }
  const refPDT = refFrag.programDateTime;
  const targetPDT = frag.programDateTime;
  if (!refPDT || !targetPDT) {
    return;
  }
  const delta = (targetPDT - refPDT) / 1e3 - (frag.start - refFrag.start);
  adjustSlidingStart(delta, details);
}
var TimeRanges2 = {
  toString: function(r2) {
    let log2 = "";
    const len = r2.length;
    for (let i = 0; i < len; i++) {
      log2 += `[${r2.start(i).toFixed(3)}-${r2.end(i).toFixed(3)}]`;
    }
    return log2;
  }
};
var State = {
  STOPPED: "STOPPED",
  IDLE: "IDLE",
  KEY_LOADING: "KEY_LOADING",
  FRAG_LOADING: "FRAG_LOADING",
  FRAG_LOADING_WAITING_RETRY: "FRAG_LOADING_WAITING_RETRY",
  WAITING_TRACK: "WAITING_TRACK",
  PARSING: "PARSING",
  PARSED: "PARSED",
  ENDED: "ENDED",
  ERROR: "ERROR",
  WAITING_INIT_PTS: "WAITING_INIT_PTS",
  WAITING_LEVEL: "WAITING_LEVEL"
};
var BaseStreamController = class extends TaskLoop {
  constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
    super(logPrefix, hls.logger);
    this.hls = void 0;
    this.fragPrevious = null;
    this.fragCurrent = null;
    this.fragmentTracker = void 0;
    this.transmuxer = null;
    this._state = State.STOPPED;
    this.playlistType = void 0;
    this.media = null;
    this.mediaBuffer = null;
    this.config = void 0;
    this.bitrateTest = false;
    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 = false;
    this.decrypter = void 0;
    this.initPTS = [];
    this.buffering = true;
    this.loadingParts = false;
    this.loopSn = void 0;
    this.onMediaSeeking = () => {
      const {
        config,
        fragCurrent,
        media,
        mediaBuffer,
        state
      } = this;
      const currentTime = media ? media.currentTime : 0;
      const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
      this.log(`media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}`);
      if (this.state === State.ENDED) {
        this.resetLoadingState();
      } else if (fragCurrent) {
        const tolerance = config.maxFragLookUpTolerance;
        const fragStartOffset = fragCurrent.start - tolerance;
        const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
        if (!bufferInfo.len || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
          const pastFragment = currentTime > fragEndOffset;
          if (currentTime < fragStartOffset || pastFragment) {
            if (pastFragment && fragCurrent.loader) {
              this.log("seeking outside of buffer while fragment load in progress, cancel fragment load");
              fragCurrent.abortRequests();
              this.resetLoadingState();
            }
            this.fragPrevious = null;
          }
        }
      }
      if (media) {
        this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
        const lastCurrentTime = this.lastCurrentTime;
        if (currentTime > lastCurrentTime) {
          this.lastCurrentTime = currentTime;
        }
        if (!this.loadingParts) {
          const bufferEnd = Math.max(bufferInfo.end, currentTime);
          const shouldLoadParts = this.shouldLoadParts(this.getLevelDetails(), bufferEnd);
          if (shouldLoadParts) {
            this.log(`LL-Part loading ON after seeking to ${currentTime.toFixed(2)} with buffer @${bufferEnd.toFixed(2)}`);
            this.loadingParts = shouldLoadParts;
          }
        }
      }
      if (!this.hls.hasEnoughToStart && !bufferInfo.len) {
        this.log(`setting startPosition to ${currentTime} because of seek before start`);
        this.nextLoadPosition = this.startPosition = currentTime;
      }
      this.tickImmediate();
    };
    this.onMediaEnded = () => {
      this.log(`setting startPosition to 0 because media ended`);
      this.startPosition = this.lastCurrentTime = 0;
    };
    this.playlistType = playlistType;
    this.hls = hls;
    this.fragmentLoader = new FragmentLoader(hls.config);
    this.keyLoader = keyLoader;
    this.fragmentTracker = fragmentTracker;
    this.config = hls.config;
    this.decrypter = new Decrypter(hls.config);
  }
  registerListeners() {
    const {
      hls
    } = this;
    hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
    hls.on(Events.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls
    } = this;
    hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
    hls.off(Events.ERROR, this.onError, this);
  }
  doTick() {
    this.onTickEnd();
  }
  onTickEnd() {
  }
  startLoad(startPosition) {
  }
  stopLoad() {
    if (this.state === State.STOPPED) {
      return;
    }
    this.fragmentLoader.abort();
    this.keyLoader.abort(this.playlistType);
    const frag = this.fragCurrent;
    if (frag != null && frag.loader) {
      frag.abortRequests();
      this.fragmentTracker.removeFragment(frag);
    }
    this.resetTransmuxer();
    this.fragCurrent = null;
    this.fragPrevious = null;
    this.clearInterval();
    this.clearNextTick();
    this.state = State.STOPPED;
  }
  get startPositionValue() {
    const {
      nextLoadPosition,
      startPosition
    } = this;
    if (startPosition === -1 && nextLoadPosition) {
      return nextLoadPosition;
    }
    return startPosition;
  }
  get bufferingEnabled() {
    return this.buffering;
  }
  pauseBuffering() {
    this.buffering = false;
  }
  resumeBuffering() {
    this.buffering = true;
  }
  get inFlightFrag() {
    return {
      frag: this.fragCurrent,
      state: this.state
    };
  }
  _streamEnded(bufferInfo, levelDetails) {
    if (levelDetails.live || !this.media) {
      return false;
    }
    const bufferEnd = bufferInfo.end || 0;
    const timelineStart = this.config.timelineOffset || 0;
    if (bufferEnd <= timelineStart) {
      return false;
    }
    const nextStart = bufferInfo.nextStart;
    const hasSecondBufferedRange = nextStart && nextStart > timelineStart && nextStart < levelDetails.edge;
    if (hasSecondBufferedRange) {
      return false;
    }
    if (this.media.currentTime < bufferInfo.start) {
      return false;
    }
    const partList = levelDetails.partList;
    if (partList != null && partList.length) {
      const lastPart = partList[partList.length - 1];
      const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
      return lastPartBuffered;
    }
    const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
    return this.fragmentTracker.isEndListAppended(playlistType);
  }
  getLevelDetails() {
    if (this.levels && this.levelLastLoaded !== null) {
      var _this$levelLastLoaded;
      return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
    }
  }
  get timelineOffset() {
    const configuredTimelineOffset = this.config.timelineOffset;
    if (configuredTimelineOffset) {
      var _this$getLevelDetails;
      return ((_this$getLevelDetails = this.getLevelDetails()) == null ? void 0 : _this$getLevelDetails.appliedTimelineOffset) || configuredTimelineOffset;
    }
    return 0;
  }
  onMediaAttached(event, data) {
    const media = this.media = this.mediaBuffer = data.media;
    media.removeEventListener("seeking", this.onMediaSeeking);
    media.removeEventListener("ended", this.onMediaEnded);
    media.addEventListener("seeking", this.onMediaSeeking);
    media.addEventListener("ended", this.onMediaEnded);
    const config = this.config;
    if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
      this.startLoad(config.startPosition);
    }
  }
  onMediaDetaching(event, data) {
    const transferringMedia = !!data.transferMedia;
    const media = this.media;
    if (media === null) {
      return;
    }
    if (media.ended) {
      this.log("MSE detaching and video ended, reset startPosition");
      this.startPosition = this.lastCurrentTime = 0;
    }
    media.removeEventListener("seeking", this.onMediaSeeking);
    media.removeEventListener("ended", this.onMediaEnded);
    if (this.keyLoader && !transferringMedia) {
      this.keyLoader.detach();
    }
    this.media = this.mediaBuffer = null;
    this.loopSn = void 0;
    if (transferringMedia) {
      this.resetLoadingState();
      this.resetTransmuxer();
      return;
    }
    this.loadingParts = false;
    this.fragmentTracker.removeAllFragments();
    this.stopLoad();
  }
  onManifestLoading() {
    this.initPTS = [];
    this.levels = this.levelLastLoaded = this.fragCurrent = null;
    this.lastCurrentTime = this.startPosition = 0;
    this.startFragRequested = false;
  }
  onError(event, data) {
  }
  onManifestLoaded(event, data) {
    this.startTimeOffset = data.startTimeOffset;
  }
  onHandlerDestroying() {
    this.stopLoad();
    if (this.transmuxer) {
      this.transmuxer.destroy();
      this.transmuxer = null;
    }
    super.onHandlerDestroying();
    this.hls = this.onMediaSeeking = this.onMediaEnded = null;
  }
  onHandlerDestroyed() {
    this.state = State.STOPPED;
    if (this.fragmentLoader) {
      this.fragmentLoader.destroy();
    }
    if (this.keyLoader) {
      this.keyLoader.destroy();
    }
    if (this.decrypter) {
      this.decrypter.destroy();
    }
    this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
    super.onHandlerDestroyed();
  }
  loadFragment(frag, level, targetBufferTime) {
    this.startFragRequested = true;
    this._loadFragForPlayback(frag, level, targetBufferTime);
  }
  _loadFragForPlayback(fragment, level, targetBufferTime) {
    const progressCallback = (data) => {
      const frag = data.frag;
      if (this.fragContextChanged(frag)) {
        this.warn(`${frag.type} sn: ${frag.sn}${data.part ? " part: " + data.part.index : ""} of ${this.fragInfo(frag, false, data.part)}) was dropped during download.`);
        this.fragmentTracker.removeFragment(frag);
        return;
      }
      frag.stats.chunkCount++;
      this._handleFragmentLoadProgress(data);
    };
    this._doFragLoad(fragment, level, targetBufferTime, progressCallback).then((data) => {
      if (!data) {
        return;
      }
      const state = this.state;
      const frag = data.frag;
      if (this.fragContextChanged(frag)) {
        if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {
          this.fragmentTracker.removeFragment(frag);
          this.state = State.IDLE;
        }
        return;
      }
      if ("payload" in data) {
        this.log(`Loaded ${frag.type} sn: ${frag.sn} of ${this.playlistLabel()} ${frag.level}`);
        this.hls.trigger(Events.FRAG_LOADED, data);
      }
      this._handleFragmentLoadComplete(data);
    }).catch((reason) => {
      if (this.state === State.STOPPED || this.state === State.ERROR) {
        return;
      }
      this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);
      this.resetFragmentLoading(fragment);
    });
  }
  clearTrackerIfNeeded(frag) {
    var _this$mediaBuffer;
    const {
      fragmentTracker
    } = this;
    const fragState = fragmentTracker.getState(frag);
    if (fragState === FragmentState.APPENDING) {
      const playlistType = frag.type;
      const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
      const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
      const backtrackFragment = this.backtrackFragment;
      const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
      if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
        fragmentTracker.removeFragment(frag);
      }
    } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
      fragmentTracker.removeAllFragments();
    } else if (fragmentTracker.hasParts(frag.type)) {
      fragmentTracker.detectPartialFragments({
        frag,
        part: null,
        stats: frag.stats,
        id: frag.type
      });
      if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
        fragmentTracker.removeFragment(frag);
      }
    }
  }
  checkLiveUpdate(details) {
    if (details.updated && !details.live) {
      const lastFragment = details.fragments[details.fragments.length - 1];
      this.fragmentTracker.detectPartialFragments({
        frag: lastFragment,
        part: null,
        stats: lastFragment.stats,
        id: lastFragment.type
      });
    }
    if (!details.fragments[0]) {
      details.deltaUpdateFailed = true;
    }
  }
  waitForLive(levelInfo) {
    const details = levelInfo.details;
    return (details == null ? void 0 : details.live) && details.type !== "EVENT" && (this.levelLastLoaded !== levelInfo || details.expired);
  }
  flushMainBuffer(startOffset, endOffset, type2 = null) {
    if (!(startOffset - endOffset)) {
      return;
    }
    const flushScope = {
      startOffset,
      endOffset,
      type: type2
    };
    this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  }
  _loadInitSegment(fragment, level) {
    this._doFragLoad(fragment, level).then((data) => {
      const frag = data == null ? void 0 : data.frag;
      if (!frag || this.fragContextChanged(frag) || !this.levels) {
        throw new Error("init load aborted");
      }
      return data;
    }).then((data) => {
      const {
        hls
      } = this;
      const {
        frag,
        payload
      } = data;
      const decryptData = frag.decryptdata;
      if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
        const startTime = self.performance.now();
        return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
          hls.trigger(Events.ERROR, {
            type: ErrorTypes.MEDIA_ERROR,
            details: ErrorDetails.FRAG_DECRYPT_ERROR,
            fatal: false,
            error: err,
            reason: err.message,
            frag
          });
          throw err;
        }).then((decryptedData) => {
          const endTime = self.performance.now();
          hls.trigger(Events.FRAG_DECRYPTED, {
            frag,
            payload: decryptedData,
            stats: {
              tstart: startTime,
              tdecrypt: endTime
            }
          });
          data.payload = decryptedData;
          return this.completeInitSegmentLoad(data);
        });
      }
      return this.completeInitSegmentLoad(data);
    }).catch((reason) => {
      if (this.state === State.STOPPED || this.state === State.ERROR) {
        return;
      }
      this.warn(reason);
      this.resetFragmentLoading(fragment);
    });
  }
  completeInitSegmentLoad(data) {
    const {
      levels
    } = this;
    if (!levels) {
      throw new Error("init load aborted, missing levels");
    }
    const stats = data.frag.stats;
    if (this.state !== State.STOPPED) {
      this.state = State.IDLE;
    }
    data.frag.data = new Uint8Array(data.payload);
    stats.parsing.start = stats.buffering.start = self.performance.now();
    stats.parsing.end = stats.buffering.end = self.performance.now();
    this.tick();
  }
  fragContextChanged(frag) {
    const {
      fragCurrent
    } = this;
    return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  }
  fragBufferedComplete(frag, part) {
    const media = this.mediaBuffer ? this.mediaBuffer : this.media;
    this.log(`Buffered ${frag.type} sn: ${frag.sn}${part ? " part: " + part.index : ""} of ${this.fragInfo(frag, false, part)} > buffer:${media ? TimeRanges2.toString(BufferHelper.getBuffered(media)) : "(detached)"})`);
    if (isMediaFragment(frag)) {
      var _this$levels;
      if (frag.type !== PlaylistLevelType.SUBTITLE) {
        const el = frag.elementaryStreams;
        if (!Object.keys(el).some((type2) => !!el[type2])) {
          this.state = State.IDLE;
          return;
        }
      }
      const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
      if (level != null && level.fragmentError) {
        this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);
        level.fragmentError = 0;
      }
    }
    this.state = State.IDLE;
  }
  _handleFragmentLoadComplete(fragLoadedEndData) {
    const {
      transmuxer
    } = this;
    if (!transmuxer) {
      return;
    }
    const {
      frag,
      part,
      partsLoaded
    } = fragLoadedEndData;
    const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some((fragLoaded) => !fragLoaded);
    const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
    transmuxer.flush(chunkMeta);
  }
  _handleFragmentLoadProgress(frag) {
  }
  _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {
    var _frag$decryptdata;
    this.fragCurrent = frag;
    const details = level == null ? void 0 : level.details;
    if (!this.levels || !details) {
      throw new Error(`frag load aborted, missing level${details ? "" : " detail"}s`);
    }
    let keyLoadingPromise = null;
    if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
      this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.playlistLabel()} ${frag.level}`);
      this.state = State.KEY_LOADING;
      this.fragCurrent = frag;
      keyLoadingPromise = this.keyLoader.load(frag).then((keyLoadedData) => {
        if (!this.fragContextChanged(keyLoadedData.frag)) {
          this.hls.trigger(Events.KEY_LOADED, keyLoadedData);
          if (this.state === State.KEY_LOADING) {
            this.state = State.IDLE;
          }
          return keyLoadedData;
        }
      });
      this.hls.trigger(Events.KEY_LOADING, {
        frag
      });
      if (this.fragCurrent === null) {
        keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`));
      }
    } else if (!frag.encrypted && details.encryptedFragments.length) {
      this.keyLoader.loadClear(frag, details.encryptedFragments);
    }
    const fragPrevious = this.fragPrevious;
    if (isMediaFragment(frag) && (!fragPrevious || frag.sn !== fragPrevious.sn)) {
      const shouldLoadParts = this.shouldLoadParts(level.details, frag.end);
      if (shouldLoadParts !== this.loadingParts) {
        this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} loading sn ${fragPrevious == null ? void 0 : fragPrevious.sn}->${frag.sn}`);
        this.loadingParts = shouldLoadParts;
      }
    }
    targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
    if (this.loadingParts && isMediaFragment(frag)) {
      const partList = details.partList;
      if (partList && progressCallback) {
        if (targetBufferTime > frag.end && details.fragmentHint) {
          frag = details.fragmentHint;
        }
        const partIndex = this.getNextPart(partList, frag, targetBufferTime);
        if (partIndex > -1) {
          const part = partList[partIndex];
          frag = this.fragCurrent = part.fragment;
          this.log(`Loading ${frag.type} sn: ${frag.sn} part: ${part.index} (${partIndex}/${partList.length - 1}) of ${this.fragInfo(frag, false, part)}) cc: ${frag.cc} [${details.startSN}-${details.endSN}], target: ${parseFloat(targetBufferTime.toFixed(3))}`);
          this.nextLoadPosition = part.start + part.duration;
          this.state = State.FRAG_LOADING;
          let _result;
          if (keyLoadingPromise) {
            _result = keyLoadingPromise.then((keyLoadedData) => {
              if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
                return null;
              }
              return this.doFragPartsLoad(frag, part, level, progressCallback);
            }).catch((error) => this.handleFragLoadError(error));
          } else {
            _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch((error) => this.handleFragLoadError(error));
          }
          this.hls.trigger(Events.FRAG_LOADING, {
            frag,
            part,
            targetBufferTime
          });
          if (this.fragCurrent === null) {
            return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));
          }
          return _result;
        } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
          return Promise.resolve(null);
        }
      }
    }
    if (isMediaFragment(frag) && this.loadingParts) {
      this.log(`LL-Part loading OFF after next part miss @${targetBufferTime.toFixed(2)}`);
      this.loadingParts = false;
    } else if (!frag.url) {
      return Promise.resolve(null);
    }
    this.log(`Loading ${frag.type} sn: ${frag.sn} of ${this.fragInfo(frag, false)}) cc: ${frag.cc} ${details ? "[" + details.startSN + "-" + details.endSN + "]" : ""}, target: ${parseFloat(targetBufferTime.toFixed(3))}`);
    if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
      this.nextLoadPosition = frag.start + frag.duration;
    }
    this.state = State.FRAG_LOADING;
    const dataOnProgress = this.config.progressive;
    let result;
    if (dataOnProgress && keyLoadingPromise) {
      result = keyLoadingPromise.then((keyLoadedData) => {
        if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
          return null;
        }
        return this.fragmentLoader.load(frag, progressCallback);
      }).catch((error) => this.handleFragLoadError(error));
    } else {
      result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : void 0), keyLoadingPromise]).then(([fragLoadedData]) => {
        if (!dataOnProgress && fragLoadedData && progressCallback) {
          progressCallback(fragLoadedData);
        }
        return fragLoadedData;
      }).catch((error) => this.handleFragLoadError(error));
    }
    this.hls.trigger(Events.FRAG_LOADING, {
      frag,
      targetBufferTime
    });
    if (this.fragCurrent === null) {
      return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));
    }
    return result;
  }
  doFragPartsLoad(frag, fromPart, level, progressCallback) {
    return new Promise((resolve, reject) => {
      var _level$details;
      const partsLoaded = [];
      const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
      const loadPart = (part) => {
        this.fragmentLoader.loadPart(frag, part, progressCallback).then((partLoadedData) => {
          partsLoaded[part.index] = partLoadedData;
          const loadedPart = partLoadedData.part;
          this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
          const nextPart = getPartWith(level.details, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
          if (nextPart) {
            loadPart(nextPart);
          } else {
            return resolve({
              frag,
              part: loadedPart,
              partsLoaded
            });
          }
        }).catch(reject);
      };
      loadPart(fromPart);
    });
  }
  handleFragLoadError(error) {
    if ("data" in error) {
      const data = error.data;
      if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
        this.handleFragLoadAborted(data.frag, data.part);
      } else {
        this.hls.trigger(Events.ERROR, data);
      }
    } else {
      this.hls.trigger(Events.ERROR, {
        type: ErrorTypes.OTHER_ERROR,
        details: ErrorDetails.INTERNAL_EXCEPTION,
        err: error,
        error,
        fatal: true
      });
    }
    return null;
  }
  _handleTransmuxerFlush(chunkMeta) {
    const context = this.getCurrentContext(chunkMeta);
    if (!context || this.state !== State.PARSING) {
      if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
        this.state = State.IDLE;
      }
      return;
    }
    const {
      frag,
      part,
      level
    } = context;
    const now2 = self.performance.now();
    frag.stats.parsing.end = now2;
    if (part) {
      part.stats.parsing.end = now2;
    }
    const levelDetails = this.getLevelDetails();
    const loadingPartsAtEdge = levelDetails && frag.sn > levelDetails.endSN;
    const shouldLoadParts = loadingPartsAtEdge || this.shouldLoadParts(levelDetails, frag.end);
    if (shouldLoadParts !== this.loadingParts) {
      this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} after parsing segment ending @${frag.end.toFixed(2)}`);
      this.loadingParts = shouldLoadParts;
    }
    this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  }
  shouldLoadParts(details, bufferEnd) {
    if (this.config.lowLatencyMode) {
      if (!details) {
        return this.loadingParts;
      }
      if (details != null && details.partList) {
        var _details$fragmentHint;
        const firstPart = details.partList[0];
        const safePartStart = firstPart.end + (((_details$fragmentHint = details.fragmentHint) == null ? void 0 : _details$fragmentHint.duration) || 0);
        if (bufferEnd >= safePartStart) {
          var _this$media;
          const playhead = this.hls.hasEnoughToStart ? ((_this$media = this.media) == null ? void 0 : _this$media.currentTime) || this.lastCurrentTime : this.getLoadPosition();
          if (playhead > firstPart.start - firstPart.fragment.duration) {
            return true;
          }
        }
      }
    }
    return false;
  }
  getCurrentContext(chunkMeta) {
    const {
      levels,
      fragCurrent
    } = this;
    const {
      level: levelIndex,
      sn,
      part: partIndex
    } = chunkMeta;
    if (!(levels != null && levels[levelIndex])) {
      this.warn(`Levels object was unset while buffering fragment ${sn} of ${this.playlistLabel()} ${levelIndex}. The current chunk will not be buffered.`);
      return null;
    }
    const level = levels[levelIndex];
    const levelDetails = level.details;
    const part = partIndex > -1 ? getPartWith(levelDetails, sn, partIndex) : null;
    const frag = part ? part.fragment : getFragmentWithSN(levelDetails, sn, fragCurrent);
    if (!frag) {
      return null;
    }
    if (fragCurrent && fragCurrent !== frag) {
      frag.stats = fragCurrent.stats;
    }
    return {
      frag,
      part,
      level
    };
  }
  bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
    var _buffer;
    if (!data || this.state !== State.PARSING) {
      return;
    }
    const {
      data1,
      data2
    } = data;
    let buffer = data1;
    if (data1 && data2) {
      buffer = appendUint8Array(data1, data2);
    }
    if (!((_buffer = buffer) != null && _buffer.length)) {
      return;
    }
    const segment = {
      type: data.type,
      frag,
      part,
      chunkMeta,
      parent: frag.type,
      data: buffer
    };
    this.hls.trigger(Events.BUFFER_APPENDING, segment);
    if (data.dropped && data.independent && !part) {
      if (noBacktracking) {
        return;
      }
      this.flushBufferGap(frag);
    }
  }
  flushBufferGap(frag) {
    const media = this.media;
    if (!media) {
      return;
    }
    if (!BufferHelper.isBuffered(media, media.currentTime)) {
      this.flushMainBuffer(0, frag.start);
      return;
    }
    const currentTime = media.currentTime;
    const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
    const fragDuration = frag.duration;
    const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
    const start2 = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
    if (frag.start - start2 > segmentFraction) {
      this.flushMainBuffer(start2, frag.start);
    }
  }
  getFwdBufferInfo(bufferable, type2) {
    var _this$media2;
    const pos = this.getLoadPosition();
    if (!isFiniteNumber(pos)) {
      return null;
    }
    const backwardSeek = this.lastCurrentTime > pos;
    const maxBufferHole = backwardSeek || (_this$media2 = this.media) != null && _this$media2.paused ? 0 : this.config.maxBufferHole;
    return this.getFwdBufferInfoAtPos(bufferable, pos, type2, maxBufferHole);
  }
  getFwdBufferInfoAtPos(bufferable, pos, type2, maxBufferHole) {
    const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
    if (bufferInfo.len === 0 && bufferInfo.nextStart !== void 0) {
      const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type2);
      if (bufferedFragAtPos && (bufferInfo.nextStart <= bufferedFragAtPos.end || bufferedFragAtPos.gap)) {
        const gapDuration = Math.max(Math.min(bufferInfo.nextStart, bufferedFragAtPos.end) - pos, maxBufferHole);
        return BufferHelper.bufferInfo(bufferable, pos, gapDuration);
      }
    }
    return bufferInfo;
  }
  getMaxBufferLength(levelBitrate) {
    const {
      config
    } = this;
    let maxBufLen;
    if (levelBitrate) {
      maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
    } else {
      maxBufLen = config.maxBufferLength;
    }
    return Math.min(maxBufLen, config.maxMaxBufferLength);
  }
  reduceMaxBufferLength(threshold, fragDuration) {
    const config = this.config;
    const minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
    const reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
    if (reducedLength >= minLength) {
      config.maxMaxBufferLength = reducedLength;
      this.warn(`Reduce max buffer length to ${reducedLength}s`);
      return true;
    }
    return false;
  }
  getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {
    var _this$fragmentTracker;
    const fragOrPart = (_this$fragmentTracker = this.fragmentTracker) == null ? void 0 : _this$fragmentTracker.getAppendedFrag(position, playlistType);
    if (fragOrPart && "fragment" in fragOrPart) {
      return fragOrPart.fragment;
    }
    return fragOrPart;
  }
  getNextFragment(pos, levelDetails) {
    const fragments = levelDetails.fragments;
    const fragLen = fragments.length;
    if (!fragLen) {
      return null;
    }
    const {
      config
    } = this;
    const start2 = fragments[0].start;
    const canLoadParts = config.lowLatencyMode && !!levelDetails.partList;
    let frag = null;
    if (levelDetails.live) {
      const initialLiveManifestSize = config.initialLiveManifestSize;
      if (fragLen < initialLiveManifestSize) {
        this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);
        return null;
      }
      if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start2) {
        var _frag;
        if (canLoadParts && !this.loadingParts) {
          this.log(`LL-Part loading ON for initial live fragment`);
          this.loadingParts = true;
        }
        frag = this.getInitialLiveFragment(levelDetails, fragments);
        const mainStart = this.hls.startPosition;
        const liveSyncPosition = this.hls.liveSyncPosition;
        const startPosition = frag ? (mainStart !== -1 && mainStart >= start2 ? mainStart : liveSyncPosition) || frag.start : pos;
        this.log(`Setting startPosition to ${startPosition} to match start frag at live edge. mainStart: ${mainStart} liveSyncPosition: ${liveSyncPosition} frag.start: ${(_frag = frag) == null ? void 0 : _frag.start}`);
        this.startPosition = this.nextLoadPosition = startPosition;
      }
    } else if (pos <= start2) {
      frag = fragments[0];
    }
    if (!frag) {
      const end = this.loadingParts ? levelDetails.partEnd : levelDetails.fragmentEnd;
      frag = this.getFragmentAtPosition(pos, end, levelDetails);
    }
    let programFrag = this.filterReplacedPrimary(frag, levelDetails);
    if (!programFrag && frag) {
      const curSNIdx = frag.sn - levelDetails.startSN;
      programFrag = this.filterReplacedPrimary(fragments[curSNIdx + 1] || null, levelDetails);
    }
    return this.mapToInitFragWhenRequired(programFrag);
  }
  isLoopLoading(frag, targetBufferTime) {
    const trackerState = this.fragmentTracker.getState(frag);
    return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  }
  getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
    let nextFragment = null;
    if (frag.gap) {
      nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
      if (nextFragment && !nextFragment.gap && bufferInfo.nextStart) {
        const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType, 0);
        if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
          const sn = nextFragment.sn;
          if (this.loopSn !== sn) {
            this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${sn}`);
            this.loopSn = sn;
          }
          return null;
        }
      }
    }
    this.loopSn = void 0;
    return nextFragment;
  }
  get primaryPrefetch() {
    if (interstitialsEnabled(this.hls.config)) {
      var _this$hls$interstitia, _this$hls$interstitia2;
      const playingInterstitial = (_this$hls$interstitia = this.hls.interstitialsManager) == null ? void 0 : (_this$hls$interstitia2 = _this$hls$interstitia.playingItem) == null ? void 0 : _this$hls$interstitia2.event;
      if (playingInterstitial) {
        return true;
      }
    }
    return false;
  }
  filterReplacedPrimary(frag, details) {
    if (!frag) {
      return frag;
    }
    if (interstitialsEnabled(this.hls.config) && frag.type !== PlaylistLevelType.SUBTITLE) {
      const interstitials = this.hls.interstitialsManager;
      const bufferingItem = interstitials == null ? void 0 : interstitials.bufferingItem;
      if (bufferingItem) {
        const bufferingInterstitial = bufferingItem.event;
        if (bufferingInterstitial) {
          if (bufferingInterstitial.appendInPlace || Math.abs(frag.start - bufferingItem.start) > 1 || bufferingItem.start === 0) {
            return null;
          }
        } else {
          if (frag.end <= bufferingItem.start && (details == null ? void 0 : details.live) === false) {
            return null;
          }
          if (frag.start > bufferingItem.end && bufferingItem.nextEvent) {
            if (bufferingItem.nextEvent.appendInPlace || frag.start - bufferingItem.end > 1) {
              return null;
            }
          }
        }
      }
      const playerQueue = interstitials == null ? void 0 : interstitials.playerQueue;
      if (playerQueue) {
        for (let i = playerQueue.length; i--; ) {
          const interstitial = playerQueue[i].interstitial;
          if (interstitial.appendInPlace && frag.start >= interstitial.startTime && frag.end <= interstitial.resumeTime) {
            return null;
          }
        }
      }
    }
    return frag;
  }
  mapToInitFragWhenRequired(frag) {
    if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
      return frag.initSegment;
    }
    return frag;
  }
  getNextPart(partList, frag, targetBufferTime) {
    let nextPart = -1;
    let contiguous = false;
    let independentAttrOmitted = true;
    for (let i = 0, len = partList.length; i < len; i++) {
      const part = partList[i];
      independentAttrOmitted = independentAttrOmitted && !part.independent;
      if (nextPart > -1 && targetBufferTime < part.start) {
        break;
      }
      const loaded = part.loaded;
      if (loaded) {
        nextPart = -1;
      } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
        nextPart = i;
      }
      contiguous = loaded;
    }
    return nextPart;
  }
  loadedEndOfParts(partList, targetBufferTime) {
    const lastPart = partList[partList.length - 1];
    return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  }
  /*
   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(levelDetails, fragments) {
    const fragPrevious = this.fragPrevious;
    let frag = null;
    if (fragPrevious) {
      if (levelDetails.hasProgramDateTime) {
        this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
        frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
      }
      if (!frag) {
        const targetSN = fragPrevious.sn + 1;
        if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
          const fragNext = fragments[targetSN - levelDetails.startSN];
          if (fragPrevious.cc === fragNext.cc) {
            frag = fragNext;
            this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
          }
        }
        if (!frag) {
          frag = findFragWithCC(fragments, fragPrevious.cc);
          if (frag) {
            this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
          }
        }
      }
    } else {
      const liveStart = this.hls.liveSyncPosition;
      if (liveStart !== null) {
        frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
      }
    }
    return frag;
  }
  /*
  This method finds the best matching fragment given the provided position.
   */
  getFragmentAtPosition(bufferEnd, end, levelDetails) {
    const {
      config
    } = this;
    let {
      fragPrevious
    } = this;
    let {
      fragments,
      endSN
    } = levelDetails;
    const {
      fragmentHint
    } = levelDetails;
    const {
      maxFragLookUpTolerance
    } = config;
    const partList = levelDetails.partList;
    const loadingParts = !!(this.loadingParts && partList != null && partList.length && fragmentHint);
    if (loadingParts && fragmentHint && !this.bitrateTest && partList[partList.length - 1].fragment.sn === fragmentHint.sn) {
      fragments = fragments.concat(fragmentHint);
      endSN = fragmentHint.sn;
    }
    let frag;
    if (bufferEnd < end) {
      var _this$media3;
      const backwardSeek = bufferEnd < this.lastCurrentTime;
      const lookupTolerance = backwardSeek || bufferEnd > end - maxFragLookUpTolerance || (_this$media3 = this.media) != null && _this$media3.paused || !this.startFragRequested ? 0 : maxFragLookUpTolerance;
      frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
    } else {
      frag = fragments[fragments.length - 1];
    }
    if (frag) {
      const curSNIdx = frag.sn - levelDetails.startSN;
      const fragState = this.fragmentTracker.getState(frag);
      if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
        fragPrevious = frag;
      }
      if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn || !levelDetails.live && !loadingParts)) {
        const sameLevel = fragPrevious && frag.level === fragPrevious.level;
        if (sameLevel) {
          const nextFrag = fragments[curSNIdx + 1];
          if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
            frag = nextFrag;
          } else {
            frag = null;
          }
        }
      }
    }
    return frag;
  }
  alignPlaylists(details, previousDetails, switchDetails) {
    const length = details.fragments.length;
    if (!length) {
      this.warn(`No fragments in live playlist`);
      return 0;
    }
    const slidingStart = details.fragmentStart;
    const firstLevelLoad = !previousDetails;
    const aligned = details.alignedSliding && isFiniteNumber(slidingStart);
    if (firstLevelLoad || !aligned && !slidingStart) {
      alignStream(switchDetails, details);
      const alignedSlidingStart = details.fragmentStart;
      this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : "na"}->${details.startSN} fragments: ${length}`);
      return alignedSlidingStart;
    }
    return slidingStart;
  }
  waitForCdnTuneIn(details) {
    const advancePartLimit = 3;
    return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  }
  setStartPosition(details, sliding) {
    let startPosition = this.startPosition;
    if (startPosition < sliding) {
      startPosition = -1;
    }
    const timelineOffset = this.timelineOffset;
    if (startPosition === -1) {
      const offsetInMultivariantPlaylist = this.startTimeOffset !== null;
      const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
      if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
        startPosition = sliding + startTimeOffset;
        if (startTimeOffset < 0) {
          startPosition += details.edge;
        }
        startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
        this.log(`Setting startPosition to ${startPosition} for start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? "multivariant" : "media"} playlist`);
        this.startPosition = startPosition;
      } else if (details.live) {
        startPosition = this.hls.liveSyncPosition || sliding;
        this.log(`Setting startPosition to -1 to start at live edge ${startPosition}`);
        this.startPosition = -1;
      } else {
        this.log(`setting startPosition to 0 by default`);
        this.startPosition = startPosition = 0;
      }
      this.lastCurrentTime = startPosition + timelineOffset;
    }
    this.nextLoadPosition = startPosition + timelineOffset;
  }
  getLoadPosition() {
    var _this$hls;
    const {
      media
    } = this;
    let pos = 0;
    if ((_this$hls = this.hls) != null && _this$hls.hasEnoughToStart && media) {
      pos = media.currentTime;
    } else if (this.nextLoadPosition >= 0) {
      pos = this.nextLoadPosition;
    }
    return pos;
  }
  handleFragLoadAborted(frag, part) {
    if (this.transmuxer && frag.type === this.playlistType && isMediaFragment(frag) && frag.stats.aborted) {
      this.warn(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of ${this.playlistLabel()} ${frag.level} was aborted`);
      this.resetFragmentLoading(frag);
    }
  }
  resetFragmentLoading(frag) {
    if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
      this.state = State.IDLE;
    }
  }
  onFragmentOrKeyLoadError(filterType, data) {
    if (data.chunkMeta && !data.frag) {
      const context = this.getCurrentContext(data.chunkMeta);
      if (context) {
        data.frag = context.frag;
      }
    }
    const frag = data.frag;
    if (!frag || frag.type !== filterType || !this.levels) {
      return;
    }
    if (this.fragContextChanged(frag)) {
      var _this$fragCurrent;
      this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.url}`);
      return;
    }
    const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
    if (gapTagEncountered) {
      this.fragmentTracker.fragBuffered(frag, true);
    }
    const errorAction = data.errorAction;
    const {
      action,
      flags,
      retryCount = 0,
      retryConfig
    } = errorAction || {};
    const couldRetry = !!errorAction && !!retryConfig;
    const retry = couldRetry && action === NetworkErrorAction.RetryRequest;
    const noAlternate = couldRetry && !errorAction.resolved && flags === ErrorActionFlags.MoveAllAlternatesMatchingHost;
    if (!retry && noAlternate && isMediaFragment(frag) && !frag.endList) {
      this.resetFragmentErrors(filterType);
      this.treatAsGap(frag);
      errorAction.resolved = true;
    } else if ((retry || noAlternate) && retryCount < retryConfig.maxNumRetry) {
      this.resetStartWhenNotLoaded(this.levelLastLoaded);
      const delay = getRetryDelay(retryConfig, retryCount);
      this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);
      errorAction.resolved = true;
      this.retryDate = self.performance.now() + delay;
      this.state = State.FRAG_LOADING_WAITING_RETRY;
    } else if (retryConfig && errorAction) {
      this.resetFragmentErrors(filterType);
      if (retryCount < retryConfig.maxNumRetry) {
        if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
          errorAction.resolved = true;
        }
      } else {
        this.warn(`${data.details} reached or exceeded max retry (${retryCount})`);
        return;
      }
    } else if (action === NetworkErrorAction.SendAlternateToPenaltyBox) {
      this.state = State.WAITING_LEVEL;
    } else {
      this.state = State.ERROR;
    }
    this.tickImmediate();
  }
  reduceLengthAndFlushBuffer(data) {
    if (this.state === State.PARSING || this.state === State.PARSED) {
      const frag = data.frag;
      const playlistType = data.parent;
      const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
      const buffered = bufferedInfo && bufferedInfo.len > 0.5;
      if (buffered) {
        this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
      }
      const flushBuffer = !buffered;
      if (flushBuffer) {
        this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`);
      }
      if (frag) {
        this.fragmentTracker.removeFragment(frag);
        this.nextLoadPosition = frag.start;
      }
      this.resetLoadingState();
      return flushBuffer;
    }
    return false;
  }
  resetFragmentErrors(filterType) {
    if (filterType === PlaylistLevelType.AUDIO) {
      this.fragCurrent = null;
    }
    if (!this.hls.hasEnoughToStart) {
      this.startFragRequested = false;
    }
    if (this.state !== State.STOPPED) {
      this.state = State.IDLE;
    }
  }
  afterBufferFlushed(media, bufferType, playlistType) {
    if (!media) {
      return;
    }
    const bufferedTimeRanges = BufferHelper.getBuffered(media);
    this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
    if (this.state === State.ENDED) {
      this.resetLoadingState();
    }
  }
  resetLoadingState() {
    this.log("Reset loading state");
    this.fragCurrent = null;
    this.fragPrevious = null;
    if (this.state !== State.STOPPED) {
      this.state = State.IDLE;
    }
  }
  resetStartWhenNotLoaded(level) {
    if (!this.hls.hasEnoughToStart) {
      this.startFragRequested = false;
      const details = level ? level.details : null;
      if (details != null && details.live) {
        this.log(`resetting startPosition for live start`);
        this.startPosition = -1;
        this.setStartPosition(details, details.fragmentStart);
        this.resetLoadingState();
      } else {
        this.nextLoadPosition = this.startPosition;
      }
    }
  }
  resetWhenMissingContext(chunkMeta) {
    this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of ${this.playlistLabel()} ${chunkMeta.level}. This chunk will not be buffered.`);
    this.removeUnbufferedFrags();
    this.resetStartWhenNotLoaded(this.levelLastLoaded);
    this.resetLoadingState();
  }
  removeUnbufferedFrags(start2 = 0) {
    this.fragmentTracker.removeFragmentsInRange(start2, Infinity, this.playlistType, false, true);
  }
  updateLevelTiming(frag, part, level, partial) {
    const details = level.details;
    if (!details) {
      this.warn("level.details undefined");
      return;
    }
    const parsed = Object.keys(frag.elementaryStreams).reduce((result, type2) => {
      const info = frag.elementaryStreams[type2];
      if (info) {
        const parsedDuration = info.endPTS - info.startPTS;
        if (parsedDuration <= 0) {
          this.warn(`Could not parse fragment ${frag.sn} ${type2} duration reliably (${parsedDuration})`);
          return result || false;
        }
        const drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
        this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
          details,
          level,
          drift,
          type: type2,
          frag,
          start: info.startPTS,
          end: info.endPTS
        });
        return true;
      }
      return result;
    }, false);
    if (!parsed) {
      var _this$transmuxer;
      if (level.fragmentError === 0) {
        this.treatAsGap(frag, level);
      }
      if (((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
        const error = new Error(`Found no media in fragment ${frag.sn} of ${this.playlistLabel()} ${frag.level} resetting transmuxer to fallback to playlist timing`);
        this.warn(error.message);
        this.hls.trigger(Events.ERROR, {
          type: ErrorTypes.MEDIA_ERROR,
          details: ErrorDetails.FRAG_PARSING_ERROR,
          fatal: false,
          error,
          frag,
          reason: `Found no media in msn ${frag.sn} of ${this.playlistLabel()} "${level.url}"`
        });
        if (!this.hls) {
          return;
        }
        this.resetTransmuxer();
      }
    }
    this.state = State.PARSED;
    this.log(`Parsed ${frag.type} sn: ${frag.sn}${part ? " part: " + part.index : ""} of ${this.fragInfo(frag, false, part)})`);
    this.hls.trigger(Events.FRAG_PARSED, {
      frag,
      part
    });
  }
  playlistLabel() {
    return this.playlistType === PlaylistLevelType.MAIN ? "level" : "track";
  }
  fragInfo(frag, pts = true, part) {
    var _ref, _ref2;
    return `${this.playlistLabel()} ${frag.level} (${part ? "part" : "frag"}:[${((_ref = pts && !part ? frag.startPTS : (part || frag).start) != null ? _ref : NaN).toFixed(3)}-${((_ref2 = pts && !part ? frag.endPTS : (part || frag).end) != null ? _ref2 : NaN).toFixed(3)}]${part && frag.type === "main" ? "INDEPENDENT=" + (part.independent ? "YES" : "NO") : ""}`;
  }
  treatAsGap(frag, level) {
    if (level) {
      level.fragmentError++;
    }
    frag.gap = true;
    this.fragmentTracker.removeFragment(frag);
    this.fragmentTracker.fragBuffered(frag, true);
  }
  resetTransmuxer() {
    var _this$transmuxer2;
    (_this$transmuxer2 = this.transmuxer) == null ? void 0 : _this$transmuxer2.reset();
  }
  recoverWorkerError(data) {
    if (data.event === "demuxerWorker") {
      this.fragmentTracker.removeAllFragments();
      if (this.transmuxer) {
        this.transmuxer.destroy();
        this.transmuxer = null;
      }
      this.resetStartWhenNotLoaded(this.levelLastLoaded);
      this.resetLoadingState();
    }
  }
  set state(nextState) {
    const previousState = this._state;
    if (previousState !== nextState) {
      this._state = nextState;
      this.log(`${previousState}->${nextState}`);
    }
  }
  get state() {
    return this._state;
  }
};
function interstitialsEnabled(config) {
  return !!config.interstitialsController && config.enableInterstitialPlayback !== false;
}
var ChunkCache = class {
  constructor() {
    this.chunks = [];
    this.dataLength = 0;
  }
  push(chunk) {
    this.chunks.push(chunk);
    this.dataLength += chunk.length;
  }
  flush() {
    const {
      chunks,
      dataLength
    } = this;
    let result;
    if (!chunks.length) {
      return new Uint8Array(0);
    } else if (chunks.length === 1) {
      result = chunks[0];
    } else {
      result = concatUint8Arrays(chunks, dataLength);
    }
    this.reset();
    return result;
  }
  reset() {
    this.chunks.length = 0;
    this.dataLength = 0;
  }
};
function concatUint8Arrays(chunks, dataLength) {
  const result = new Uint8Array(dataLength);
  let offset = 0;
  for (let i = 0; i < chunks.length; i++) {
    const chunk = chunks[i];
    result.set(chunk, offset);
    offset += chunk.length;
  }
  return result;
}
var eventemitter3 = {
  exports: {}
};
var hasRequiredEventemitter3;
function requireEventemitter3() {
  if (hasRequiredEventemitter3) return eventemitter3.exports;
  hasRequiredEventemitter3 = 1;
  (function(module) {
    var has = Object.prototype.hasOwnProperty, prefix = "~";
    function Events3() {
    }
    if (Object.create) {
      Events3.prototype = /* @__PURE__ */ Object.create(null);
      if (!new Events3().__proto__) prefix = false;
    }
    function EE(fn, context, once) {
      this.fn = fn;
      this.context = context;
      this.once = once || false;
    }
    function addListener(emitter, event, fn, context, once) {
      if (typeof fn !== "function") {
        throw new TypeError("The listener must be a function");
      }
      var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
      if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
      else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
      else emitter._events[evt] = [emitter._events[evt], listener];
      return emitter;
    }
    function clearEvent(emitter, evt) {
      if (--emitter._eventsCount === 0) emitter._events = new Events3();
      else delete emitter._events[evt];
    }
    function EventEmitter2() {
      this._events = new Events3();
      this._eventsCount = 0;
    }
    EventEmitter2.prototype.eventNames = function eventNames() {
      var names = [], events, name;
      if (this._eventsCount === 0) return names;
      for (name in events = this._events) {
        if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
      }
      if (Object.getOwnPropertySymbols) {
        return names.concat(Object.getOwnPropertySymbols(events));
      }
      return names;
    };
    EventEmitter2.prototype.listeners = function listeners(event) {
      var evt = prefix ? prefix + event : event, handlers = this._events[evt];
      if (!handlers) return [];
      if (handlers.fn) return [handlers.fn];
      for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
        ee[i] = handlers[i].fn;
      }
      return ee;
    };
    EventEmitter2.prototype.listenerCount = function listenerCount(event) {
      var evt = prefix ? prefix + event : event, listeners = this._events[evt];
      if (!listeners) return 0;
      if (listeners.fn) return 1;
      return listeners.length;
    };
    EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
      var evt = prefix ? prefix + event : event;
      if (!this._events[evt]) return false;
      var listeners = this._events[evt], len = arguments.length, args, i;
      if (listeners.fn) {
        if (listeners.once) this.removeListener(event, listeners.fn, void 0, true);
        switch (len) {
          case 1:
            return listeners.fn.call(listeners.context), true;
          case 2:
            return listeners.fn.call(listeners.context, a1), true;
          case 3:
            return listeners.fn.call(listeners.context, a1, a2), true;
          case 4:
            return listeners.fn.call(listeners.context, a1, a2, a3), true;
          case 5:
            return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
          case 6:
            return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
        }
        for (i = 1, args = new Array(len - 1); i < len; i++) {
          args[i - 1] = arguments[i];
        }
        listeners.fn.apply(listeners.context, args);
      } else {
        var length = listeners.length, j;
        for (i = 0; i < length; i++) {
          if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true);
          switch (len) {
            case 1:
              listeners[i].fn.call(listeners[i].context);
              break;
            case 2:
              listeners[i].fn.call(listeners[i].context, a1);
              break;
            case 3:
              listeners[i].fn.call(listeners[i].context, a1, a2);
              break;
            case 4:
              listeners[i].fn.call(listeners[i].context, a1, a2, a3);
              break;
            default:
              if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
                args[j - 1] = arguments[j];
              }
              listeners[i].fn.apply(listeners[i].context, args);
          }
        }
      }
      return true;
    };
    EventEmitter2.prototype.on = function on3(event, fn, context) {
      return addListener(this, event, fn, context, false);
    };
    EventEmitter2.prototype.once = function once(event, fn, context) {
      return addListener(this, event, fn, context, true);
    };
    EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
      var evt = prefix ? prefix + event : event;
      if (!this._events[evt]) return this;
      if (!fn) {
        clearEvent(this, evt);
        return this;
      }
      var listeners = this._events[evt];
      if (listeners.fn) {
        if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
          clearEvent(this, evt);
        }
      } else {
        for (var i = 0, events = [], length = listeners.length; i < length; i++) {
          if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
            events.push(listeners[i]);
          }
        }
        if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
        else clearEvent(this, evt);
      }
      return this;
    };
    EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
      var evt;
      if (event) {
        evt = prefix ? prefix + event : event;
        if (this._events[evt]) clearEvent(this, evt);
      } else {
        this._events = new Events3();
        this._eventsCount = 0;
      }
      return this;
    };
    EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
    EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
    EventEmitter2.prefixed = prefix;
    EventEmitter2.EventEmitter = EventEmitter2;
    {
      module.exports = EventEmitter2;
    }
  })(eventemitter3);
  return eventemitter3.exports;
}
var eventemitter3Exports = requireEventemitter3();
var EventEmitter = /* @__PURE__ */ getDefaultExportFromCjs(eventemitter3Exports);
var version = "1.6.1";
var workerStore = {};
function hasUMDWorker() {
  return typeof __HLS_WORKER_BUNDLE__ === "function";
}
function injectWorker() {
  const workerContext = workerStore[version];
  if (workerContext) {
    workerContext.clientCount++;
    return workerContext;
  }
  const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
    type: "text/javascript"
  });
  const objectURL = self.URL.createObjectURL(blob);
  const worker = new self.Worker(objectURL);
  const result = {
    worker,
    objectURL,
    clientCount: 1
  };
  workerStore[version] = result;
  return result;
}
function loadWorker(path) {
  const workerContext = workerStore[path];
  if (workerContext) {
    workerContext.clientCount++;
    return workerContext;
  }
  const scriptURL = new self.URL(path, self.location.href).href;
  const worker = new self.Worker(scriptURL);
  const result = {
    worker,
    scriptURL,
    clientCount: 1
  };
  workerStore[path] = result;
  return result;
}
function removeWorkerFromStore(path) {
  const workerContext = workerStore[path || version];
  if (workerContext) {
    const clientCount = workerContext.clientCount--;
    if (clientCount === 1) {
      const {
        worker,
        objectURL
      } = workerContext;
      delete workerStore[path || version];
      if (objectURL) {
        self.URL.revokeObjectURL(objectURL);
      }
      worker.terminate();
    }
  }
}
function isId3Footer(data, offset) {
  if (offset + 10 <= data.length) {
    if (data[offset] === 51 && data[offset + 1] === 68 && data[offset + 2] === 73) {
      if (data[offset + 3] < 255 && data[offset + 4] < 255) {
        if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
          return true;
        }
      }
    }
  }
  return false;
}
function isId3Header(data, offset) {
  if (offset + 10 <= data.length) {
    if (data[offset] === 73 && data[offset + 1] === 68 && data[offset + 2] === 51) {
      if (data[offset + 3] < 255 && data[offset + 4] < 255) {
        if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
          return true;
        }
      }
    }
  }
  return false;
}
function readId3Size(data, offset) {
  let size = 0;
  size = (data[offset] & 127) << 21;
  size |= (data[offset + 1] & 127) << 14;
  size |= (data[offset + 2] & 127) << 7;
  size |= data[offset + 3] & 127;
  return size;
}
function getId3Data(data, offset) {
  const front = offset;
  let length = 0;
  while (isId3Header(data, offset)) {
    length += 10;
    const size = readId3Size(data, offset + 6);
    length += size;
    if (isId3Footer(data, offset + 10)) {
      length += 10;
    }
    offset += length;
  }
  if (length > 0) {
    return data.subarray(front, front + length);
  }
  return void 0;
}
function getAudioConfig(observer, data, offset, manifestCodec) {
  const adtsSamplingRates = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
  const byte2 = data[offset + 2];
  const adtsSamplingIndex = byte2 >> 2 & 15;
  if (adtsSamplingIndex > 12) {
    const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);
    observer.emit(Events.ERROR, Events.ERROR, {
      type: ErrorTypes.MEDIA_ERROR,
      details: ErrorDetails.FRAG_PARSING_ERROR,
      fatal: true,
      error,
      reason: error.message
    });
    return;
  }
  const adtsObjectType = (byte2 >> 6 & 3) + 1;
  const channelCount = data[offset + 3] >> 6 & 3 | (byte2 & 1) << 2;
  const codec = "mp4a.40." + adtsObjectType;
  const samplerate = adtsSamplingRates[adtsSamplingIndex];
  let aacSampleIndex = adtsSamplingIndex;
  if (adtsObjectType === 5 || adtsObjectType === 29) {
    aacSampleIndex -= 3;
  }
  const config = [adtsObjectType << 3 | (aacSampleIndex & 14) >> 1, (aacSampleIndex & 1) << 7 | channelCount << 3];
  logger.log(`manifest codec:${manifestCodec}, parsed codec:${codec}, channels:${channelCount}, rate:${samplerate} (ADTS object type:${adtsObjectType} sampling index:${adtsSamplingIndex})`);
  return {
    config,
    samplerate,
    channelCount,
    codec,
    parsedCodec: codec,
    manifestCodec
  };
}
function isHeaderPattern$1(data, offset) {
  return data[offset] === 255 && (data[offset + 1] & 246) === 240;
}
function getHeaderLength(data, offset) {
  return data[offset + 1] & 1 ? 7 : 9;
}
function getFullFrameLength(data, offset) {
  return (data[offset + 3] & 3) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 224) >>> 5;
}
function canGetFrameLength(data, offset) {
  return offset + 5 < data.length;
}
function isHeader$1(data, offset) {
  return offset + 1 < data.length && isHeaderPattern$1(data, offset);
}
function canParse$1(data, offset) {
  return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
}
function probe$1(data, offset) {
  if (isHeader$1(data, offset)) {
    const headerLength = getHeaderLength(data, offset);
    if (offset + headerLength >= data.length) {
      return false;
    }
    const frameLength = getFullFrameLength(data, offset);
    if (frameLength <= headerLength) {
      return false;
    }
    const newOffset = offset + frameLength;
    return newOffset === data.length || isHeader$1(data, newOffset);
  }
  return false;
}
function initTrackConfig(track, observer, data, offset, audioCodec) {
  if (!track.samplerate) {
    const config = getAudioConfig(observer, data, offset, audioCodec);
    if (!config) {
      return;
    }
    _extends(track, config);
  }
}
function getFrameDuration(samplerate) {
  return 1024 * 9e4 / samplerate;
}
function parseFrameHeader(data, offset) {
  const headerLength = getHeaderLength(data, offset);
  if (offset + headerLength <= data.length) {
    const frameLength = getFullFrameLength(data, offset) - headerLength;
    if (frameLength > 0) {
      return {
        headerLength,
        frameLength
      };
    }
  }
}
function appendFrame$2(track, data, offset, pts, frameIndex) {
  const frameDuration = getFrameDuration(track.samplerate);
  const stamp = pts + frameIndex * frameDuration;
  const header = parseFrameHeader(data, offset);
  let unit;
  if (header) {
    const {
      frameLength,
      headerLength
    } = header;
    const _length = headerLength + frameLength;
    const missing = Math.max(0, offset + _length - data.length);
    if (missing) {
      unit = new Uint8Array(_length - headerLength);
      unit.set(data.subarray(offset + headerLength, data.length), 0);
    } else {
      unit = data.subarray(offset + headerLength, offset + _length);
    }
    const _sample = {
      unit,
      pts: stamp
    };
    if (!missing) {
      track.samples.push(_sample);
    }
    return {
      sample: _sample,
      length: _length,
      missing
    };
  }
  const length = data.length - offset;
  unit = new Uint8Array(length);
  unit.set(data.subarray(offset, data.length), 0);
  const sample = {
    unit,
    pts: stamp
  };
  return {
    sample,
    length,
    missing: -1
  };
}
function canParseId3(data, offset) {
  return isId3Header(data, offset) && readId3Size(data, offset + 6) + 10 <= data.length - offset;
}
function decodeId3PrivFrame(frame) {
  if (frame.size < 2) {
    return void 0;
  }
  const owner = utf8ArrayToStr(frame.data, true);
  const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  return {
    key: frame.type,
    info: owner,
    data: privateData.buffer
  };
}
function decodeId3TextFrame(frame) {
  if (frame.size < 2) {
    return void 0;
  }
  if (frame.type === "TXXX") {
    let index = 1;
    const description = utf8ArrayToStr(frame.data.subarray(index), true);
    index += description.length + 1;
    const value = utf8ArrayToStr(frame.data.subarray(index));
    return {
      key: frame.type,
      info: description,
      data: value
    };
  }
  const text = utf8ArrayToStr(frame.data.subarray(1));
  return {
    key: frame.type,
    info: "",
    data: text
  };
}
function decodeId3UrlFrame(frame) {
  if (frame.type === "WXXX") {
    if (frame.size < 2) {
      return void 0;
    }
    let index = 1;
    const description = utf8ArrayToStr(frame.data.subarray(index), true);
    index += description.length + 1;
    const value = utf8ArrayToStr(frame.data.subarray(index));
    return {
      key: frame.type,
      info: description,
      data: value
    };
  }
  const url = utf8ArrayToStr(frame.data);
  return {
    key: frame.type,
    info: "",
    data: url
  };
}
function base64encode(binary) {
  return btoa(String.fromCharCode(...binary));
}
function roundToEven(value, precision) {
  if (value < 0) {
    return -roundToEven(-value, precision);
  }
  const decimalShift = Math.pow(10, precision);
  const isEquidistant = Math.abs(value * decimalShift % 1 - 0.5) < Number.EPSILON;
  if (isEquidistant) {
    const flooredValue = Math.floor(value * decimalShift);
    return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;
  } else {
    return Math.round(value * decimalShift) / decimalShift;
  }
}
function urlToRelativePath(url, base) {
  const to = new URL(url);
  const from3 = new URL(base);
  if (to.origin !== from3.origin) {
    return url;
  }
  const toPath = to.pathname.split("/").slice(1);
  const fromPath = from3.pathname.split("/").slice(1, -1);
  while (toPath[0] === fromPath[0]) {
    toPath.shift();
    fromPath.shift();
  }
  while (fromPath.length) {
    fromPath.shift();
    toPath.unshift("..");
  }
  return toPath.join("/");
}
function uuid() {
  try {
    return crypto.randomUUID();
  } catch (error) {
    try {
      const url = URL.createObjectURL(new Blob());
      const uuid2 = url.toString();
      URL.revokeObjectURL(url);
      return uuid2.slice(uuid2.lastIndexOf("/") + 1);
    } catch (error2) {
      let dt = (/* @__PURE__ */ new Date()).getTime();
      const uuid2 = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
        const r2 = (dt + Math.random() * 16) % 16 | 0;
        dt = Math.floor(dt / 16);
        return (c == "x" ? r2 : r2 & 3 | 8).toString(16);
      });
      return uuid2;
    }
  }
}
function toArrayBuffer(view2) {
  if (view2 instanceof ArrayBuffer) {
    return view2;
  } else {
    if (view2.byteOffset == 0 && view2.byteLength == view2.buffer.byteLength) {
      return view2.buffer;
    }
    return new Uint8Array(view2).buffer;
  }
}
function toUint8(data, offset = 0, length = Infinity) {
  return view(data, offset, length, Uint8Array);
}
function view(data, offset, length, Type) {
  const buffer = unsafeGetArrayBuffer(data);
  let bytesPerElement = 1;
  if ("BYTES_PER_ELEMENT" in Type) {
    bytesPerElement = Type.BYTES_PER_ELEMENT;
  }
  const dataOffset = isArrayBufferView(data) ? data.byteOffset : 0;
  const dataEnd = (dataOffset + data.byteLength) / bytesPerElement;
  const rawStart = (dataOffset + offset) / bytesPerElement;
  const start2 = Math.floor(Math.max(0, Math.min(rawStart, dataEnd)));
  const end = Math.floor(Math.min(start2 + Math.max(length, 0), dataEnd));
  return new Type(buffer, start2, end - start2);
}
function unsafeGetArrayBuffer(view2) {
  if (view2 instanceof ArrayBuffer) {
    return view2;
  } else {
    return view2.buffer;
  }
}
function isArrayBufferView(obj) {
  return obj && obj.buffer instanceof ArrayBuffer && obj.byteLength !== void 0 && obj.byteOffset !== void 0;
}
function decodeId3ImageFrame(frame) {
  const metadataFrame = {
    key: frame.type,
    description: "",
    data: "",
    mimeType: null,
    pictureType: null
  };
  const utf8Encoding = 3;
  if (frame.size < 2) {
    return void 0;
  }
  if (frame.data[0] !== utf8Encoding) {
    console.log("Ignore frame with unrecognized character encoding");
    return void 0;
  }
  const mimeTypeEndIndex = frame.data.subarray(1).indexOf(0);
  if (mimeTypeEndIndex === -1) {
    return void 0;
  }
  const mimeType = utf8ArrayToStr(toUint8(frame.data, 1, mimeTypeEndIndex));
  const pictureType = frame.data[2 + mimeTypeEndIndex];
  const descriptionEndIndex = frame.data.subarray(3 + mimeTypeEndIndex).indexOf(0);
  if (descriptionEndIndex === -1) {
    return void 0;
  }
  const description = utf8ArrayToStr(toUint8(frame.data, 3 + mimeTypeEndIndex, descriptionEndIndex));
  let data;
  if (mimeType === "-->") {
    data = utf8ArrayToStr(toUint8(frame.data, 4 + mimeTypeEndIndex + descriptionEndIndex));
  } else {
    data = toArrayBuffer(frame.data.subarray(4 + mimeTypeEndIndex + descriptionEndIndex));
  }
  metadataFrame.mimeType = mimeType;
  metadataFrame.pictureType = pictureType;
  metadataFrame.description = description;
  metadataFrame.data = data;
  return metadataFrame;
}
function decodeId3Frame(frame) {
  if (frame.type === "PRIV") {
    return decodeId3PrivFrame(frame);
  } else if (frame.type[0] === "W") {
    return decodeId3UrlFrame(frame);
  } else if (frame.type === "APIC") {
    return decodeId3ImageFrame(frame);
  }
  return decodeId3TextFrame(frame);
}
function getId3FrameData(data) {
  const type2 = String.fromCharCode(data[0], data[1], data[2], data[3]);
  const size = readId3Size(data, 4);
  const offset = 10;
  return {
    type: type2,
    size,
    data: data.subarray(offset, offset + size)
  };
}
var HEADER_FOOTER_SIZE = 10;
var FRAME_SIZE = 10;
function getId3Frames(id3Data) {
  let offset = 0;
  const frames = [];
  while (isId3Header(id3Data, offset)) {
    const size = readId3Size(id3Data, offset + 6);
    if (id3Data[offset + 5] >> 6 & 1) {
      offset += HEADER_FOOTER_SIZE;
    }
    offset += HEADER_FOOTER_SIZE;
    const end = offset + size;
    while (offset + FRAME_SIZE < end) {
      const frameData = getId3FrameData(id3Data.subarray(offset));
      const frame = decodeId3Frame(frameData);
      if (frame) {
        frames.push(frame);
      }
      offset += frameData.size + HEADER_FOOTER_SIZE;
    }
    if (isId3Footer(id3Data, offset)) {
      offset += HEADER_FOOTER_SIZE;
    }
  }
  return frames;
}
function isId3TimestampFrame(frame) {
  return frame && frame.key === "PRIV" && frame.info === "com.apple.streaming.transportStreamTimestamp";
}
function readId3Timestamp(timeStampFrame) {
  if (timeStampFrame.data.byteLength === 8) {
    const data = new Uint8Array(timeStampFrame.data);
    const pts33Bit = data[3] & 1;
    let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
    timestamp /= 45;
    if (pts33Bit) {
      timestamp += 4772185884e-2;
    }
    return Math.round(timestamp);
  }
  return void 0;
}
function getId3Timestamp(data) {
  const frames = getId3Frames(data);
  for (let i = 0; i < frames.length; i++) {
    const frame = frames[i];
    if (isId3TimestampFrame(frame)) {
      return readId3Timestamp(frame);
    }
  }
  return void 0;
}
var MetadataSchema = /* @__PURE__ */ function(MetadataSchema2) {
  MetadataSchema2["audioId3"] = "org.id3";
  MetadataSchema2["dateRange"] = "com.apple.quicktime.HLS";
  MetadataSchema2["emsg"] = "https://aomedia.org/emsg/ID3";
  MetadataSchema2["misbklv"] = "urn:misb:KLV:bin:1910.1";
  return MetadataSchema2;
}({});
function dummyTrack(type2 = "", inputTimeScale = 9e4) {
  return {
    type: type2,
    id: -1,
    pid: -1,
    inputTimeScale,
    sequenceNumber: -1,
    samples: [],
    dropped: 0
  };
}
var BaseAudioDemuxer = class {
  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(initSegment, audioCodec, videoCodec, trackDuration) {
    this._id3Track = {
      type: "id3",
      id: 3,
      pid: -1,
      inputTimeScale: 9e4,
      sequenceNumber: 0,
      samples: [],
      dropped: 0
    };
  }
  resetTimeStamp(deaultTimestamp) {
    this.initPTS = deaultTimestamp;
    this.resetContiguity();
  }
  resetContiguity() {
    this.basePTS = null;
    this.lastPTS = null;
    this.frameIndex = 0;
  }
  canParse(data, offset) {
    return false;
  }
  appendFrame(track, data, offset) {
  }
  // feed incoming data to the front of the parsing pipeline
  demux(data, timeOffset) {
    if (this.cachedData) {
      data = appendUint8Array(this.cachedData, data);
      this.cachedData = null;
    }
    let id3Data = getId3Data(data, 0);
    let offset = id3Data ? id3Data.length : 0;
    let lastDataIndex;
    const track = this._audioTrack;
    const id3Track = this._id3Track;
    const timestamp = id3Data ? getId3Timestamp(id3Data) : void 0;
    const length = data.length;
    if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
      this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
      this.lastPTS = this.basePTS;
    }
    if (this.lastPTS === null) {
      this.lastPTS = this.basePTS;
    }
    if (id3Data && id3Data.length > 0) {
      id3Track.samples.push({
        pts: this.lastPTS,
        dts: this.lastPTS,
        data: id3Data,
        type: MetadataSchema.audioId3,
        duration: Number.POSITIVE_INFINITY
      });
    }
    while (offset < length) {
      if (this.canParse(data, offset)) {
        const frame = this.appendFrame(track, data, offset);
        if (frame) {
          this.frameIndex++;
          this.lastPTS = frame.sample.pts;
          offset += frame.length;
          lastDataIndex = offset;
        } else {
          offset = length;
        }
      } else if (canParseId3(data, offset)) {
        id3Data = getId3Data(data, offset);
        id3Track.samples.push({
          pts: this.lastPTS,
          dts: this.lastPTS,
          data: id3Data,
          type: MetadataSchema.audioId3,
          duration: Number.POSITIVE_INFINITY
        });
        offset += id3Data.length;
        lastDataIndex = offset;
      } else {
        offset++;
      }
      if (offset === length && lastDataIndex !== length) {
        const partialData = data.slice(lastDataIndex);
        if (this.cachedData) {
          this.cachedData = appendUint8Array(this.cachedData, partialData);
        } else {
          this.cachedData = partialData;
        }
      }
    }
    return {
      audioTrack: track,
      videoTrack: dummyTrack(),
      id3Track,
      textTrack: dummyTrack()
    };
  }
  demuxSampleAes(data, keyData, timeOffset) {
    return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  }
  flush(timeOffset) {
    const cachedData = this.cachedData;
    if (cachedData) {
      this.cachedData = null;
      this.demux(cachedData, 0);
    }
    return {
      audioTrack: this._audioTrack,
      videoTrack: dummyTrack(),
      id3Track: this._id3Track,
      textTrack: dummyTrack()
    };
  }
  destroy() {
    this.cachedData = null;
    this._audioTrack = this._id3Track = void 0;
  }
};
var initPTSFn = (timestamp, timeOffset, initPTS) => {
  if (isFiniteNumber(timestamp)) {
    return timestamp * 90;
  }
  const init90kHz = initPTS ? initPTS.baseTime * 9e4 / initPTS.timescale : 0;
  return timeOffset * 9e4 + init90kHz;
};
var chromeVersion$1 = null;
var BitratesMap = [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];
var SamplingRateMap = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3];
var SamplesCoefficients = [
  // 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
  ]
];
var BytesInSlot = [
  0,
  // Reserved
  1,
  // Layer3
  1,
  // Layer2
  4
  // Layer1
];
function appendFrame$1(track, data, offset, pts, frameIndex) {
  if (offset + 24 > data.length) {
    return;
  }
  const header = parseHeader(data, offset);
  if (header && offset + header.frameLength <= data.length) {
    const frameDuration = header.samplesPerFrame * 9e4 / header.sampleRate;
    const stamp = pts + frameIndex * frameDuration;
    const sample = {
      unit: data.subarray(offset, offset + header.frameLength),
      pts: stamp,
      dts: stamp
    };
    track.config = [];
    track.channelCount = header.channelCount;
    track.samplerate = header.sampleRate;
    track.samples.push(sample);
    return {
      sample,
      length: header.frameLength,
      missing: 0
    };
  }
}
function parseHeader(data, offset) {
  const mpegVersion = data[offset + 1] >> 3 & 3;
  const mpegLayer = data[offset + 1] >> 1 & 3;
  const bitRateIndex = data[offset + 2] >> 4 & 15;
  const sampleRateIndex = data[offset + 2] >> 2 & 3;
  if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
    const paddingBit = data[offset + 2] >> 1 & 1;
    const channelMode = data[offset + 3] >> 6;
    const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
    const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1e3;
    const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
    const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
    const channelCount = channelMode === 3 ? 1 : 2;
    const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
    const bytesInSlot = BytesInSlot[mpegLayer];
    const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
    const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
    if (chromeVersion$1 === null) {
      const userAgent = navigator.userAgent || "";
      const result = userAgent.match(/Chrome\/(\d+)/i);
      chromeVersion$1 = result ? parseInt(result[1]) : 0;
    }
    const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
    if (needChromeFix && mpegLayer === 2 && bitRate >= 224e3 && channelMode === 0) {
      data[offset + 3] = data[offset + 3] | 128;
    }
    return {
      sampleRate,
      channelCount,
      frameLength,
      samplesPerFrame
    };
  }
}
function isHeaderPattern(data, offset) {
  return data[offset] === 255 && (data[offset + 1] & 224) === 224 && (data[offset + 1] & 6) !== 0;
}
function isHeader(data, offset) {
  return offset + 1 < data.length && isHeaderPattern(data, offset);
}
function canParse(data, offset) {
  const headerSize = 4;
  return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
}
function probe(data, offset) {
  if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
    const headerLength = 4;
    const header = parseHeader(data, offset);
    let frameLength = headerLength;
    if (header != null && header.frameLength) {
      frameLength = header.frameLength;
    }
    const newOffset = offset + frameLength;
    return newOffset === data.length || isHeader(data, newOffset);
  }
  return false;
}
var AACDemuxer = class extends BaseAudioDemuxer {
  constructor(observer, config) {
    super();
    this.observer = void 0;
    this.config = void 0;
    this.observer = observer;
    this.config = config;
  }
  resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
    super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
    this._audioTrack = {
      container: "audio/adts",
      type: "audio",
      id: 2,
      pid: -1,
      sequenceNumber: 0,
      segmentCodec: "aac",
      samples: [],
      manifestCodec: audioCodec,
      duration: trackDuration,
      inputTimeScale: 9e4,
      dropped: 0
    };
  }
  // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  static probe(data, logger4) {
    if (!data) {
      return false;
    }
    const id3Data = getId3Data(data, 0);
    let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
    if (probe(data, offset)) {
      return false;
    }
    for (let length = data.length; offset < length; offset++) {
      if (probe$1(data, offset)) {
        logger4.log("ADTS sync word found !");
        return true;
      }
    }
    return false;
  }
  canParse(data, offset) {
    return canParse$1(data, offset);
  }
  appendFrame(track, data, offset) {
    initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
    const frame = appendFrame$2(track, data, offset, this.basePTS, this.frameIndex);
    if (frame && frame.missing === 0) {
      return frame;
    }
  }
};
var getAudioBSID = (data, offset) => {
  let bsid = 0;
  let numBits = 5;
  offset += numBits;
  const temp = new Uint32Array(1);
  const mask = new Uint32Array(1);
  const byte = new Uint8Array(1);
  while (numBits > 0) {
    byte[0] = data[offset];
    const bits = Math.min(numBits, 8);
    const shift = 8 - bits;
    mask[0] = 4278190080 >>> 24 + shift << shift;
    temp[0] = (byte[0] & mask[0]) >> shift;
    bsid = !bsid ? temp[0] : bsid << bits | temp[0];
    offset += 1;
    numBits -= bits;
  }
  return bsid;
};
var AC3Demuxer = class extends BaseAudioDemuxer {
  constructor(observer) {
    super();
    this.observer = void 0;
    this.observer = observer;
  }
  resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
    super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
    this._audioTrack = {
      container: "audio/ac-3",
      type: "audio",
      id: 2,
      pid: -1,
      sequenceNumber: 0,
      segmentCodec: "ac3",
      samples: [],
      manifestCodec: audioCodec,
      duration: trackDuration,
      inputTimeScale: 9e4,
      dropped: 0
    };
  }
  canParse(data, offset) {
    return offset + 64 < data.length;
  }
  appendFrame(track, data, offset) {
    const frameLength = appendFrame(track, data, offset, this.basePTS, this.frameIndex);
    if (frameLength !== -1) {
      const sample = track.samples[track.samples.length - 1];
      return {
        sample,
        length: frameLength,
        missing: 0
      };
    }
  }
  static probe(data) {
    if (!data) {
      return false;
    }
    const id3Data = getId3Data(data, 0);
    if (!id3Data) {
      return false;
    }
    const offset = id3Data.length;
    if (data[offset] === 11 && data[offset + 1] === 119 && getId3Timestamp(id3Data) !== void 0 && // check the bsid to confirm ac-3
    getAudioBSID(data, offset) < 16) {
      return true;
    }
    return false;
  }
};
function appendFrame(track, data, start2, pts, frameIndex) {
  if (start2 + 8 > data.length) {
    return -1;
  }
  if (data[start2] !== 11 || data[start2 + 1] !== 119) {
    return -1;
  }
  const samplingRateCode = data[start2 + 4] >> 6;
  if (samplingRateCode >= 3) {
    return -1;
  }
  const samplingRateMap = [48e3, 44100, 32e3];
  const sampleRate = samplingRateMap[samplingRateCode];
  const frameSizeCode = data[start2 + 4] & 63;
  const frameSizeMap = [64, 69, 96, 64, 70, 96, 80, 87, 120, 80, 88, 120, 96, 104, 144, 96, 105, 144, 112, 121, 168, 112, 122, 168, 128, 139, 192, 128, 140, 192, 160, 174, 240, 160, 175, 240, 192, 208, 288, 192, 209, 288, 224, 243, 336, 224, 244, 336, 256, 278, 384, 256, 279, 384, 320, 348, 480, 320, 349, 480, 384, 417, 576, 384, 418, 576, 448, 487, 672, 448, 488, 672, 512, 557, 768, 512, 558, 768, 640, 696, 960, 640, 697, 960, 768, 835, 1152, 768, 836, 1152, 896, 975, 1344, 896, 976, 1344, 1024, 1114, 1536, 1024, 1115, 1536, 1152, 1253, 1728, 1152, 1254, 1728, 1280, 1393, 1920, 1280, 1394, 1920];
  const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;
  if (start2 + frameLength > data.length) {
    return -1;
  }
  const channelMode = data[start2 + 6] >> 5;
  let skipCount = 0;
  if (channelMode === 2) {
    skipCount += 2;
  } else {
    if (channelMode & 1 && channelMode !== 1) {
      skipCount += 2;
    }
    if (channelMode & 4) {
      skipCount += 2;
    }
  }
  const lfeon = (data[start2 + 6] << 8 | data[start2 + 7]) >> 12 - skipCount & 1;
  const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];
  const channelCount = channelsMap[channelMode] + lfeon;
  const bsid = data[start2 + 5] >> 3;
  const bsmod = data[start2 + 5] & 7;
  const config = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 224]);
  const frameDuration = 1536 / sampleRate * 9e4;
  const stamp = pts + frameIndex * frameDuration;
  const unit = data.subarray(start2, start2 + frameLength);
  track.config = config;
  track.channelCount = channelCount;
  track.samplerate = sampleRate;
  track.samples.push({
    unit,
    pts: stamp
  });
  return frameLength;
}
var MP3Demuxer = class extends BaseAudioDemuxer {
  resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
    super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
    this._audioTrack = {
      container: "audio/mpeg",
      type: "audio",
      id: 2,
      pid: -1,
      sequenceNumber: 0,
      segmentCodec: "mp3",
      samples: [],
      manifestCodec: audioCodec,
      duration: trackDuration,
      inputTimeScale: 9e4,
      dropped: 0
    };
  }
  static probe(data) {
    if (!data) {
      return false;
    }
    const id3Data = getId3Data(data, 0);
    let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
    if (id3Data && data[offset] === 11 && data[offset + 1] === 119 && getId3Timestamp(id3Data) !== void 0 && // check the bsid to confirm ac-3 or ec-3 (not mp3)
    getAudioBSID(data, offset) <= 16) {
      return false;
    }
    for (let length = data.length; offset < length; offset++) {
      if (probe(data, offset)) {
        logger.log("MPEG Audio sync word found !");
        return true;
      }
    }
    return false;
  }
  canParse(data, offset) {
    return canParse(data, offset);
  }
  appendFrame(track, data, offset) {
    if (this.basePTS === null) {
      return;
    }
    return appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  }
};
var emsgSchemePattern = /\/emsg[-/]ID3/i;
var MP4Demuxer = class {
  constructor(observer, config) {
    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 = config;
  }
  resetTimeStamp() {
  }
  resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
    const videoTrack = this.videoTrack = dummyTrack("video", 1);
    const audioTrack = this.audioTrack = dummyTrack("audio", 1);
    const captionTrack = this.txtTrack = dummyTrack("text", 1);
    this.id3Track = dummyTrack("id3", 1);
    this.timeOffset = 0;
    if (!(initSegment != null && initSegment.byteLength)) {
      return;
    }
    const initData = parseInitSegment(initSegment);
    if (initData.video) {
      const {
        id,
        timescale: timescale2,
        codec,
        supplemental
      } = initData.video;
      videoTrack.id = id;
      videoTrack.timescale = captionTrack.timescale = timescale2;
      videoTrack.codec = codec;
      videoTrack.supplemental = supplemental;
    }
    if (initData.audio) {
      const {
        id,
        timescale: timescale2,
        codec
      } = initData.audio;
      audioTrack.id = id;
      audioTrack.timescale = timescale2;
      audioTrack.codec = codec;
    }
    captionTrack.id = RemuxerTrackIdConfig.text;
    videoTrack.sampleDuration = 0;
    videoTrack.duration = audioTrack.duration = trackDuration;
  }
  resetContiguity() {
    this.remainderData = null;
  }
  static probe(data) {
    return hasMoofData(data);
  }
  demux(data, timeOffset) {
    this.timeOffset = timeOffset;
    let videoSamples = data;
    const videoTrack = this.videoTrack;
    const textTrack = this.txtTrack;
    if (this.config.progressive) {
      if (this.remainderData) {
        videoSamples = appendUint8Array(this.remainderData, data);
      }
      const segmentedData = segmentValidRange(videoSamples);
      this.remainderData = segmentedData.remainder;
      videoTrack.samples = segmentedData.valid || new Uint8Array();
    } else {
      videoTrack.samples = videoSamples;
    }
    const id3Track = this.extractID3Track(videoTrack, timeOffset);
    textTrack.samples = parseSamples(timeOffset, videoTrack);
    return {
      videoTrack,
      audioTrack: this.audioTrack,
      id3Track,
      textTrack: this.txtTrack
    };
  }
  flush() {
    const timeOffset = this.timeOffset;
    const videoTrack = this.videoTrack;
    const textTrack = this.txtTrack;
    videoTrack.samples = this.remainderData || new Uint8Array();
    this.remainderData = null;
    const id3Track = this.extractID3Track(videoTrack, this.timeOffset);
    textTrack.samples = parseSamples(timeOffset, videoTrack);
    return {
      videoTrack,
      audioTrack: dummyTrack(),
      id3Track,
      textTrack: dummyTrack()
    };
  }
  extractID3Track(videoTrack, timeOffset) {
    const id3Track = this.id3Track;
    if (videoTrack.samples.length) {
      const emsgs = findBox(videoTrack.samples, ["emsg"]);
      if (emsgs) {
        emsgs.forEach((data) => {
          const emsgInfo = parseEmsg(data);
          if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
            const pts = getEmsgStartTime(emsgInfo, timeOffset);
            let duration5 = emsgInfo.eventDuration === 4294967295 ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
            if (duration5 <= 1e-3) {
              duration5 = Number.POSITIVE_INFINITY;
            }
            const payload = emsgInfo.payload;
            id3Track.samples.push({
              data: payload,
              len: payload.byteLength,
              dts: pts,
              pts,
              type: MetadataSchema.emsg,
              duration: duration5
            });
          } else if (this.config.enableEmsgKLVMetadata && emsgInfo.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")) {
            const pts = getEmsgStartTime(emsgInfo, timeOffset);
            id3Track.samples.push({
              data: emsgInfo.payload,
              len: emsgInfo.payload.byteLength,
              dts: pts,
              pts,
              type: MetadataSchema.misbklv,
              duration: Number.POSITIVE_INFINITY
            });
          }
        });
      }
    }
    return id3Track;
  }
  demuxSampleAes(data, keyData, timeOffset) {
    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 getEmsgStartTime(emsgInfo, timeOffset) {
  return isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
}
var SampleAesDecrypter = class {
  constructor(observer, config, keyData) {
    this.keyData = void 0;
    this.decrypter = void 0;
    this.keyData = keyData;
    this.decrypter = new Decrypter(config, {
      removePKCS7Padding: false
    });
  }
  decryptBuffer(encryptedData) {
    return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, DecrypterAesMode.cbc);
  }
  // AAC - encrypt all full 16 bytes blocks starting from offset 16
  decryptAacSample(samples, sampleIndex, callback2) {
    const curUnit = samples[sampleIndex].unit;
    if (curUnit.length <= 16) {
      return;
    }
    const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
    const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
    this.decryptBuffer(encryptedBuffer).then((decryptedBuffer) => {
      const decryptedData = new Uint8Array(decryptedBuffer);
      curUnit.set(decryptedData, 16);
      if (!this.decrypter.isSync()) {
        this.decryptAacSamples(samples, sampleIndex + 1, callback2);
      }
    });
  }
  decryptAacSamples(samples, sampleIndex, callback2) {
    for (; ; sampleIndex++) {
      if (sampleIndex >= samples.length) {
        callback2();
        return;
      }
      if (samples[sampleIndex].unit.length < 32) {
        continue;
      }
      this.decryptAacSample(samples, sampleIndex, callback2);
      if (!this.decrypter.isSync()) {
        return;
      }
    }
  }
  // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  getAvcEncryptedData(decodedData) {
    const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
    const encryptedData = new Int8Array(encryptedDataLen);
    let outputPos = 0;
    for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
      encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
    }
    return encryptedData;
  }
  getAvcDecryptedUnit(decodedData, decryptedData) {
    const uint8DecryptedData = new Uint8Array(decryptedData);
    let inputPos = 0;
    for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
      decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
    }
    return decodedData;
  }
  decryptAvcSample(samples, sampleIndex, unitIndex, callback2, curUnit) {
    const decodedData = discardEPB(curUnit.data);
    const encryptedData = this.getAvcEncryptedData(decodedData);
    this.decryptBuffer(encryptedData.buffer).then((decryptedBuffer) => {
      curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);
      if (!this.decrypter.isSync()) {
        this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback2);
      }
    });
  }
  decryptAvcSamples(samples, sampleIndex, unitIndex, callback2) {
    if (samples instanceof Uint8Array) {
      throw new Error("Cannot decrypt samples of type Uint8Array");
    }
    for (; ; sampleIndex++, unitIndex = 0) {
      if (sampleIndex >= samples.length) {
        callback2();
        return;
      }
      const curUnits = samples[sampleIndex].units;
      for (; ; unitIndex++) {
        if (unitIndex >= curUnits.length) {
          break;
        }
        const curUnit = curUnits[unitIndex];
        if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
          continue;
        }
        this.decryptAvcSample(samples, sampleIndex, unitIndex, callback2, curUnit);
        if (!this.decrypter.isSync()) {
          return;
        }
      }
    }
  }
};
var BaseVideoParser = class {
  constructor() {
    this.VideoSample = null;
  }
  createVideoSample(key, pts, dts) {
    return {
      key,
      frame: false,
      pts,
      dts,
      units: [],
      length: 0
    };
  }
  getLastNalUnit(samples) {
    var _VideoSample;
    let VideoSample = this.VideoSample;
    let lastUnit;
    if (!VideoSample || VideoSample.units.length === 0) {
      VideoSample = samples[samples.length - 1];
    }
    if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
      const units = VideoSample.units;
      lastUnit = units[units.length - 1];
    }
    return lastUnit;
  }
  pushAccessUnit(VideoSample, videoTrack) {
    if (VideoSample.units.length && VideoSample.frame) {
      if (VideoSample.pts === void 0) {
        const samples = videoTrack.samples;
        const nbSamples = samples.length;
        if (nbSamples) {
          const lastSample = samples[nbSamples - 1];
          VideoSample.pts = lastSample.pts;
          VideoSample.dts = lastSample.dts;
        } else {
          videoTrack.dropped++;
          return;
        }
      }
      videoTrack.samples.push(VideoSample);
    }
  }
  parseNALu(track, array, endOfSegment) {
    const len = array.byteLength;
    let state = track.naluState || 0;
    const lastState = state;
    const units = [];
    let i = 0;
    let value;
    let overflow;
    let unitType;
    let lastUnitStart = -1;
    let lastUnitType = 0;
    if (state === -1) {
      lastUnitStart = 0;
      lastUnitType = this.getNALuType(array, 0);
      state = 0;
      i = 1;
    }
    while (i < len) {
      value = array[i++];
      if (!state) {
        state = value ? 0 : 1;
        continue;
      }
      if (state === 1) {
        state = value ? 0 : 2;
        continue;
      }
      if (!value) {
        state = 3;
      } else if (value === 1) {
        overflow = i - state - 1;
        if (lastUnitStart >= 0) {
          const unit = {
            data: array.subarray(lastUnitStart, overflow),
            type: lastUnitType
          };
          units.push(unit);
        } else {
          const lastUnit = this.getLastNalUnit(track.samples);
          if (lastUnit) {
            if (lastState && i <= 4 - lastState) {
              if (lastUnit.state) {
                lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
              }
            }
            if (overflow > 0) {
              lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
              lastUnit.state = 0;
            }
          }
        }
        if (i < len) {
          unitType = this.getNALuType(array, i);
          lastUnitStart = i;
          lastUnitType = unitType;
          state = 0;
        } else {
          state = -1;
        }
      } else {
        state = 0;
      }
    }
    if (lastUnitStart >= 0 && state >= 0) {
      const unit = {
        data: array.subarray(lastUnitStart, len),
        type: lastUnitType,
        state
      };
      units.push(unit);
    }
    if (units.length === 0) {
      const lastUnit = this.getLastNalUnit(track.samples);
      if (lastUnit) {
        lastUnit.data = appendUint8Array(lastUnit.data, array);
      }
    }
    track.naluState = state;
    return units;
  }
};
var ExpGolomb = class {
  constructor(data) {
    this.data = void 0;
    this.bytesAvailable = void 0;
    this.word = void 0;
    this.bitsAvailable = void 0;
    this.data = data;
    this.bytesAvailable = data.byteLength;
    this.word = 0;
    this.bitsAvailable = 0;
  }
  // ():void
  loadWord() {
    const data = this.data;
    const bytesAvailable = this.bytesAvailable;
    const position = data.byteLength - bytesAvailable;
    const workingBytes = new Uint8Array(4);
    const availableBytes = Math.min(4, bytesAvailable);
    if (availableBytes === 0) {
      throw new Error("no bytes available");
    }
    workingBytes.set(data.subarray(position, position + availableBytes));
    this.word = new DataView(workingBytes.buffer).getUint32(0);
    this.bitsAvailable = availableBytes * 8;
    this.bytesAvailable -= availableBytes;
  }
  // (count:int):void
  skipBits(count) {
    let skipBytes;
    count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
    if (this.bitsAvailable > count) {
      this.word <<= count;
      this.bitsAvailable -= count;
    } else {
      count -= this.bitsAvailable;
      skipBytes = count >> 3;
      count -= skipBytes << 3;
      this.bytesAvailable -= skipBytes;
      this.loadWord();
      this.word <<= count;
      this.bitsAvailable -= count;
    }
  }
  // (size:int):uint
  readBits(size) {
    let bits = Math.min(this.bitsAvailable, size);
    const valu = this.word >>> 32 - bits;
    if (size > 32) {
      logger.error("Cannot read more than 32 bits at a time");
    }
    this.bitsAvailable -= bits;
    if (this.bitsAvailable > 0) {
      this.word <<= bits;
    } else if (this.bytesAvailable > 0) {
      this.loadWord();
    } else {
      throw new Error("no bits available");
    }
    bits = size - bits;
    if (bits > 0 && this.bitsAvailable) {
      return valu << bits | this.readBits(bits);
    } else {
      return valu;
    }
  }
  // ():uint
  skipLZ() {
    let leadingZeroCount;
    for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
      if ((this.word & 2147483648 >>> leadingZeroCount) !== 0) {
        this.word <<= leadingZeroCount;
        this.bitsAvailable -= leadingZeroCount;
        return leadingZeroCount;
      }
    }
    this.loadWord();
    return leadingZeroCount + this.skipLZ();
  }
  // ():void
  skipUEG() {
    this.skipBits(1 + this.skipLZ());
  }
  // ():void
  skipEG() {
    this.skipBits(1 + this.skipLZ());
  }
  // ():uint
  readUEG() {
    const clz = this.skipLZ();
    return this.readBits(clz + 1) - 1;
  }
  // ():int
  readEG() {
    const valu = this.readUEG();
    if (1 & valu) {
      return 1 + valu >>> 1;
    } else {
      return -1 * (valu >>> 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);
  }
};
var AvcVideoParser = class extends BaseVideoParser {
  parsePES(track, textTrack, pes, endOfSegment) {
    const units = this.parseNALu(track, pes.data, endOfSegment);
    let VideoSample = this.VideoSample;
    let push2;
    let spsfound = false;
    pes.data = null;
    if (VideoSample && units.length && !track.audFound) {
      this.pushAccessUnit(VideoSample, track);
      VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
    }
    units.forEach((unit) => {
      var _VideoSample2, _VideoSample3;
      switch (unit.type) {
        // NDR
        case 1: {
          let iskey = false;
          push2 = true;
          const data = unit.data;
          if (spsfound && data.length > 4) {
            const sliceType = this.readSliceType(data);
            if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
              iskey = true;
            }
          }
          if (iskey) {
            var _VideoSample;
            if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
              this.pushAccessUnit(VideoSample, track);
              VideoSample = this.VideoSample = null;
            }
          }
          if (!VideoSample) {
            VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
          }
          VideoSample.frame = true;
          VideoSample.key = iskey;
          break;
        }
        case 5:
          push2 = true;
          if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
            this.pushAccessUnit(VideoSample, track);
            VideoSample = this.VideoSample = null;
          }
          if (!VideoSample) {
            VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
          }
          VideoSample.key = true;
          VideoSample.frame = true;
          break;
        // SEI
        case 6: {
          push2 = true;
          parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
          break;
        }
        case 7: {
          var _track$pixelRatio, _track$pixelRatio2;
          push2 = true;
          spsfound = true;
          const sps = unit.data;
          const config = this.readSPS(sps);
          if (!track.sps || track.width !== config.width || track.height !== config.height || ((_track$pixelRatio = track.pixelRatio) == null ? void 0 : _track$pixelRatio[0]) !== config.pixelRatio[0] || ((_track$pixelRatio2 = track.pixelRatio) == null ? void 0 : _track$pixelRatio2[1]) !== config.pixelRatio[1]) {
            track.width = config.width;
            track.height = config.height;
            track.pixelRatio = config.pixelRatio;
            track.sps = [sps];
            const codecarray = sps.subarray(1, 4);
            let codecstring = "avc1.";
            for (let i = 0; i < 3; i++) {
              let h = codecarray[i].toString(16);
              if (h.length < 2) {
                h = "0" + h;
              }
              codecstring += h;
            }
            track.codec = codecstring;
          }
          break;
        }
        // PPS
        case 8:
          push2 = true;
          track.pps = [unit.data];
          break;
        // AUD
        case 9:
          push2 = true;
          track.audFound = true;
          if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
            this.pushAccessUnit(VideoSample, track);
            VideoSample = null;
          }
          if (!VideoSample) {
            VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
          }
          break;
        // Filler Data
        case 12:
          push2 = true;
          break;
        default:
          push2 = false;
          break;
      }
      if (VideoSample && push2) {
        const units2 = VideoSample.units;
        units2.push(unit);
      }
    });
    if (endOfSegment && VideoSample) {
      this.pushAccessUnit(VideoSample, track);
      this.VideoSample = null;
    }
  }
  getNALuType(data, offset) {
    return data[offset] & 31;
  }
  readSliceType(data) {
    const eg = new ExpGolomb(data);
    eg.readUByte();
    eg.readUEG();
    return eg.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(count, reader) {
    let lastScale = 8;
    let nextScale = 8;
    let deltaScale;
    for (let j = 0; j < count; j++) {
      if (nextScale !== 0) {
        deltaScale = reader.readEG();
        nextScale = (lastScale + deltaScale + 256) % 256;
      }
      lastScale = nextScale === 0 ? lastScale : nextScale;
    }
  }
  /**
   * 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(sps) {
    const eg = new ExpGolomb(sps);
    let frameCropLeftOffset = 0;
    let frameCropRightOffset = 0;
    let frameCropTopOffset = 0;
    let frameCropBottomOffset = 0;
    let numRefFramesInPicOrderCntCycle;
    let scalingListCount;
    let i;
    const readUByte = eg.readUByte.bind(eg);
    const readBits = eg.readBits.bind(eg);
    const readUEG = eg.readUEG.bind(eg);
    const readBoolean = eg.readBoolean.bind(eg);
    const skipBits = eg.skipBits.bind(eg);
    const skipEG = eg.skipEG.bind(eg);
    const skipUEG = eg.skipUEG.bind(eg);
    const skipScalingList = this.skipScalingList.bind(this);
    readUByte();
    const profileIdc = readUByte();
    readBits(5);
    skipBits(3);
    readUByte();
    skipUEG();
    if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
      const chromaFormatIdc = readUEG();
      if (chromaFormatIdc === 3) {
        skipBits(1);
      }
      skipUEG();
      skipUEG();
      skipBits(1);
      if (readBoolean()) {
        scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
        for (i = 0; i < scalingListCount; i++) {
          if (readBoolean()) {
            if (i < 6) {
              skipScalingList(16, eg);
            } else {
              skipScalingList(64, eg);
            }
          }
        }
      }
    }
    skipUEG();
    const picOrderCntType = readUEG();
    if (picOrderCntType === 0) {
      readUEG();
    } else if (picOrderCntType === 1) {
      skipBits(1);
      skipEG();
      skipEG();
      numRefFramesInPicOrderCntCycle = readUEG();
      for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
        skipEG();
      }
    }
    skipUEG();
    skipBits(1);
    const picWidthInMbsMinus1 = readUEG();
    const picHeightInMapUnitsMinus1 = readUEG();
    const frameMbsOnlyFlag = readBits(1);
    if (frameMbsOnlyFlag === 0) {
      skipBits(1);
    }
    skipBits(1);
    if (readBoolean()) {
      frameCropLeftOffset = readUEG();
      frameCropRightOffset = readUEG();
      frameCropTopOffset = readUEG();
      frameCropBottomOffset = readUEG();
    }
    let pixelRatio = [1, 1];
    if (readBoolean()) {
      if (readBoolean()) {
        const aspectRatioIdc = readUByte();
        switch (aspectRatioIdc) {
          case 1:
            pixelRatio = [1, 1];
            break;
          case 2:
            pixelRatio = [12, 11];
            break;
          case 3:
            pixelRatio = [10, 11];
            break;
          case 4:
            pixelRatio = [16, 11];
            break;
          case 5:
            pixelRatio = [40, 33];
            break;
          case 6:
            pixelRatio = [24, 11];
            break;
          case 7:
            pixelRatio = [20, 11];
            break;
          case 8:
            pixelRatio = [32, 11];
            break;
          case 9:
            pixelRatio = [80, 33];
            break;
          case 10:
            pixelRatio = [18, 11];
            break;
          case 11:
            pixelRatio = [15, 11];
            break;
          case 12:
            pixelRatio = [64, 33];
            break;
          case 13:
            pixelRatio = [160, 99];
            break;
          case 14:
            pixelRatio = [4, 3];
            break;
          case 15:
            pixelRatio = [3, 2];
            break;
          case 16:
            pixelRatio = [2, 1];
            break;
          case 255: {
            pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
            break;
          }
        }
      }
    }
    return {
      width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
      height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
      pixelRatio
    };
  }
};
var HevcVideoParser = class extends BaseVideoParser {
  constructor(...args) {
    super(...args);
    this.initVPS = null;
  }
  parsePES(track, textTrack, pes, endOfSegment) {
    const units = this.parseNALu(track, pes.data, endOfSegment);
    let VideoSample = this.VideoSample;
    let push2;
    let spsfound = false;
    pes.data = null;
    if (VideoSample && units.length && !track.audFound) {
      this.pushAccessUnit(VideoSample, track);
      VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
    }
    units.forEach((unit) => {
      var _VideoSample2, _VideoSample3;
      switch (unit.type) {
        // NON-IDR, NON RANDOM ACCESS SLICE
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
          if (!VideoSample) {
            VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
          }
          VideoSample.frame = true;
          push2 = true;
          break;
        // CRA, BLA (random access picture)
        case 16:
        case 17:
        case 18:
        case 21:
          push2 = true;
          if (spsfound) {
            var _VideoSample;
            if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
              this.pushAccessUnit(VideoSample, track);
              VideoSample = this.VideoSample = null;
            }
          }
          if (!VideoSample) {
            VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
          }
          VideoSample.key = true;
          VideoSample.frame = true;
          break;
        // IDR
        case 19:
        case 20:
          push2 = true;
          if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
            this.pushAccessUnit(VideoSample, track);
            VideoSample = this.VideoSample = null;
          }
          if (!VideoSample) {
            VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
          }
          VideoSample.key = true;
          VideoSample.frame = true;
          break;
        // SEI
        case 39:
          push2 = true;
          parseSEIMessageFromNALu(
            unit.data,
            2,
            // NALu header size
            pes.pts,
            textTrack.samples
          );
          break;
        // VPS
        case 32:
          push2 = true;
          if (!track.vps) {
            if (typeof track.params !== "object") {
              track.params = {};
            }
            track.params = _extends(track.params, this.readVPS(unit.data));
            this.initVPS = unit.data;
          }
          track.vps = [unit.data];
          break;
        // SPS
        case 33:
          push2 = true;
          spsfound = true;
          if (track.vps !== void 0 && track.vps[0] !== this.initVPS && track.sps !== void 0 && !this.matchSPS(track.sps[0], unit.data)) {
            this.initVPS = track.vps[0];
            track.sps = track.pps = void 0;
          }
          if (!track.sps) {
            const config = this.readSPS(unit.data);
            track.width = config.width;
            track.height = config.height;
            track.pixelRatio = config.pixelRatio;
            track.codec = config.codecString;
            track.sps = [];
            if (typeof track.params !== "object") {
              track.params = {};
            }
            for (const prop in config.params) {
              track.params[prop] = config.params[prop];
            }
          }
          this.pushParameterSet(track.sps, unit.data, track.vps);
          if (!VideoSample) {
            VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
          }
          VideoSample.key = true;
          break;
        // PPS
        case 34:
          push2 = true;
          if (typeof track.params === "object") {
            if (!track.pps) {
              track.pps = [];
              const config = this.readPPS(unit.data);
              for (const prop in config) {
                track.params[prop] = config[prop];
              }
            }
            this.pushParameterSet(track.pps, unit.data, track.vps);
          }
          break;
        // ACCESS UNIT DELIMITER
        case 35:
          push2 = true;
          track.audFound = true;
          if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
            this.pushAccessUnit(VideoSample, track);
            VideoSample = null;
          }
          if (!VideoSample) {
            VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
          }
          break;
        default:
          push2 = false;
          break;
      }
      if (VideoSample && push2) {
        const units2 = VideoSample.units;
        units2.push(unit);
      }
    });
    if (endOfSegment && VideoSample) {
      this.pushAccessUnit(VideoSample, track);
      this.VideoSample = null;
    }
  }
  pushParameterSet(parameterSets, data, vps) {
    if (vps && vps[0] === this.initVPS || !vps && !parameterSets.length) {
      parameterSets.push(data);
    }
  }
  getNALuType(data, offset) {
    return (data[offset] & 126) >>> 1;
  }
  ebsp2rbsp(arr) {
    const dst = new Uint8Array(arr.byteLength);
    let dstIdx = 0;
    for (let i = 0; i < arr.byteLength; i++) {
      if (i >= 2) {
        if (arr[i] === 3 && arr[i - 1] === 0 && arr[i - 2] === 0) {
          continue;
        }
      }
      dst[dstIdx] = arr[i];
      dstIdx++;
    }
    return new Uint8Array(dst.buffer, 0, dstIdx);
  }
  pushAccessUnit(VideoSample, videoTrack) {
    super.pushAccessUnit(VideoSample, videoTrack);
    if (this.initVPS) {
      this.initVPS = null;
    }
  }
  readVPS(vps) {
    const eg = new ExpGolomb(vps);
    eg.readUByte();
    eg.readUByte();
    eg.readBits(4);
    eg.skipBits(2);
    eg.readBits(6);
    const max_sub_layers_minus1 = eg.readBits(3);
    const temporal_id_nesting_flag = eg.readBoolean();
    return {
      numTemporalLayers: max_sub_layers_minus1 + 1,
      temporalIdNested: temporal_id_nesting_flag
    };
  }
  readSPS(sps) {
    const eg = new ExpGolomb(this.ebsp2rbsp(sps));
    eg.readUByte();
    eg.readUByte();
    eg.readBits(4);
    const max_sub_layers_minus1 = eg.readBits(3);
    eg.readBoolean();
    const general_profile_space = eg.readBits(2);
    const general_tier_flag = eg.readBoolean();
    const general_profile_idc = eg.readBits(5);
    const general_profile_compatibility_flags_1 = eg.readUByte();
    const general_profile_compatibility_flags_2 = eg.readUByte();
    const general_profile_compatibility_flags_3 = eg.readUByte();
    const general_profile_compatibility_flags_4 = eg.readUByte();
    const general_constraint_indicator_flags_1 = eg.readUByte();
    const general_constraint_indicator_flags_2 = eg.readUByte();
    const general_constraint_indicator_flags_3 = eg.readUByte();
    const general_constraint_indicator_flags_4 = eg.readUByte();
    const general_constraint_indicator_flags_5 = eg.readUByte();
    const general_constraint_indicator_flags_6 = eg.readUByte();
    const general_level_idc = eg.readUByte();
    const sub_layer_profile_present_flags = [];
    const sub_layer_level_present_flags = [];
    for (let i = 0; i < max_sub_layers_minus1; i++) {
      sub_layer_profile_present_flags.push(eg.readBoolean());
      sub_layer_level_present_flags.push(eg.readBoolean());
    }
    if (max_sub_layers_minus1 > 0) {
      for (let i = max_sub_layers_minus1; i < 8; i++) {
        eg.readBits(2);
      }
    }
    for (let i = 0; i < max_sub_layers_minus1; i++) {
      if (sub_layer_profile_present_flags[i]) {
        eg.readUByte();
        eg.readUByte();
        eg.readUByte();
        eg.readUByte();
        eg.readUByte();
        eg.readUByte();
        eg.readUByte();
        eg.readUByte();
        eg.readUByte();
        eg.readUByte();
        eg.readUByte();
      }
      if (sub_layer_level_present_flags[i]) {
        eg.readUByte();
      }
    }
    eg.readUEG();
    const chroma_format_idc = eg.readUEG();
    if (chroma_format_idc == 3) {
      eg.skipBits(1);
    }
    const pic_width_in_luma_samples = eg.readUEG();
    const pic_height_in_luma_samples = eg.readUEG();
    const conformance_window_flag = eg.readBoolean();
    let pic_left_offset = 0, pic_right_offset = 0, pic_top_offset = 0, pic_bottom_offset = 0;
    if (conformance_window_flag) {
      pic_left_offset += eg.readUEG();
      pic_right_offset += eg.readUEG();
      pic_top_offset += eg.readUEG();
      pic_bottom_offset += eg.readUEG();
    }
    const bit_depth_luma_minus8 = eg.readUEG();
    const bit_depth_chroma_minus8 = eg.readUEG();
    const log2_max_pic_order_cnt_lsb_minus4 = eg.readUEG();
    const sub_layer_ordering_info_present_flag = eg.readBoolean();
    for (let i = sub_layer_ordering_info_present_flag ? 0 : max_sub_layers_minus1; i <= max_sub_layers_minus1; i++) {
      eg.skipUEG();
      eg.skipUEG();
      eg.skipUEG();
    }
    eg.skipUEG();
    eg.skipUEG();
    eg.skipUEG();
    eg.skipUEG();
    eg.skipUEG();
    eg.skipUEG();
    const scaling_list_enabled_flag = eg.readBoolean();
    if (scaling_list_enabled_flag) {
      const sps_scaling_list_data_present_flag = eg.readBoolean();
      if (sps_scaling_list_data_present_flag) {
        for (let sizeId = 0; sizeId < 4; sizeId++) {
          for (let matrixId = 0; matrixId < (sizeId === 3 ? 2 : 6); matrixId++) {
            const scaling_list_pred_mode_flag = eg.readBoolean();
            if (!scaling_list_pred_mode_flag) {
              eg.readUEG();
            } else {
              const coefNum = Math.min(64, 1 << 4 + (sizeId << 1));
              if (sizeId > 1) {
                eg.readEG();
              }
              for (let i = 0; i < coefNum; i++) {
                eg.readEG();
              }
            }
          }
        }
      }
    }
    eg.readBoolean();
    eg.readBoolean();
    const pcm_enabled_flag = eg.readBoolean();
    if (pcm_enabled_flag) {
      eg.readUByte();
      eg.skipUEG();
      eg.skipUEG();
      eg.readBoolean();
    }
    const num_short_term_ref_pic_sets = eg.readUEG();
    let num_delta_pocs = 0;
    for (let i = 0; i < num_short_term_ref_pic_sets; i++) {
      let inter_ref_pic_set_prediction_flag = false;
      if (i !== 0) {
        inter_ref_pic_set_prediction_flag = eg.readBoolean();
      }
      if (inter_ref_pic_set_prediction_flag) {
        if (i === num_short_term_ref_pic_sets) {
          eg.readUEG();
        }
        eg.readBoolean();
        eg.readUEG();
        let next_num_delta_pocs = 0;
        for (let j = 0; j <= num_delta_pocs; j++) {
          const used_by_curr_pic_flag = eg.readBoolean();
          let use_delta_flag = false;
          if (!used_by_curr_pic_flag) {
            use_delta_flag = eg.readBoolean();
          }
          if (used_by_curr_pic_flag || use_delta_flag) {
            next_num_delta_pocs++;
          }
        }
        num_delta_pocs = next_num_delta_pocs;
      } else {
        const num_negative_pics = eg.readUEG();
        const num_positive_pics = eg.readUEG();
        num_delta_pocs = num_negative_pics + num_positive_pics;
        for (let j = 0; j < num_negative_pics; j++) {
          eg.readUEG();
          eg.readBoolean();
        }
        for (let j = 0; j < num_positive_pics; j++) {
          eg.readUEG();
          eg.readBoolean();
        }
      }
    }
    const long_term_ref_pics_present_flag = eg.readBoolean();
    if (long_term_ref_pics_present_flag) {
      const num_long_term_ref_pics_sps = eg.readUEG();
      for (let i = 0; i < num_long_term_ref_pics_sps; i++) {
        for (let j = 0; j < log2_max_pic_order_cnt_lsb_minus4 + 4; j++) {
          eg.readBits(1);
        }
        eg.readBits(1);
      }
    }
    let min_spatial_segmentation_idc = 0;
    let sar_width = 1, sar_height = 1;
    let fps_fixed = true, fps_den = 1, fps_num = 0;
    eg.readBoolean();
    eg.readBoolean();
    let default_display_window_flag = false;
    const vui_parameters_present_flag = eg.readBoolean();
    if (vui_parameters_present_flag) {
      const aspect_ratio_info_present_flag = eg.readBoolean();
      if (aspect_ratio_info_present_flag) {
        const aspect_ratio_idc = eg.readUByte();
        const sar_width_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
        const sar_height_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
        if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
          sar_width = sar_width_table[aspect_ratio_idc - 1];
          sar_height = sar_height_table[aspect_ratio_idc - 1];
        } else if (aspect_ratio_idc === 255) {
          sar_width = eg.readBits(16);
          sar_height = eg.readBits(16);
        }
      }
      const overscan_info_present_flag = eg.readBoolean();
      if (overscan_info_present_flag) {
        eg.readBoolean();
      }
      const video_signal_type_present_flag = eg.readBoolean();
      if (video_signal_type_present_flag) {
        eg.readBits(3);
        eg.readBoolean();
        const colour_description_present_flag = eg.readBoolean();
        if (colour_description_present_flag) {
          eg.readUByte();
          eg.readUByte();
          eg.readUByte();
        }
      }
      const chroma_loc_info_present_flag = eg.readBoolean();
      if (chroma_loc_info_present_flag) {
        eg.readUEG();
        eg.readUEG();
      }
      eg.readBoolean();
      eg.readBoolean();
      eg.readBoolean();
      default_display_window_flag = eg.readBoolean();
      if (default_display_window_flag) {
        pic_left_offset += eg.readUEG();
        pic_right_offset += eg.readUEG();
        pic_top_offset += eg.readUEG();
        pic_bottom_offset += eg.readUEG();
      }
      const vui_timing_info_present_flag = eg.readBoolean();
      if (vui_timing_info_present_flag) {
        fps_den = eg.readBits(32);
        fps_num = eg.readBits(32);
        const vui_poc_proportional_to_timing_flag = eg.readBoolean();
        if (vui_poc_proportional_to_timing_flag) {
          eg.readUEG();
        }
        const vui_hrd_parameters_present_flag = eg.readBoolean();
        if (vui_hrd_parameters_present_flag) {
          const nal_hrd_parameters_present_flag = eg.readBoolean();
          const vcl_hrd_parameters_present_flag = eg.readBoolean();
          let sub_pic_hrd_params_present_flag = false;
          if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
            sub_pic_hrd_params_present_flag = eg.readBoolean();
            if (sub_pic_hrd_params_present_flag) {
              eg.readUByte();
              eg.readBits(5);
              eg.readBoolean();
              eg.readBits(5);
            }
            eg.readBits(4);
            eg.readBits(4);
            if (sub_pic_hrd_params_present_flag) {
              eg.readBits(4);
            }
            eg.readBits(5);
            eg.readBits(5);
            eg.readBits(5);
          }
          for (let i = 0; i <= max_sub_layers_minus1; i++) {
            fps_fixed = eg.readBoolean();
            const fixed_pic_rate_within_cvs_flag = fps_fixed || eg.readBoolean();
            let low_delay_hrd_flag = false;
            if (fixed_pic_rate_within_cvs_flag) {
              eg.readEG();
            } else {
              low_delay_hrd_flag = eg.readBoolean();
            }
            const cpb_cnt = low_delay_hrd_flag ? 1 : eg.readUEG() + 1;
            if (nal_hrd_parameters_present_flag) {
              for (let j = 0; j < cpb_cnt; j++) {
                eg.readUEG();
                eg.readUEG();
                if (sub_pic_hrd_params_present_flag) {
                  eg.readUEG();
                  eg.readUEG();
                }
                eg.skipBits(1);
              }
            }
            if (vcl_hrd_parameters_present_flag) {
              for (let j = 0; j < cpb_cnt; j++) {
                eg.readUEG();
                eg.readUEG();
                if (sub_pic_hrd_params_present_flag) {
                  eg.readUEG();
                  eg.readUEG();
                }
                eg.skipBits(1);
              }
            }
          }
        }
      }
      const bitstream_restriction_flag = eg.readBoolean();
      if (bitstream_restriction_flag) {
        eg.readBoolean();
        eg.readBoolean();
        eg.readBoolean();
        min_spatial_segmentation_idc = eg.readUEG();
      }
    }
    let width2 = pic_width_in_luma_samples, height2 = pic_height_in_luma_samples;
    if (conformance_window_flag || default_display_window_flag) {
      let chroma_scale_w = 1, chroma_scale_h = 1;
      if (chroma_format_idc === 1) {
        chroma_scale_w = chroma_scale_h = 2;
      } else if (chroma_format_idc == 2) {
        chroma_scale_w = 2;
      }
      width2 = pic_width_in_luma_samples - chroma_scale_w * pic_right_offset - chroma_scale_w * pic_left_offset;
      height2 = pic_height_in_luma_samples - chroma_scale_h * pic_bottom_offset - chroma_scale_h * pic_top_offset;
    }
    const profile_space_string = general_profile_space ? ["A", "B", "C"][general_profile_space] : "";
    const profile_compatibility_buf = general_profile_compatibility_flags_1 << 24 | general_profile_compatibility_flags_2 << 16 | general_profile_compatibility_flags_3 << 8 | general_profile_compatibility_flags_4;
    let profile_compatibility_rev = 0;
    for (let i = 0; i < 32; i++) {
      profile_compatibility_rev = (profile_compatibility_rev | (profile_compatibility_buf >> i & 1) << 31 - i) >>> 0;
    }
    let profile_compatibility_flags_string = profile_compatibility_rev.toString(16);
    if (general_profile_idc === 1 && profile_compatibility_flags_string === "2") {
      profile_compatibility_flags_string = "6";
    }
    const tier_flag_string = general_tier_flag ? "H" : "L";
    return {
      codecString: `hvc1.${profile_space_string}${general_profile_idc}.${profile_compatibility_flags_string}.${tier_flag_string}${general_level_idc}.B0`,
      params: {
        general_tier_flag,
        general_profile_idc,
        general_profile_space,
        general_profile_compatibility_flags: [general_profile_compatibility_flags_1, general_profile_compatibility_flags_2, general_profile_compatibility_flags_3, general_profile_compatibility_flags_4],
        general_constraint_indicator_flags: [general_constraint_indicator_flags_1, general_constraint_indicator_flags_2, general_constraint_indicator_flags_3, general_constraint_indicator_flags_4, general_constraint_indicator_flags_5, general_constraint_indicator_flags_6],
        general_level_idc,
        bit_depth: bit_depth_luma_minus8 + 8,
        bit_depth_luma_minus8,
        bit_depth_chroma_minus8,
        min_spatial_segmentation_idc,
        chroma_format_idc,
        frame_rate: {
          fixed: fps_fixed,
          fps: fps_num / fps_den
        }
      },
      width: width2,
      height: height2,
      pixelRatio: [sar_width, sar_height]
    };
  }
  readPPS(pps) {
    const eg = new ExpGolomb(this.ebsp2rbsp(pps));
    eg.readUByte();
    eg.readUByte();
    eg.skipUEG();
    eg.skipUEG();
    eg.skipBits(2);
    eg.skipBits(3);
    eg.skipBits(2);
    eg.skipUEG();
    eg.skipUEG();
    eg.skipEG();
    eg.skipBits(2);
    const cu_qp_delta_enabled_flag = eg.readBoolean();
    if (cu_qp_delta_enabled_flag) {
      eg.skipUEG();
    }
    eg.skipEG();
    eg.skipEG();
    eg.skipBits(4);
    const tiles_enabled_flag = eg.readBoolean();
    const entropy_coding_sync_enabled_flag = eg.readBoolean();
    let parallelismType = 1;
    if (entropy_coding_sync_enabled_flag && tiles_enabled_flag) {
      parallelismType = 0;
    } else if (entropy_coding_sync_enabled_flag) {
      parallelismType = 3;
    } else if (tiles_enabled_flag) {
      parallelismType = 2;
    }
    return {
      parallelismType
    };
  }
  matchSPS(sps1, sps2) {
    return String.fromCharCode.apply(null, sps1).substr(3) === String.fromCharCode.apply(null, sps2).substr(3);
  }
};
var PACKET_LENGTH = 188;
var TSDemuxer = class _TSDemuxer {
  constructor(observer, config, typeSupported, logger4) {
    this.logger = void 0;
    this.observer = void 0;
    this.config = void 0;
    this.typeSupported = void 0;
    this.sampleAes = null;
    this.pmtParsed = false;
    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 = observer;
    this.config = config;
    this.typeSupported = typeSupported;
    this.logger = logger4;
    this.videoParser = null;
  }
  static probe(data, logger4) {
    const syncOffset = _TSDemuxer.syncOffset(data);
    if (syncOffset > 0) {
      logger4.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);
    }
    return syncOffset !== -1;
  }
  static syncOffset(data) {
    const length = data.length;
    let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
    let i = 0;
    while (i < scanwindow) {
      let foundPat = false;
      let packetStart = -1;
      let tsPackets = 0;
      for (let j = i; j < length; j += PACKET_LENGTH) {
        if (data[j] === 71 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 71)) {
          tsPackets++;
          if (packetStart === -1) {
            packetStart = j;
            if (packetStart !== 0) {
              scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
            }
          }
          if (!foundPat) {
            foundPat = parsePID(data, j) === 0;
          }
          if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
            return packetStart;
          }
        } else if (tsPackets) {
          return -1;
        } else {
          break;
        }
      }
      i++;
    }
    return -1;
  }
  /**
   * Creates a track model internal to demuxer used to drive remuxing input
   */
  static createTrack(type2, duration5) {
    return {
      container: type2 === "video" || type2 === "audio" ? "video/mp2t" : void 0,
      type: type2,
      id: RemuxerTrackIdConfig[type2],
      pid: -1,
      inputTimeScale: 9e4,
      sequenceNumber: 0,
      samples: [],
      dropped: 0,
      duration: type2 === "audio" ? duration5 : 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(initSegment, audioCodec, videoCodec, trackDuration) {
    this.pmtParsed = false;
    this._pmtId = -1;
    this._videoTrack = _TSDemuxer.createTrack("video");
    this._videoTrack.duration = trackDuration;
    this._audioTrack = _TSDemuxer.createTrack("audio", trackDuration);
    this._id3Track = _TSDemuxer.createTrack("id3");
    this._txtTrack = _TSDemuxer.createTrack("text");
    this._audioTrack.segmentCodec = "aac";
    this.aacOverFlow = null;
    this.remainderData = null;
    this.audioCodec = audioCodec;
    this.videoCodec = videoCodec;
  }
  resetTimeStamp() {
  }
  resetContiguity() {
    const {
      _audioTrack,
      _videoTrack,
      _id3Track
    } = this;
    if (_audioTrack) {
      _audioTrack.pesData = null;
    }
    if (_videoTrack) {
      _videoTrack.pesData = null;
    }
    if (_id3Track) {
      _id3Track.pesData = null;
    }
    this.aacOverFlow = null;
    this.remainderData = null;
  }
  demux(data, timeOffset, isSampleAes = false, flush = false) {
    if (!isSampleAes) {
      this.sampleAes = null;
    }
    let pes;
    const videoTrack = this._videoTrack;
    const audioTrack = this._audioTrack;
    const id3Track = this._id3Track;
    const textTrack = this._txtTrack;
    let videoPid = videoTrack.pid;
    let videoData = videoTrack.pesData;
    let audioPid = audioTrack.pid;
    let id3Pid = id3Track.pid;
    let audioData = audioTrack.pesData;
    let id3Data = id3Track.pesData;
    let unknownPID = null;
    let pmtParsed = this.pmtParsed;
    let pmtId = this._pmtId;
    let len = data.length;
    if (this.remainderData) {
      data = appendUint8Array(this.remainderData, data);
      len = data.length;
      this.remainderData = null;
    }
    if (len < PACKET_LENGTH && !flush) {
      this.remainderData = data;
      return {
        audioTrack,
        videoTrack,
        id3Track,
        textTrack
      };
    }
    const syncOffset = Math.max(0, _TSDemuxer.syncOffset(data));
    len -= (len - syncOffset) % PACKET_LENGTH;
    if (len < data.byteLength && !flush) {
      this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
    }
    let tsPacketErrors = 0;
    for (let start2 = syncOffset; start2 < len; start2 += PACKET_LENGTH) {
      if (data[start2] === 71) {
        const stt = !!(data[start2 + 1] & 64);
        const pid = parsePID(data, start2);
        const atf = (data[start2 + 3] & 48) >> 4;
        let offset;
        if (atf > 1) {
          offset = start2 + 5 + data[start2 + 4];
          if (offset === start2 + PACKET_LENGTH) {
            continue;
          }
        } else {
          offset = start2 + 4;
        }
        switch (pid) {
          case videoPid:
            if (stt) {
              if (videoData && (pes = parsePES(videoData, this.logger))) {
                if (this.videoParser === null) {
                  switch (videoTrack.segmentCodec) {
                    case "avc":
                      this.videoParser = new AvcVideoParser();
                      break;
                    case "hevc":
                      {
                        this.videoParser = new HevcVideoParser();
                      }
                      break;
                  }
                }
                if (this.videoParser !== null) {
                  this.videoParser.parsePES(videoTrack, textTrack, pes, false);
                }
              }
              videoData = {
                data: [],
                size: 0
              };
            }
            if (videoData) {
              videoData.data.push(data.subarray(offset, start2 + PACKET_LENGTH));
              videoData.size += start2 + PACKET_LENGTH - offset;
            }
            break;
          case audioPid:
            if (stt) {
              if (audioData && (pes = parsePES(audioData, this.logger))) {
                switch (audioTrack.segmentCodec) {
                  case "aac":
                    this.parseAACPES(audioTrack, pes);
                    break;
                  case "mp3":
                    this.parseMPEGPES(audioTrack, pes);
                    break;
                  case "ac3":
                    {
                      this.parseAC3PES(audioTrack, pes);
                    }
                    break;
                }
              }
              audioData = {
                data: [],
                size: 0
              };
            }
            if (audioData) {
              audioData.data.push(data.subarray(offset, start2 + PACKET_LENGTH));
              audioData.size += start2 + PACKET_LENGTH - offset;
            }
            break;
          case id3Pid:
            if (stt) {
              if (id3Data && (pes = parsePES(id3Data, this.logger))) {
                this.parseID3PES(id3Track, pes);
              }
              id3Data = {
                data: [],
                size: 0
              };
            }
            if (id3Data) {
              id3Data.data.push(data.subarray(offset, start2 + PACKET_LENGTH));
              id3Data.size += start2 + PACKET_LENGTH - offset;
            }
            break;
          case 0:
            if (stt) {
              offset += data[offset] + 1;
            }
            pmtId = this._pmtId = parsePAT(data, offset);
            break;
          case pmtId: {
            if (stt) {
              offset += data[offset] + 1;
            }
            const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer, this.logger);
            videoPid = parsedPIDs.videoPid;
            if (videoPid > 0) {
              videoTrack.pid = videoPid;
              videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
            }
            audioPid = parsedPIDs.audioPid;
            if (audioPid > 0) {
              audioTrack.pid = audioPid;
              audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
            }
            id3Pid = parsedPIDs.id3Pid;
            if (id3Pid > 0) {
              id3Track.pid = id3Pid;
            }
            if (unknownPID !== null && !pmtParsed) {
              this.logger.warn(`MPEG-TS PMT found at ${start2} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);
              unknownPID = null;
              start2 = syncOffset - 188;
            }
            pmtParsed = this.pmtParsed = true;
            break;
          }
          case 17:
          case 8191:
            break;
          default:
            unknownPID = pid;
            break;
        }
      } else {
        tsPacketErrors++;
      }
    }
    if (tsPacketErrors > 0) {
      emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`), void 0, this.logger);
    }
    videoTrack.pesData = videoData;
    audioTrack.pesData = audioData;
    id3Track.pesData = id3Data;
    const demuxResult = {
      audioTrack,
      videoTrack,
      id3Track,
      textTrack
    };
    if (flush) {
      this.extractRemainingSamples(demuxResult);
    }
    return demuxResult;
  }
  flush() {
    const {
      remainderData
    } = this;
    this.remainderData = null;
    let result;
    if (remainderData) {
      result = this.demux(remainderData, -1, false, true);
    } else {
      result = {
        videoTrack: this._videoTrack,
        audioTrack: this._audioTrack,
        id3Track: this._id3Track,
        textTrack: this._txtTrack
      };
    }
    this.extractRemainingSamples(result);
    if (this.sampleAes) {
      return this.decrypt(result, this.sampleAes);
    }
    return result;
  }
  extractRemainingSamples(demuxResult) {
    const {
      audioTrack,
      videoTrack,
      id3Track,
      textTrack
    } = demuxResult;
    const videoData = videoTrack.pesData;
    const audioData = audioTrack.pesData;
    const id3Data = id3Track.pesData;
    let pes;
    if (videoData && (pes = parsePES(videoData, this.logger))) {
      if (this.videoParser === null) {
        switch (videoTrack.segmentCodec) {
          case "avc":
            this.videoParser = new AvcVideoParser();
            break;
          case "hevc":
            {
              this.videoParser = new HevcVideoParser();
            }
            break;
        }
      }
      if (this.videoParser !== null) {
        this.videoParser.parsePES(videoTrack, textTrack, pes, true);
        videoTrack.pesData = null;
      }
    } else {
      videoTrack.pesData = videoData;
    }
    if (audioData && (pes = parsePES(audioData, this.logger))) {
      switch (audioTrack.segmentCodec) {
        case "aac":
          this.parseAACPES(audioTrack, pes);
          break;
        case "mp3":
          this.parseMPEGPES(audioTrack, pes);
          break;
        case "ac3":
          {
            this.parseAC3PES(audioTrack, pes);
          }
          break;
      }
      audioTrack.pesData = null;
    } else {
      if (audioData != null && audioData.size) {
        this.logger.log("last AAC PES packet truncated,might overlap between fragments");
      }
      audioTrack.pesData = audioData;
    }
    if (id3Data && (pes = parsePES(id3Data, this.logger))) {
      this.parseID3PES(id3Track, pes);
      id3Track.pesData = null;
    } else {
      id3Track.pesData = id3Data;
    }
  }
  demuxSampleAes(data, keyData, timeOffset) {
    const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
    const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
    return this.decrypt(demuxResult, sampleAes);
  }
  decrypt(demuxResult, sampleAes) {
    return new Promise((resolve) => {
      const {
        audioTrack,
        videoTrack
      } = demuxResult;
      if (audioTrack.samples && audioTrack.segmentCodec === "aac") {
        sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {
          if (videoTrack.samples) {
            sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
              resolve(demuxResult);
            });
          } else {
            resolve(demuxResult);
          }
        });
      } else if (videoTrack.samples) {
        sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
          resolve(demuxResult);
        });
      }
    });
  }
  destroy() {
    if (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(track, pes) {
    let startOffset = 0;
    const aacOverFlow = this.aacOverFlow;
    let data = pes.data;
    if (aacOverFlow) {
      this.aacOverFlow = null;
      const frameMissingBytes = aacOverFlow.missing;
      const sampleLength = aacOverFlow.sample.unit.byteLength;
      if (frameMissingBytes === -1) {
        data = appendUint8Array(aacOverFlow.sample.unit, data);
      } else {
        const frameOverflowBytes = sampleLength - frameMissingBytes;
        aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
        track.samples.push(aacOverFlow.sample);
        startOffset = aacOverFlow.missing;
      }
    }
    let offset;
    let len;
    for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
      if (isHeader$1(data, offset)) {
        break;
      }
    }
    if (offset !== startOffset) {
      let reason;
      const recoverable = offset < len - 1;
      if (recoverable) {
        reason = `AAC PES did not start with ADTS header,offset:${offset}`;
      } else {
        reason = "No ADTS header found in AAC PES";
      }
      emitParsingError(this.observer, new Error(reason), recoverable, this.logger);
      if (!recoverable) {
        return;
      }
    }
    initTrackConfig(track, this.observer, data, offset, this.audioCodec);
    let pts;
    if (pes.pts !== void 0) {
      pts = pes.pts;
    } else if (aacOverFlow) {
      const frameDuration = getFrameDuration(track.samplerate);
      pts = aacOverFlow.sample.pts + frameDuration;
    } else {
      this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");
      return;
    }
    let frameIndex = 0;
    let frame;
    while (offset < len) {
      frame = appendFrame$2(track, data, offset, pts, frameIndex);
      offset += frame.length;
      if (!frame.missing) {
        frameIndex++;
        for (; offset < len - 1; offset++) {
          if (isHeader$1(data, offset)) {
            break;
          }
        }
      } else {
        this.aacOverFlow = frame;
        break;
      }
    }
  }
  parseMPEGPES(track, pes) {
    const data = pes.data;
    const length = data.length;
    let frameIndex = 0;
    let offset = 0;
    const pts = pes.pts;
    if (pts === void 0) {
      this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");
      return;
    }
    while (offset < length) {
      if (isHeader(data, offset)) {
        const frame = appendFrame$1(track, data, offset, pts, frameIndex);
        if (frame) {
          offset += frame.length;
          frameIndex++;
        } else {
          break;
        }
      } else {
        offset++;
      }
    }
  }
  parseAC3PES(track, pes) {
    {
      const data = pes.data;
      const pts = pes.pts;
      if (pts === void 0) {
        this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");
        return;
      }
      const length = data.length;
      let frameIndex = 0;
      let offset = 0;
      let parsed;
      while (offset < length && (parsed = appendFrame(track, data, offset, pts, frameIndex++)) > 0) {
        offset += parsed;
      }
    }
  }
  parseID3PES(id3Track, pes) {
    if (pes.pts === void 0) {
      this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");
      return;
    }
    const id3Sample = _extends({}, pes, {
      type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
      duration: Number.POSITIVE_INFINITY
    });
    id3Track.samples.push(id3Sample);
  }
};
function parsePID(data, offset) {
  return ((data[offset + 1] & 31) << 8) + data[offset + 2];
}
function parsePAT(data, offset) {
  return (data[offset + 10] & 31) << 8 | data[offset + 11];
}
function parsePMT(data, offset, typeSupported, isSampleAes, observer, logger4) {
  const result = {
    audioPid: -1,
    videoPid: -1,
    id3Pid: -1,
    segmentVideoCodec: "avc",
    segmentAudioCodec: "aac"
  };
  const sectionLength = (data[offset + 1] & 15) << 8 | data[offset + 2];
  const tableEnd = offset + 3 + sectionLength - 4;
  const programInfoLength = (data[offset + 10] & 15) << 8 | data[offset + 11];
  offset += 12 + programInfoLength;
  while (offset < tableEnd) {
    const pid = parsePID(data, offset);
    const esInfoLength = (data[offset + 3] & 15) << 8 | data[offset + 4];
    switch (data[offset]) {
      case 207:
        if (!isSampleAes) {
          logEncryptedSamplesFoundInUnencryptedStream("ADTS AAC", logger4);
          break;
        }
      /* falls through */
      case 15:
        if (result.audioPid === -1) {
          result.audioPid = pid;
        }
        break;
      // Packetized metadata (ID3)
      case 21:
        if (result.id3Pid === -1) {
          result.id3Pid = pid;
        }
        break;
      case 219:
        if (!isSampleAes) {
          logEncryptedSamplesFoundInUnencryptedStream("H.264", logger4);
          break;
        }
      /* falls through */
      case 27:
        if (result.videoPid === -1) {
          result.videoPid = pid;
        }
        break;
      // ISO/IEC 11172-3 (MPEG-1 audio)
      // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
      case 3:
      case 4:
        if (!typeSupported.mpeg && !typeSupported.mp3) {
          logger4.log("MPEG audio found, not supported in this browser");
        } else if (result.audioPid === -1) {
          result.audioPid = pid;
          result.segmentAudioCodec = "mp3";
        }
        break;
      case 193:
        if (!isSampleAes) {
          logEncryptedSamplesFoundInUnencryptedStream("AC-3", logger4);
          break;
        }
      /* falls through */
      case 129:
        {
          if (!typeSupported.ac3) {
            logger4.log("AC-3 audio found, not supported in this browser");
          } else if (result.audioPid === -1) {
            result.audioPid = pid;
            result.segmentAudioCodec = "ac3";
          }
        }
        break;
      case 6:
        if (result.audioPid === -1 && esInfoLength > 0) {
          let parsePos = offset + 5;
          let remaining = esInfoLength;
          while (remaining > 2) {
            const descriptorId = data[parsePos];
            switch (descriptorId) {
              case 106:
                {
                  if (typeSupported.ac3 !== true) {
                    logger4.log("AC-3 audio found, not supported in this browser for now");
                  } else {
                    result.audioPid = pid;
                    result.segmentAudioCodec = "ac3";
                  }
                }
                break;
            }
            const descriptorLen = data[parsePos + 1] + 2;
            parsePos += descriptorLen;
            remaining -= descriptorLen;
          }
        }
        break;
      case 194:
      // SAMPLE-AES EC3
      /* falls through */
      case 135:
        emitParsingError(observer, new Error("Unsupported EC-3 in M2TS found"), void 0, logger4);
        return result;
      case 36:
        {
          if (result.videoPid === -1) {
            result.videoPid = pid;
            result.segmentVideoCodec = "hevc";
            logger4.log("HEVC in M2TS found");
          }
        }
        break;
    }
    offset += esInfoLength + 5;
  }
  return result;
}
function emitParsingError(observer, error, levelRetry, logger4) {
  logger4.warn(`parsing error: ${error.message}`);
  observer.emit(Events.ERROR, Events.ERROR, {
    type: ErrorTypes.MEDIA_ERROR,
    details: ErrorDetails.FRAG_PARSING_ERROR,
    fatal: false,
    levelRetry,
    error,
    reason: error.message
  });
}
function logEncryptedSamplesFoundInUnencryptedStream(type2, logger4) {
  logger4.log(`${type2} with AES-128-CBC encryption found in unencrypted stream`);
}
function parsePES(stream, logger4) {
  let i = 0;
  let frag;
  let pesLen;
  let pesHdrLen;
  let pesPts;
  let pesDts;
  const data = stream.data;
  if (!stream || stream.size === 0) {
    return null;
  }
  while (data[0].length < 19 && data.length > 1) {
    data[0] = appendUint8Array(data[0], data[1]);
    data.splice(1, 1);
  }
  frag = data[0];
  const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  if (pesPrefix === 1) {
    pesLen = (frag[4] << 8) + frag[5];
    if (pesLen && pesLen > stream.size - 6) {
      return null;
    }
    const pesFlags = frag[7];
    if (pesFlags & 192) {
      pesPts = (frag[9] & 14) * 536870912 + // 1 << 29
      (frag[10] & 255) * 4194304 + // 1 << 22
      (frag[11] & 254) * 16384 + // 1 << 14
      (frag[12] & 255) * 128 + // 1 << 7
      (frag[13] & 254) / 2;
      if (pesFlags & 64) {
        pesDts = (frag[14] & 14) * 536870912 + // 1 << 29
        (frag[15] & 255) * 4194304 + // 1 << 22
        (frag[16] & 254) * 16384 + // 1 << 14
        (frag[17] & 255) * 128 + // 1 << 7
        (frag[18] & 254) / 2;
        if (pesPts - pesDts > 60 * 9e4) {
          logger4.warn(`${Math.round((pesPts - pesDts) / 9e4)}s delta between PTS and DTS, align them`);
          pesPts = pesDts;
        }
      } else {
        pesDts = pesPts;
      }
    }
    pesHdrLen = frag[8];
    let payloadStartOffset = pesHdrLen + 9;
    if (stream.size <= payloadStartOffset) {
      return null;
    }
    stream.size -= payloadStartOffset;
    const pesData = new Uint8Array(stream.size);
    for (let j = 0, dataLen = data.length; j < dataLen; j++) {
      frag = data[j];
      let len = frag.byteLength;
      if (payloadStartOffset) {
        if (payloadStartOffset > len) {
          payloadStartOffset -= len;
          continue;
        } else {
          frag = frag.subarray(payloadStartOffset);
          len -= payloadStartOffset;
          payloadStartOffset = 0;
        }
      }
      pesData.set(frag, i);
      i += len;
    }
    if (pesLen) {
      pesLen -= pesHdrLen + 3;
    }
    return {
      data: pesData,
      pts: pesPts,
      dts: pesDts,
      len: pesLen
    };
  }
  return null;
}
var AAC = class {
  static getSilentFrame(codec, channelCount) {
    switch (codec) {
      case "mp4a.40.2":
        if (channelCount === 1) {
          return new Uint8Array([0, 200, 0, 128, 35, 128]);
        } else if (channelCount === 2) {
          return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);
        } else if (channelCount === 3) {
          return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);
        } else if (channelCount === 4) {
          return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);
        } else if (channelCount === 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]);
        } else if (channelCount === 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 (channelCount === 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]);
        } else if (channelCount === 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]);
        } else if (channelCount === 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;
    }
    return void 0;
  }
};
var UINT32_MAX = Math.pow(2, 32) - 1;
var MP4 = class _MP4 {
  static init() {
    _MP4.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 i;
    for (i in _MP4.types) {
      if (_MP4.types.hasOwnProperty(i)) {
        _MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
      }
    }
    const videoHdlr = 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'
    ]);
    const audioHdlr = 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'
    ]);
    _MP4.HDLR_TYPES = {
      video: videoHdlr,
      audio: audioHdlr
    };
    const dref = 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
    ]);
    const stco = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0
      // entry_count
    ]);
    _MP4.STTS = _MP4.STSC = _MP4.STCO = stco;
    _MP4.STSZ = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0,
      // sample_size
      0,
      0,
      0,
      0
      // sample_count
    ]);
    _MP4.VMHD = new Uint8Array([
      0,
      // version
      0,
      0,
      1,
      // flags
      0,
      0,
      // graphicsmode
      0,
      0,
      0,
      0,
      0,
      0
      // opcolor
    ]);
    _MP4.SMHD = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      // balance
      0,
      0
      // reserved
    ]);
    _MP4.STSD = new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      1
    ]);
    const majorBrand = new Uint8Array([105, 115, 111, 109]);
    const avc1Brand = new Uint8Array([97, 118, 99, 49]);
    const minorVersion = new Uint8Array([0, 0, 0, 1]);
    _MP4.FTYP = _MP4.box(_MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
    _MP4.DINF = _MP4.box(_MP4.types.dinf, _MP4.box(_MP4.types.dref, dref));
  }
  static box(type2, ...payload) {
    let size = 8;
    let i = payload.length;
    const len = i;
    while (i--) {
      size += payload[i].byteLength;
    }
    const result = new Uint8Array(size);
    result[0] = size >> 24 & 255;
    result[1] = size >> 16 & 255;
    result[2] = size >> 8 & 255;
    result[3] = size & 255;
    result.set(type2, 4);
    for (i = 0, size = 8; i < len; i++) {
      result.set(payload[i], size);
      size += payload[i].byteLength;
    }
    return result;
  }
  static hdlr(type2) {
    return _MP4.box(_MP4.types.hdlr, _MP4.HDLR_TYPES[type2]);
  }
  static mdat(data) {
    return _MP4.box(_MP4.types.mdat, data);
  }
  static mdhd(timescale2, duration5) {
    duration5 *= timescale2;
    const upperWordDuration = Math.floor(duration5 / (UINT32_MAX + 1));
    const lowerWordDuration = Math.floor(duration5 % (UINT32_MAX + 1));
    return _MP4.box(_MP4.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
      timescale2 >> 24 & 255,
      timescale2 >> 16 & 255,
      timescale2 >> 8 & 255,
      timescale2 & 255,
      // timescale
      upperWordDuration >> 24,
      upperWordDuration >> 16 & 255,
      upperWordDuration >> 8 & 255,
      upperWordDuration & 255,
      lowerWordDuration >> 24,
      lowerWordDuration >> 16 & 255,
      lowerWordDuration >> 8 & 255,
      lowerWordDuration & 255,
      85,
      196,
      // 'und' language (undetermined)
      0,
      0
    ]));
  }
  static mdia(track) {
    return _MP4.box(_MP4.types.mdia, _MP4.mdhd(track.timescale || 0, track.duration || 0), _MP4.hdlr(track.type), _MP4.minf(track));
  }
  static mfhd(sequenceNumber) {
    return _MP4.box(_MP4.types.mfhd, new Uint8Array([
      0,
      0,
      0,
      0,
      // flags
      sequenceNumber >> 24,
      sequenceNumber >> 16 & 255,
      sequenceNumber >> 8 & 255,
      sequenceNumber & 255
      // sequence_number
    ]));
  }
  static minf(track) {
    if (track.type === "audio") {
      return _MP4.box(_MP4.types.minf, _MP4.box(_MP4.types.smhd, _MP4.SMHD), _MP4.DINF, _MP4.stbl(track));
    } else {
      return _MP4.box(_MP4.types.minf, _MP4.box(_MP4.types.vmhd, _MP4.VMHD), _MP4.DINF, _MP4.stbl(track));
    }
  }
  static moof(sn, baseMediaDecodeTime, track) {
    return _MP4.box(_MP4.types.moof, _MP4.mfhd(sn), _MP4.traf(track, baseMediaDecodeTime));
  }
  static moov(tracks) {
    let i = tracks.length;
    const boxes = [];
    while (i--) {
      boxes[i] = _MP4.trak(tracks[i]);
    }
    return _MP4.box.apply(null, [_MP4.types.moov, _MP4.mvhd(tracks[0].timescale || 0, tracks[0].duration || 0)].concat(boxes).concat(_MP4.mvex(tracks)));
  }
  static mvex(tracks) {
    let i = tracks.length;
    const boxes = [];
    while (i--) {
      boxes[i] = _MP4.trex(tracks[i]);
    }
    return _MP4.box.apply(null, [_MP4.types.mvex, ...boxes]);
  }
  static mvhd(timescale2, duration5) {
    duration5 *= timescale2;
    const upperWordDuration = Math.floor(duration5 / (UINT32_MAX + 1));
    const lowerWordDuration = Math.floor(duration5 % (UINT32_MAX + 1));
    const bytes = 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
      timescale2 >> 24 & 255,
      timescale2 >> 16 & 255,
      timescale2 >> 8 & 255,
      timescale2 & 255,
      // timescale
      upperWordDuration >> 24,
      upperWordDuration >> 16 & 255,
      upperWordDuration >> 8 & 255,
      upperWordDuration & 255,
      lowerWordDuration >> 24,
      lowerWordDuration >> 16 & 255,
      lowerWordDuration >> 8 & 255,
      lowerWordDuration & 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 _MP4.box(_MP4.types.mvhd, bytes);
  }
  static sdtp(track) {
    const samples = track.samples || [];
    const bytes = new Uint8Array(4 + samples.length);
    let i;
    let flags;
    for (i = 0; i < samples.length; i++) {
      flags = samples[i].flags;
      bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
    }
    return _MP4.box(_MP4.types.sdtp, bytes);
  }
  static stbl(track) {
    return _MP4.box(_MP4.types.stbl, _MP4.stsd(track), _MP4.box(_MP4.types.stts, _MP4.STTS), _MP4.box(_MP4.types.stsc, _MP4.STSC), _MP4.box(_MP4.types.stsz, _MP4.STSZ), _MP4.box(_MP4.types.stco, _MP4.STCO));
  }
  static avc1(track) {
    let sps = [];
    let pps = [];
    let i;
    let data;
    let len;
    for (i = 0; i < track.sps.length; i++) {
      data = track.sps[i];
      len = data.byteLength;
      sps.push(len >>> 8 & 255);
      sps.push(len & 255);
      sps = sps.concat(Array.prototype.slice.call(data));
    }
    for (i = 0; i < track.pps.length; i++) {
      data = track.pps[i];
      len = data.byteLength;
      pps.push(len >>> 8 & 255);
      pps.push(len & 255);
      pps = pps.concat(Array.prototype.slice.call(data));
    }
    const avcc = _MP4.box(_MP4.types.avcC, new Uint8Array([
      1,
      // version
      sps[3],
      // profile
      sps[4],
      // profile compat
      sps[5],
      // level
      252 | 3,
      // lengthSizeMinusOne, hard-coded to 4 bytes
      224 | track.sps.length
      // 3bit reserved (111) + numOfSequenceParameterSets
    ].concat(sps).concat([
      track.pps.length
      // numOfPictureParameterSets
    ]).concat(pps)));
    const width2 = track.width;
    const height2 = track.height;
    const hSpacing = track.pixelRatio[0];
    const vSpacing = track.pixelRatio[1];
    return _MP4.box(
      _MP4.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
        width2 >> 8 & 255,
        width2 & 255,
        // width
        height2 >> 8 & 255,
        height2 & 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
      avcc,
      _MP4.box(_MP4.types.btrt, new Uint8Array([
        0,
        28,
        156,
        128,
        // bufferSizeDB
        0,
        45,
        198,
        192,
        // maxBitrate
        0,
        45,
        198,
        192
      ])),
      // avgBitrate
      _MP4.box(_MP4.types.pasp, new Uint8Array([
        hSpacing >> 24,
        // hSpacing
        hSpacing >> 16 & 255,
        hSpacing >> 8 & 255,
        hSpacing & 255,
        vSpacing >> 24,
        // vSpacing
        vSpacing >> 16 & 255,
        vSpacing >> 8 & 255,
        vSpacing & 255
      ]))
    );
  }
  static esds(track) {
    const config = track.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
      ...config,
      6,
      1,
      2
      // GASpecificConfig)); // length + audio config descriptor
    ]);
  }
  static audioStsd(track) {
    const samplerate = track.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,
      track.channelCount || 0,
      // channelcount
      0,
      16,
      // sampleSize:16bits
      0,
      0,
      0,
      0,
      // reserved2
      samplerate >> 8 & 255,
      samplerate & 255,
      //
      0,
      0
    ]);
  }
  static mp4a(track) {
    return _MP4.box(_MP4.types.mp4a, _MP4.audioStsd(track), _MP4.box(_MP4.types.esds, _MP4.esds(track)));
  }
  static mp3(track) {
    return _MP4.box(_MP4.types[".mp3"], _MP4.audioStsd(track));
  }
  static ac3(track) {
    return _MP4.box(_MP4.types["ac-3"], _MP4.audioStsd(track), _MP4.box(_MP4.types.dac3, track.config));
  }
  static stsd(track) {
    const {
      segmentCodec
    } = track;
    if (track.type === "audio") {
      if (segmentCodec === "aac") {
        return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.mp4a(track));
      }
      if (segmentCodec === "ac3" && track.config) {
        return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.ac3(track));
      }
      if (segmentCodec === "mp3" && track.codec === "mp3") {
        return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.mp3(track));
      }
    } else {
      if (track.pps && track.sps) {
        if (segmentCodec === "avc") {
          return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.avc1(track));
        }
        if (segmentCodec === "hevc" && track.vps) {
          return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.hvc1(track));
        }
      } else {
        throw new Error(`video track missing pps or sps`);
      }
    }
    throw new Error(`unsupported ${track.type} segment codec (${segmentCodec}/${track.codec})`);
  }
  static tkhd(track) {
    const id = track.id;
    const duration5 = (track.duration || 0) * (track.timescale || 0);
    const width2 = track.width || 0;
    const height2 = track.height || 0;
    const upperWordDuration = Math.floor(duration5 / (UINT32_MAX + 1));
    const lowerWordDuration = Math.floor(duration5 % (UINT32_MAX + 1));
    return _MP4.box(_MP4.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
      id >> 24 & 255,
      id >> 16 & 255,
      id >> 8 & 255,
      id & 255,
      // track_ID
      0,
      0,
      0,
      0,
      // reserved
      upperWordDuration >> 24,
      upperWordDuration >> 16 & 255,
      upperWordDuration >> 8 & 255,
      upperWordDuration & 255,
      lowerWordDuration >> 24,
      lowerWordDuration >> 16 & 255,
      lowerWordDuration >> 8 & 255,
      lowerWordDuration & 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
      width2 >> 8 & 255,
      width2 & 255,
      0,
      0,
      // width
      height2 >> 8 & 255,
      height2 & 255,
      0,
      0
      // height
    ]));
  }
  static traf(track, baseMediaDecodeTime) {
    const sampleDependencyTable = _MP4.sdtp(track);
    const id = track.id;
    const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
    const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
    return _MP4.box(
      _MP4.types.traf,
      _MP4.box(_MP4.types.tfhd, new Uint8Array([
        0,
        // version 0
        0,
        0,
        0,
        // flags
        id >> 24,
        id >> 16 & 255,
        id >> 8 & 255,
        id & 255
        // track_ID
      ])),
      _MP4.box(_MP4.types.tfdt, new Uint8Array([
        1,
        // version 1
        0,
        0,
        0,
        // flags
        upperWordBaseMediaDecodeTime >> 24,
        upperWordBaseMediaDecodeTime >> 16 & 255,
        upperWordBaseMediaDecodeTime >> 8 & 255,
        upperWordBaseMediaDecodeTime & 255,
        lowerWordBaseMediaDecodeTime >> 24,
        lowerWordBaseMediaDecodeTime >> 16 & 255,
        lowerWordBaseMediaDecodeTime >> 8 & 255,
        lowerWordBaseMediaDecodeTime & 255
      ])),
      _MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
      20 + // tfdt
      8 + // traf header
      16 + // mfhd
      8 + // moof header
      8),
      // mdat header
      sampleDependencyTable
    );
  }
  /**
   * Generate a track box.
   * @param track a track definition
   */
  static trak(track) {
    track.duration = track.duration || 4294967295;
    return _MP4.box(_MP4.types.trak, _MP4.tkhd(track), _MP4.mdia(track));
  }
  static trex(track) {
    const id = track.id;
    return _MP4.box(_MP4.types.trex, new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      id >> 24,
      id >> 16 & 255,
      id >> 8 & 255,
      id & 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(track, offset) {
    const samples = track.samples || [];
    const len = samples.length;
    const arraylen = 12 + 16 * len;
    const array = new Uint8Array(arraylen);
    let i;
    let sample;
    let duration5;
    let size;
    let flags;
    let cts;
    offset += 8 + arraylen;
    array.set([
      track.type === "video" ? 1 : 0,
      // version 1 for video with signed-int sample_composition_time_offset
      0,
      15,
      1,
      // flags
      len >>> 24 & 255,
      len >>> 16 & 255,
      len >>> 8 & 255,
      len & 255,
      // sample_count
      offset >>> 24 & 255,
      offset >>> 16 & 255,
      offset >>> 8 & 255,
      offset & 255
      // data_offset
    ], 0);
    for (i = 0; i < len; i++) {
      sample = samples[i];
      duration5 = sample.duration;
      size = sample.size;
      flags = sample.flags;
      cts = sample.cts;
      array.set([
        duration5 >>> 24 & 255,
        duration5 >>> 16 & 255,
        duration5 >>> 8 & 255,
        duration5 & 255,
        // sample_duration
        size >>> 24 & 255,
        size >>> 16 & 255,
        size >>> 8 & 255,
        size & 255,
        // sample_size
        flags.isLeading << 2 | flags.dependsOn,
        flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync,
        flags.degradPrio & 240 << 8,
        flags.degradPrio & 15,
        // sample_flags
        cts >>> 24 & 255,
        cts >>> 16 & 255,
        cts >>> 8 & 255,
        cts & 255
        // sample_composition_time_offset
      ], 12 + 16 * i);
    }
    return _MP4.box(_MP4.types.trun, array);
  }
  static initSegment(tracks) {
    if (!_MP4.types) {
      _MP4.init();
    }
    const movie = _MP4.moov(tracks);
    const result = appendUint8Array(_MP4.FTYP, movie);
    return result;
  }
  static hvc1(track) {
    const ps = track.params;
    const units = [track.vps, track.sps, track.pps];
    const NALuLengthSize = 4;
    const config = new Uint8Array([1, ps.general_profile_space << 6 | (ps.general_tier_flag ? 32 : 0) | ps.general_profile_idc, ps.general_profile_compatibility_flags[0], ps.general_profile_compatibility_flags[1], ps.general_profile_compatibility_flags[2], ps.general_profile_compatibility_flags[3], ps.general_constraint_indicator_flags[0], ps.general_constraint_indicator_flags[1], ps.general_constraint_indicator_flags[2], ps.general_constraint_indicator_flags[3], ps.general_constraint_indicator_flags[4], ps.general_constraint_indicator_flags[5], ps.general_level_idc, 240 | ps.min_spatial_segmentation_idc >> 8, 255 & ps.min_spatial_segmentation_idc, 252 | ps.parallelismType, 252 | ps.chroma_format_idc, 248 | ps.bit_depth_luma_minus8, 248 | ps.bit_depth_chroma_minus8, 0, parseInt(ps.frame_rate.fps), NALuLengthSize - 1 | ps.temporal_id_nested << 2 | ps.num_temporal_layers << 3 | (ps.frame_rate.fixed ? 64 : 0), units.length]);
    let length = config.length;
    for (let i = 0; i < units.length; i += 1) {
      length += 3;
      for (let j = 0; j < units[i].length; j += 1) {
        length += 2 + units[i][j].length;
      }
    }
    const hvcC = new Uint8Array(length);
    hvcC.set(config, 0);
    length = config.length;
    const iMax = units.length - 1;
    for (let i = 0; i < units.length; i += 1) {
      hvcC.set(new Uint8Array([32 + i | (i === iMax ? 128 : 0), 0, units[i].length]), length);
      length += 3;
      for (let j = 0; j < units[i].length; j += 1) {
        hvcC.set(new Uint8Array([units[i][j].length >> 8, units[i][j].length & 255]), length);
        length += 2;
        hvcC.set(units[i][j], length);
        length += units[i][j].length;
      }
    }
    const hvcc = _MP4.box(_MP4.types.hvcC, hvcC);
    const width2 = track.width;
    const height2 = track.height;
    const hSpacing = track.pixelRatio[0];
    const vSpacing = track.pixelRatio[1];
    return _MP4.box(
      _MP4.types.hvc1,
      new Uint8Array([
        0,
        0,
        0,
        // reserved
        0,
        0,
        0,
        // reserved
        0,
        1,
        // data_reference_index
        0,
        0,
        // pre_defined
        0,
        0,
        // reserved
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        // pre_defined
        width2 >> 8 & 255,
        width2 & 255,
        // width
        height2 >> 8 & 255,
        height2 & 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
      hvcc,
      _MP4.box(_MP4.types.btrt, new Uint8Array([
        0,
        28,
        156,
        128,
        // bufferSizeDB
        0,
        45,
        198,
        192,
        // maxBitrate
        0,
        45,
        198,
        192
      ])),
      // avgBitrate
      _MP4.box(_MP4.types.pasp, new Uint8Array([
        hSpacing >> 24,
        // hSpacing
        hSpacing >> 16 & 255,
        hSpacing >> 8 & 255,
        hSpacing & 255,
        vSpacing >> 24,
        // vSpacing
        vSpacing >> 16 & 255,
        vSpacing >> 8 & 255,
        vSpacing & 255
      ]))
    );
  }
};
MP4.types = void 0;
MP4.HDLR_TYPES = void 0;
MP4.STTS = void 0;
MP4.STSC = void 0;
MP4.STCO = void 0;
MP4.STSZ = void 0;
MP4.VMHD = void 0;
MP4.SMHD = void 0;
MP4.STSD = void 0;
MP4.FTYP = void 0;
MP4.DINF = void 0;
var MPEG_TS_CLOCK_FREQ_HZ = 9e4;
function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) {
  const result = baseTime * destScale * srcBase;
  return round ? Math.round(result) : result;
}
function toTimescaleFromScale(baseTime, destScale, srcScale = 1, round = false) {
  return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);
}
function toMsFromMpegTsClock(baseTime, round = false) {
  return toTimescaleFromBase(baseTime, 1e3, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
}
function toMpegTsClockFromTimescale(baseTime, srcScale = 1) {
  return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
}
var MAX_SILENT_FRAME_DURATION = 10 * 1e3;
var AAC_SAMPLES_PER_FRAME = 1024;
var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
var AC3_SAMPLES_PER_FRAME = 1536;
var chromeVersion = null;
var safariWebkitVersion = null;
function createMp4Sample(isKeyframe, duration5, size, cts) {
  return {
    duration: duration5,
    size,
    cts,
    flags: {
      isLeading: 0,
      isDependedOn: 0,
      hasRedundancy: 0,
      degradPrio: 0,
      dependsOn: isKeyframe ? 2 : 1,
      isNonSync: isKeyframe ? 0 : 1
    }
  };
}
var MP4Remuxer = class {
  constructor(observer, config, typeSupported, logger4) {
    this.logger = void 0;
    this.observer = void 0;
    this.config = void 0;
    this.typeSupported = void 0;
    this.ISGenerated = false;
    this._initPTS = null;
    this._initDTS = null;
    this.nextAvcDts = null;
    this.nextAudioPts = null;
    this.videoSampleDuration = null;
    this.isAudioContiguous = false;
    this.isVideoContiguous = false;
    this.videoTrackConfig = void 0;
    this.observer = observer;
    this.config = config;
    this.typeSupported = typeSupported;
    this.logger = logger4;
    this.ISGenerated = false;
    if (chromeVersion === null) {
      const userAgent = navigator.userAgent || "";
      const result = userAgent.match(/Chrome\/(\d+)/i);
      chromeVersion = result ? parseInt(result[1]) : 0;
    }
    if (safariWebkitVersion === null) {
      const result = navigator.userAgent.match(/Safari\/(\d+)/i);
      safariWebkitVersion = result ? parseInt(result[1]) : 0;
    }
  }
  destroy() {
    this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  }
  resetTimeStamp(defaultTimeStamp) {
    this.logger.log("[mp4-remuxer]: initPTS & initDTS reset");
    this._initPTS = this._initDTS = defaultTimeStamp;
  }
  resetNextTimestamp() {
    this.logger.log("[mp4-remuxer]: reset next timestamp");
    this.isVideoContiguous = false;
    this.isAudioContiguous = false;
  }
  resetInitSegment() {
    this.logger.log("[mp4-remuxer]: ISGenerated flag reset");
    this.ISGenerated = false;
    this.videoTrackConfig = void 0;
  }
  getVideoStartPts(videoSamples) {
    let rolloverDetected = false;
    const firstPts = videoSamples[0].pts;
    const startPTS = videoSamples.reduce((minPTS, sample) => {
      let pts = sample.pts;
      let delta = pts - minPTS;
      if (delta < -4294967296) {
        rolloverDetected = true;
        pts = normalizePts(pts, firstPts);
        delta = pts - minPTS;
      }
      if (delta > 0) {
        return minPTS;
      }
      return pts;
    }, firstPts);
    if (rolloverDetected) {
      this.logger.debug("PTS rollover detected");
    }
    return startPTS;
  }
  remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
    let video;
    let audio;
    let initSegment;
    let text;
    let id3;
    let independent;
    let audioTimeOffset = timeOffset;
    let videoTimeOffset = timeOffset;
    const hasAudio = audioTrack.pid > -1;
    const hasVideo = videoTrack.pid > -1;
    const length = videoTrack.samples.length;
    const enoughAudioSamples = audioTrack.samples.length > 0;
    const enoughVideoSamples = flush && length > 0 || length > 1;
    const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
    if (canRemuxAvc) {
      if (this.ISGenerated) {
        var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
        const config = this.videoTrackConfig;
        if (config && (videoTrack.width !== config.width || videoTrack.height !== config.height || ((_videoTrack$pixelRati = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati[0]) !== ((_config$pixelRatio = config.pixelRatio) == null ? void 0 : _config$pixelRatio[0]) || ((_videoTrack$pixelRati2 = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati2[1]) !== ((_config$pixelRatio2 = config.pixelRatio) == null ? void 0 : _config$pixelRatio2[1])) || !config && enoughVideoSamples || this.nextAudioPts === null && enoughAudioSamples) {
          this.resetInitSegment();
        }
      }
      if (!this.ISGenerated) {
        initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
      }
      const isVideoContiguous = this.isVideoContiguous;
      let firstKeyFrameIndex = -1;
      let firstKeyFramePTS;
      if (enoughVideoSamples) {
        firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
        if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
          independent = true;
          if (firstKeyFrameIndex > 0) {
            this.logger.warn(`[mp4-remuxer]: Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);
            const startPTS = this.getVideoStartPts(videoTrack.samples);
            videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
            videoTrack.dropped += firstKeyFrameIndex;
            videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
            firstKeyFramePTS = videoTimeOffset;
          } else if (firstKeyFrameIndex === -1) {
            this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${length} video samples`);
            independent = false;
          }
        }
      }
      if (this.ISGenerated) {
        if (enoughAudioSamples && enoughVideoSamples) {
          const startPTS = this.getVideoStartPts(videoTrack.samples);
          const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;
          const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
          audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
          videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
        }
        if (enoughAudioSamples) {
          if (!audioTrack.samplerate) {
            this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected");
            initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
          }
          audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : void 0);
          if (enoughVideoSamples) {
            const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
            if (!videoTrack.inputTimeScale) {
              this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected");
              initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
            }
            video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
          }
        } else if (enoughVideoSamples) {
          video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
        }
        if (video) {
          video.firstKeyFrame = firstKeyFrameIndex;
          video.independent = firstKeyFrameIndex !== -1;
          video.firstKeyFramePTS = firstKeyFramePTS;
        }
      }
    }
    if (this.ISGenerated && this._initPTS && this._initDTS) {
      if (id3Track.samples.length) {
        id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
      }
      if (textTrack.samples.length) {
        text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
      }
    }
    return {
      audio,
      video,
      initSegment,
      independent,
      text,
      id3
    };
  }
  generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
    const audioSamples = audioTrack.samples;
    const videoSamples = videoTrack.samples;
    const typeSupported = this.typeSupported;
    const tracks = {};
    const _initPTS = this._initPTS;
    let computePTSDTS = !_initPTS || accurateTimeOffset;
    let container = "audio/mp4";
    let initPTS;
    let initDTS;
    let timescale2;
    if (computePTSDTS) {
      initPTS = initDTS = Infinity;
    }
    if (audioTrack.config && audioSamples.length) {
      audioTrack.timescale = audioTrack.samplerate;
      switch (audioTrack.segmentCodec) {
        case "mp3":
          if (typeSupported.mpeg) {
            container = "audio/mpeg";
            audioTrack.codec = "";
          } else if (typeSupported.mp3) {
            audioTrack.codec = "mp3";
          }
          break;
        case "ac3":
          audioTrack.codec = "ac-3";
          break;
      }
      tracks.audio = {
        id: "audio",
        container,
        codec: audioTrack.codec,
        initSegment: audioTrack.segmentCodec === "mp3" && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
        metadata: {
          channelCount: audioTrack.channelCount
        }
      };
      if (computePTSDTS) {
        timescale2 = audioTrack.inputTimeScale;
        if (!_initPTS || timescale2 !== _initPTS.timescale) {
          initPTS = initDTS = audioSamples[0].pts - Math.round(timescale2 * timeOffset);
        } else {
          computePTSDTS = false;
        }
      }
    }
    if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
      videoTrack.timescale = videoTrack.inputTimeScale;
      tracks.video = {
        id: "main",
        container: "video/mp4",
        codec: videoTrack.codec,
        initSegment: MP4.initSegment([videoTrack]),
        metadata: {
          width: videoTrack.width,
          height: videoTrack.height
        }
      };
      if (computePTSDTS) {
        timescale2 = videoTrack.inputTimeScale;
        if (!_initPTS || timescale2 !== _initPTS.timescale) {
          const startPTS = this.getVideoStartPts(videoSamples);
          const startOffset = Math.round(timescale2 * timeOffset);
          initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
          initPTS = Math.min(initPTS, startPTS - startOffset);
        } else {
          computePTSDTS = false;
        }
      }
      this.videoTrackConfig = {
        width: videoTrack.width,
        height: videoTrack.height,
        pixelRatio: videoTrack.pixelRatio
      };
    }
    if (Object.keys(tracks).length) {
      this.ISGenerated = true;
      if (computePTSDTS) {
        this._initPTS = {
          baseTime: initPTS,
          timescale: timescale2
        };
        this._initDTS = {
          baseTime: initDTS,
          timescale: timescale2
        };
      } else {
        initPTS = timescale2 = void 0;
      }
      return {
        tracks,
        initPTS,
        timescale: timescale2
      };
    }
  }
  remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
    const timeScale = track.inputTimeScale;
    const inputSamples = track.samples;
    const outputSamples = [];
    const nbSamples = inputSamples.length;
    const initPTS = this._initPTS;
    let nextAvcDts = this.nextAvcDts;
    let offset = 8;
    let mp4SampleDuration = this.videoSampleDuration;
    let firstDTS;
    let lastDTS;
    let minPTS = Number.POSITIVE_INFINITY;
    let maxPTS = Number.NEGATIVE_INFINITY;
    let sortSamples = false;
    if (!contiguous || nextAvcDts === null) {
      const pts = timeOffset * timeScale;
      const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
      if (chromeVersion && nextAvcDts !== null && Math.abs(pts - cts - nextAvcDts) < 15e3) {
        contiguous = true;
      } else {
        nextAvcDts = pts - cts;
      }
    }
    const initTime = initPTS.baseTime * timeScale / initPTS.timescale;
    for (let i = 0; i < nbSamples; i++) {
      const sample = inputSamples[i];
      sample.pts = normalizePts(sample.pts - initTime, nextAvcDts);
      sample.dts = normalizePts(sample.dts - initTime, nextAvcDts);
      if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
        sortSamples = true;
      }
    }
    if (sortSamples) {
      inputSamples.sort(function(a, b) {
        const deltadts = a.dts - b.dts;
        const deltapts = a.pts - b.pts;
        return deltadts || deltapts;
      });
    }
    firstDTS = inputSamples[0].dts;
    lastDTS = inputSamples[inputSamples.length - 1].dts;
    const inputDuration = lastDTS - firstDTS;
    const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
    if (contiguous) {
      const delta = firstDTS - nextAvcDts;
      const foundHole = delta > averageSampleDuration;
      const foundOverlap = delta < -1;
      if (foundHole || foundOverlap) {
        if (foundHole) {
          this.logger.warn(`${(track.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);
        } else {
          this.logger.warn(`${(track.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);
        }
        if (!foundOverlap || nextAvcDts >= inputSamples[0].pts || chromeVersion) {
          firstDTS = nextAvcDts;
          const firstPTS = inputSamples[0].pts - delta;
          if (foundHole) {
            inputSamples[0].dts = firstDTS;
            inputSamples[0].pts = firstPTS;
          } else {
            let isPTSOrderRetained = true;
            for (let i = 0; i < inputSamples.length; i++) {
              if (inputSamples[i].dts > firstPTS && isPTSOrderRetained) {
                break;
              }
              const prevPTS = inputSamples[i].pts;
              inputSamples[i].dts -= delta;
              inputSamples[i].pts -= delta;
              if (i < inputSamples.length - 1) {
                const nextSamplePTS = inputSamples[i + 1].pts;
                const currentSamplePTS = inputSamples[i].pts;
                const currentOrder = nextSamplePTS <= currentSamplePTS;
                const prevOrder = nextSamplePTS <= prevPTS;
                isPTSOrderRetained = currentOrder == prevOrder;
              }
            }
          }
          this.logger.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);
        }
      }
    }
    firstDTS = Math.max(0, firstDTS);
    let nbNalu = 0;
    let naluLen = 0;
    let dtsStep = firstDTS;
    for (let i = 0; i < nbSamples; i++) {
      const sample = inputSamples[i];
      const units = sample.units;
      const nbUnits = units.length;
      let sampleLen = 0;
      for (let j = 0; j < nbUnits; j++) {
        sampleLen += units[j].data.length;
      }
      naluLen += sampleLen;
      nbNalu += nbUnits;
      sample.length = sampleLen;
      if (sample.dts < dtsStep) {
        sample.dts = dtsStep;
        dtsStep += averageSampleDuration / 4 | 0 || 1;
      } else {
        dtsStep = sample.dts;
      }
      minPTS = Math.min(sample.pts, minPTS);
      maxPTS = Math.max(sample.pts, maxPTS);
    }
    lastDTS = inputSamples[nbSamples - 1].dts;
    const mdatSize = naluLen + 4 * nbNalu + 8;
    let mdat;
    try {
      mdat = new Uint8Array(mdatSize);
    } catch (err) {
      this.observer.emit(Events.ERROR, Events.ERROR, {
        type: ErrorTypes.MUX_ERROR,
        details: ErrorDetails.REMUX_ALLOC_ERROR,
        fatal: false,
        error: err,
        bytes: mdatSize,
        reason: `fail allocating video mdat ${mdatSize}`
      });
      return;
    }
    const view2 = new DataView(mdat.buffer);
    view2.setUint32(0, mdatSize);
    mdat.set(MP4.types.mdat, 4);
    let stretchedLastFrame = false;
    let minDtsDelta = Number.POSITIVE_INFINITY;
    let minPtsDelta = Number.POSITIVE_INFINITY;
    let maxDtsDelta = Number.NEGATIVE_INFINITY;
    let maxPtsDelta = Number.NEGATIVE_INFINITY;
    for (let i = 0; i < nbSamples; i++) {
      const VideoSample = inputSamples[i];
      const VideoSampleUnits = VideoSample.units;
      let mp4SampleLength = 0;
      for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {
        const unit = VideoSampleUnits[j];
        const unitData = unit.data;
        const unitDataLen = unit.data.byteLength;
        view2.setUint32(offset, unitDataLen);
        offset += 4;
        mdat.set(unitData, offset);
        offset += unitDataLen;
        mp4SampleLength += 4 + unitDataLen;
      }
      let ptsDelta;
      if (i < nbSamples - 1) {
        mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;
        ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;
      } else {
        const config = this.config;
        const lastFrameDuration = i > 0 ? VideoSample.dts - inputSamples[i - 1].dts : averageSampleDuration;
        ptsDelta = i > 0 ? VideoSample.pts - inputSamples[i - 1].pts : averageSampleDuration;
        if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
          const gapTolerance = Math.floor(config.maxBufferHole * timeScale);
          const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - VideoSample.pts;
          if (deltaToFrameEnd > gapTolerance) {
            mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
            if (mp4SampleDuration < 0) {
              mp4SampleDuration = lastFrameDuration;
            } else {
              stretchedLastFrame = true;
            }
            this.logger.log(`[mp4-remuxer]: It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);
          } else {
            mp4SampleDuration = lastFrameDuration;
          }
        } else {
          mp4SampleDuration = lastFrameDuration;
        }
      }
      const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
      minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
      maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
      minPtsDelta = Math.min(minPtsDelta, ptsDelta);
      maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
      outputSamples.push(createMp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
    }
    if (outputSamples.length) {
      if (chromeVersion) {
        if (chromeVersion < 70) {
          const flags = outputSamples[0].flags;
          flags.dependsOn = 2;
          flags.isNonSync = 0;
        }
      } else if (safariWebkitVersion) {
        if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
          this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");
          let dts = firstDTS;
          for (let i = 0, len = outputSamples.length; i < len; i++) {
            const nextDts = dts + outputSamples[i].duration;
            const pts = dts + outputSamples[i].cts;
            if (i < len - 1) {
              const nextPts = nextDts + outputSamples[i + 1].cts;
              outputSamples[i].duration = nextPts - pts;
            } else {
              outputSamples[i].duration = i ? outputSamples[i - 1].duration : averageSampleDuration;
            }
            outputSamples[i].cts = 0;
            dts = nextDts;
          }
        }
      }
    }
    mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
    this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
    this.videoSampleDuration = mp4SampleDuration;
    this.isVideoContiguous = true;
    const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends(track, {
      samples: outputSamples
    }));
    const type2 = "video";
    const data = {
      data1: moof,
      data2: mdat,
      startPTS: minPTS / timeScale,
      endPTS: (maxPTS + mp4SampleDuration) / timeScale,
      startDTS: firstDTS / timeScale,
      endDTS: nextAvcDts / timeScale,
      type: type2,
      hasAudio: false,
      hasVideo: true,
      nb: outputSamples.length,
      dropped: track.dropped
    };
    track.samples = [];
    track.dropped = 0;
    return data;
  }
  getSamplesPerFrame(track) {
    switch (track.segmentCodec) {
      case "mp3":
        return MPEG_AUDIO_SAMPLE_PER_FRAME;
      case "ac3":
        return AC3_SAMPLES_PER_FRAME;
      default:
        return AAC_SAMPLES_PER_FRAME;
    }
  }
  remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
    const inputTimeScale = track.inputTimeScale;
    const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
    const scaleFactor = inputTimeScale / mp4timeScale;
    const mp4SampleDuration = this.getSamplesPerFrame(track);
    const inputSampleDuration = mp4SampleDuration * scaleFactor;
    const initPTS = this._initPTS;
    const rawMPEG = track.segmentCodec === "mp3" && this.typeSupported.mpeg;
    const outputSamples = [];
    const alignedWithVideo = videoTimeOffset !== void 0;
    let inputSamples = track.samples;
    let offset = rawMPEG ? 0 : 8;
    let nextAudioPts = this.nextAudioPts || -1;
    const timeOffsetMpegTS = timeOffset * inputTimeScale;
    const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
    this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9e3 || Math.abs(normalizePts(inputSamples[0].pts - initTime, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration);
    inputSamples.forEach(function(sample) {
      sample.pts = normalizePts(sample.pts - initTime, timeOffsetMpegTS);
    });
    if (!contiguous || nextAudioPts < 0) {
      inputSamples = inputSamples.filter((sample) => sample.pts >= 0);
      if (!inputSamples.length) {
        return;
      }
      if (videoTimeOffset === 0) {
        nextAudioPts = 0;
      } else if (accurateTimeOffset && !alignedWithVideo) {
        nextAudioPts = Math.max(0, timeOffsetMpegTS);
      } else {
        nextAudioPts = inputSamples[0].pts;
      }
    }
    if (track.segmentCodec === "aac") {
      const maxAudioFramesDrift = this.config.maxAudioFramesDrift;
      for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {
        const sample = inputSamples[i];
        const pts = sample.pts;
        const delta = pts - nextPts;
        const duration5 = Math.abs(1e3 * delta / inputTimeScale);
        if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
          if (i === 0) {
            this.logger.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3 * delta / inputTimeScale)} ms.`);
            this.nextAudioPts = nextAudioPts = nextPts = pts;
          }
        } else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration5 < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
          let missing = Math.round(delta / inputSampleDuration);
          nextPts = pts - missing * inputSampleDuration;
          if (nextPts < 0) {
            missing--;
            nextPts += inputSampleDuration;
          }
          if (i === 0) {
            this.nextAudioPts = nextAudioPts = nextPts;
          }
          this.logger.warn(`[mp4-remuxer]: Injecting ${missing} audio frame @ ${(nextPts / inputTimeScale).toFixed(3)}s due to ${Math.round(1e3 * delta / inputTimeScale)} ms gap.`);
          for (let j = 0; j < missing; j++) {
            const newStamp = Math.max(nextPts, 0);
            let fillFrame = AAC.getSilentFrame(track.parsedCodec || track.manifestCodec || track.codec, track.channelCount);
            if (!fillFrame) {
              this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.");
              fillFrame = sample.unit.subarray();
            }
            inputSamples.splice(i, 0, {
              unit: fillFrame,
              pts: newStamp
            });
            nextPts += inputSampleDuration;
            i++;
          }
        }
        sample.pts = nextPts;
        nextPts += inputSampleDuration;
      }
    }
    let firstPTS = null;
    let lastPTS = null;
    let mdat;
    let mdatSize = 0;
    let sampleLength = inputSamples.length;
    while (sampleLength--) {
      mdatSize += inputSamples[sampleLength].unit.byteLength;
    }
    for (let j = 0, _nbSamples = inputSamples.length; j < _nbSamples; j++) {
      const audioSample = inputSamples[j];
      const unit = audioSample.unit;
      let pts = audioSample.pts;
      if (lastPTS !== null) {
        const prevSample = outputSamples[j - 1];
        prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);
      } else {
        if (contiguous && track.segmentCodec === "aac") {
          pts = nextAudioPts;
        }
        firstPTS = pts;
        if (mdatSize > 0) {
          mdatSize += offset;
          try {
            mdat = new Uint8Array(mdatSize);
          } catch (err) {
            this.observer.emit(Events.ERROR, Events.ERROR, {
              type: ErrorTypes.MUX_ERROR,
              details: ErrorDetails.REMUX_ALLOC_ERROR,
              fatal: false,
              error: err,
              bytes: mdatSize,
              reason: `fail allocating audio mdat ${mdatSize}`
            });
            return;
          }
          if (!rawMPEG) {
            const view2 = new DataView(mdat.buffer);
            view2.setUint32(0, mdatSize);
            mdat.set(MP4.types.mdat, 4);
          }
        } else {
          return;
        }
      }
      mdat.set(unit, offset);
      const unitLen = unit.byteLength;
      offset += unitLen;
      outputSamples.push(createMp4Sample(true, mp4SampleDuration, unitLen, 0));
      lastPTS = pts;
    }
    const nbSamples = outputSamples.length;
    if (!nbSamples) {
      return;
    }
    const lastSample = outputSamples[outputSamples.length - 1];
    this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration;
    const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
      samples: outputSamples
    }));
    track.samples = [];
    const start2 = firstPTS / inputTimeScale;
    const end = nextAudioPts / inputTimeScale;
    const type2 = "audio";
    const audioData = {
      data1: moof,
      data2: mdat,
      startPTS: start2,
      endPTS: end,
      startDTS: start2,
      endDTS: end,
      type: type2,
      hasAudio: true,
      hasVideo: false,
      nb: nbSamples
    };
    this.isAudioContiguous = true;
    return audioData;
  }
};
function normalizePts(value, reference) {
  let offset;
  if (reference === null) {
    return value;
  }
  if (reference < value) {
    offset = -8589934592;
  } else {
    offset = 8589934592;
  }
  while (Math.abs(value - reference) > 4294967296) {
    value += offset;
  }
  return value;
}
function findKeyframeIndex(samples) {
  for (let i = 0; i < samples.length; i++) {
    if (samples[i].key) {
      return i;
    }
  }
  return -1;
}
function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  const length = track.samples.length;
  if (!length) {
    return;
  }
  const inputTimeScale = track.inputTimeScale;
  for (let index = 0; index < length; index++) {
    const sample = track.samples[index];
    sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
    sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  }
  const samples = track.samples;
  track.samples = [];
  return {
    samples
  };
}
function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  const length = track.samples.length;
  if (!length) {
    return;
  }
  const inputTimeScale = track.inputTimeScale;
  for (let index = 0; index < length; index++) {
    const sample = track.samples[index];
    sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  }
  track.samples.sort((a, b) => a.pts - b.pts);
  const samples = track.samples;
  track.samples = [];
  return {
    samples
  };
}
var PassThroughRemuxer = class {
  constructor(observer, config, typeSupported, logger4) {
    this.logger = void 0;
    this.emitInitSegment = false;
    this.audioCodec = void 0;
    this.videoCodec = void 0;
    this.initData = void 0;
    this.initPTS = null;
    this.initTracks = void 0;
    this.lastEndTime = null;
    this.logger = logger4;
  }
  destroy() {
  }
  resetTimeStamp(defaultInitPTS) {
    this.initPTS = defaultInitPTS;
    this.lastEndTime = null;
  }
  resetNextTimestamp() {
    this.lastEndTime = null;
  }
  resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
    this.audioCodec = audioCodec;
    this.videoCodec = videoCodec;
    this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
    this.emitInitSegment = true;
  }
  generateInitSegment(initSegment) {
    let {
      audioCodec,
      videoCodec
    } = this;
    if (!(initSegment != null && initSegment.byteLength)) {
      this.initTracks = void 0;
      this.initData = void 0;
      return;
    }
    const initData = this.initData = parseInitSegment(initSegment);
    if (initData.audio) {
      audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO);
    }
    if (initData.video) {
      videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO);
    }
    const tracks = {};
    if (initData.audio && initData.video) {
      tracks.audiovideo = {
        container: "video/mp4",
        codec: audioCodec + "," + videoCodec,
        supplemental: initData.video.supplemental,
        initSegment,
        id: "main"
      };
    } else if (initData.audio) {
      tracks.audio = {
        container: "audio/mp4",
        codec: audioCodec,
        initSegment,
        id: "audio"
      };
    } else if (initData.video) {
      tracks.video = {
        container: "video/mp4",
        codec: videoCodec,
        supplemental: initData.video.supplemental,
        initSegment,
        id: "main"
      };
    } else {
      this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.");
    }
    this.initTracks = tracks;
  }
  remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
    var _initData, _initData2;
    let {
      initPTS,
      lastEndTime
    } = this;
    const result = {
      audio: void 0,
      video: void 0,
      text: textTrack,
      id3: id3Track,
      initSegment: void 0
    };
    if (!isFiniteNumber(lastEndTime)) {
      lastEndTime = this.lastEndTime = timeOffset || 0;
    }
    const data = videoTrack.samples;
    if (!(data != null && data.length)) {
      return result;
    }
    const initSegment = {
      initPTS: void 0,
      timescale: 1
    };
    let initData = this.initData;
    if (!((_initData = initData) != null && _initData.length)) {
      this.generateInitSegment(data);
      initData = this.initData;
    }
    if (!((_initData2 = initData) != null && _initData2.length)) {
      this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment.");
      return result;
    }
    if (this.emitInitSegment) {
      initSegment.tracks = this.initTracks;
      this.emitInitSegment = false;
    }
    const duration5 = getDuration(data, initData);
    const startDTS = getStartDTS(initData, data);
    const decodeTime = startDTS === null ? timeOffset : startDTS;
    if ((accurateTimeOffset || !initPTS) && (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration5) || initSegment.timescale !== initPTS.timescale)) {
      initSegment.initPTS = decodeTime - timeOffset;
      if (initPTS && initPTS.timescale === 1) {
        this.logger.warn(`Adjusting initPTS @${timeOffset} from ${initPTS.baseTime / initPTS.timescale} to ${initSegment.initPTS}`);
      }
      this.initPTS = initPTS = {
        baseTime: initSegment.initPTS,
        timescale: 1
      };
    }
    const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
    const endTime = startTime + duration5;
    offsetStartDTS(initData, data, initPTS.baseTime / initPTS.timescale);
    if (duration5 > 0) {
      this.lastEndTime = endTime;
    } else {
      this.logger.warn("Duration parsed from mp4 should be greater than zero");
      this.resetNextTimestamp();
    }
    const hasAudio = !!initData.audio;
    const hasVideo = !!initData.video;
    let type2 = "";
    if (hasAudio) {
      type2 += "audio";
    }
    if (hasVideo) {
      type2 += "video";
    }
    const track = {
      data1: data,
      startPTS: startTime,
      startDTS: startTime,
      endPTS: endTime,
      endDTS: endTime,
      type: type2,
      hasAudio,
      hasVideo,
      nb: 1,
      dropped: 0
    };
    result.audio = track.type === "audio" ? track : void 0;
    result.video = track.type !== "audio" ? track : void 0;
    result.initSegment = initSegment;
    result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
    if (textTrack.samples.length) {
      result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
    }
    return result;
  }
};
function isInvalidInitPts(initPTS, startDTS, timeOffset, duration5) {
  if (initPTS === null) {
    return true;
  }
  const minDuration = Math.max(duration5, 1);
  const startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  return Math.abs(startTime - timeOffset) > minDuration;
}
function getParsedTrackCodec(track, type2) {
  const parsedCodec = track == null ? void 0 : track.codec;
  if (parsedCodec && parsedCodec.length > 4) {
    return parsedCodec;
  }
  if (type2 === ElementaryStreamTypes.AUDIO) {
    if (parsedCodec === "ec-3" || parsedCodec === "ac-3" || parsedCodec === "alac") {
      return parsedCodec;
    }
    if (parsedCodec === "fLaC" || parsedCodec === "Opus") {
      const preferManagedMediaSource = false;
      return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
    }
    logger.warn(`Unhandled audio codec "${parsedCodec}" in mp4 MAP`);
    return parsedCodec || "mp4a";
  }
  logger.warn(`Unhandled video codec "${parsedCodec}" in mp4 MAP`);
  return parsedCodec || "avc1";
}
var now;
try {
  now = self.performance.now.bind(self.performance);
} catch (err) {
  now = Date.now;
}
var muxConfig = [{
  demux: MP4Demuxer,
  remux: PassThroughRemuxer
}, {
  demux: TSDemuxer,
  remux: MP4Remuxer
}, {
  demux: AACDemuxer,
  remux: MP4Remuxer
}, {
  demux: MP3Demuxer,
  remux: MP4Remuxer
}];
{
  muxConfig.splice(2, 0, {
    demux: AC3Demuxer,
    remux: MP4Remuxer
  });
}
var Transmuxer = class {
  constructor(observer, typeSupported, config, vendor, id, logger4) {
    this.asyncResult = false;
    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 = observer;
    this.typeSupported = typeSupported;
    this.config = config;
    this.id = id;
    this.logger = logger4;
  }
  configure(transmuxConfig) {
    this.transmuxConfig = transmuxConfig;
    if (this.decrypter) {
      this.decrypter.reset();
    }
  }
  push(data, decryptdata, chunkMeta, state) {
    const stats = chunkMeta.transmuxing;
    stats.executeStart = now();
    let uintData = new Uint8Array(data);
    const {
      currentTransmuxState,
      transmuxConfig
    } = this;
    if (state) {
      this.currentTransmuxState = state;
    }
    const {
      contiguous,
      discontinuity,
      trackSwitch,
      accurateTimeOffset,
      timeOffset,
      initSegmentChange
    } = state || currentTransmuxState;
    const {
      audioCodec,
      videoCodec,
      defaultInitPts,
      duration: duration5,
      initSegmentData
    } = transmuxConfig;
    const keyData = getEncryptionType(uintData, decryptdata);
    if (keyData && isFullSegmentEncryption(keyData.method)) {
      const decrypter = this.getDecrypter();
      const aesMode = getAesModeFromFullSegmentMethod(keyData.method);
      if (decrypter.isSync()) {
        let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode);
        const loadingParts = chunkMeta.part > -1;
        if (loadingParts) {
          const _data = decrypter.flush();
          decryptedData = _data ? _data.buffer : _data;
        }
        if (!decryptedData) {
          stats.executeEnd = now();
          return emptyResult(chunkMeta);
        }
        uintData = new Uint8Array(decryptedData);
      } else {
        this.asyncResult = true;
        this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode).then((decryptedData) => {
          const result2 = this.push(decryptedData, null, chunkMeta);
          this.decryptionPromise = null;
          return result2;
        });
        return this.decryptionPromise;
      }
    }
    const resetMuxers = this.needsProbing(discontinuity, trackSwitch);
    if (resetMuxers) {
      const error = this.configureTransmuxer(uintData);
      if (error) {
        this.logger.warn(`[transmuxer] ${error.message}`);
        this.observer.emit(Events.ERROR, Events.ERROR, {
          type: ErrorTypes.MEDIA_ERROR,
          details: ErrorDetails.FRAG_PARSING_ERROR,
          fatal: false,
          error,
          reason: error.message
        });
        stats.executeEnd = now();
        return emptyResult(chunkMeta);
      }
    }
    if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
      this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration5, decryptdata);
    }
    if (discontinuity || initSegmentChange || resetMuxers) {
      this.resetInitialTimestamp(defaultInitPts);
    }
    if (!contiguous) {
      this.resetContiguity();
    }
    const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
    this.asyncResult = isPromise(result);
    const currentState = this.currentTransmuxState;
    currentState.contiguous = true;
    currentState.discontinuity = false;
    currentState.trackSwitch = false;
    stats.executeEnd = now();
    return result;
  }
  // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  flush(chunkMeta) {
    const stats = chunkMeta.transmuxing;
    stats.executeStart = now();
    const {
      decrypter,
      currentTransmuxState,
      decryptionPromise
    } = this;
    if (decryptionPromise) {
      this.asyncResult = true;
      return decryptionPromise.then(() => {
        return this.flush(chunkMeta);
      });
    }
    const transmuxResults = [];
    const {
      timeOffset
    } = currentTransmuxState;
    if (decrypter) {
      const decryptedData = decrypter.flush();
      if (decryptedData) {
        transmuxResults.push(this.push(decryptedData.buffer, null, chunkMeta));
      }
    }
    const {
      demuxer,
      remuxer
    } = this;
    if (!demuxer || !remuxer) {
      stats.executeEnd = now();
      const emptyResults = [emptyResult(chunkMeta)];
      if (this.asyncResult) {
        return Promise.resolve(emptyResults);
      }
      return emptyResults;
    }
    const demuxResultOrPromise = demuxer.flush(timeOffset);
    if (isPromise(demuxResultOrPromise)) {
      this.asyncResult = true;
      return demuxResultOrPromise.then((demuxResult) => {
        this.flushRemux(transmuxResults, demuxResult, chunkMeta);
        return transmuxResults;
      });
    }
    this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
    if (this.asyncResult) {
      return Promise.resolve(transmuxResults);
    }
    return transmuxResults;
  }
  flushRemux(transmuxResults, demuxResult, chunkMeta) {
    const {
      audioTrack,
      videoTrack,
      id3Track,
      textTrack
    } = demuxResult;
    const {
      accurateTimeOffset,
      timeOffset
    } = this.currentTransmuxState;
    this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${chunkMeta.sn}${chunkMeta.part > -1 ? " part: " + chunkMeta.part : ""} of ${this.id === PlaylistLevelType.MAIN ? "level" : "track"} ${chunkMeta.level}`);
    const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
    transmuxResults.push({
      remuxResult,
      chunkMeta
    });
    chunkMeta.transmuxing.executeEnd = now();
  }
  resetInitialTimestamp(defaultInitPts) {
    const {
      demuxer,
      remuxer
    } = this;
    if (!demuxer || !remuxer) {
      return;
    }
    demuxer.resetTimeStamp(defaultInitPts);
    remuxer.resetTimeStamp(defaultInitPts);
  }
  resetContiguity() {
    const {
      demuxer,
      remuxer
    } = this;
    if (!demuxer || !remuxer) {
      return;
    }
    demuxer.resetContiguity();
    remuxer.resetNextTimestamp();
  }
  resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
    const {
      demuxer,
      remuxer
    } = this;
    if (!demuxer || !remuxer) {
      return;
    }
    demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
    remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  }
  destroy() {
    if (this.demuxer) {
      this.demuxer.destroy();
      this.demuxer = void 0;
    }
    if (this.remuxer) {
      this.remuxer.destroy();
      this.remuxer = void 0;
    }
  }
  transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
    let result;
    if (keyData && keyData.method === "SAMPLE-AES") {
      result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
    } else {
      result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
    }
    return result;
  }
  transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
    const {
      audioTrack,
      videoTrack,
      id3Track,
      textTrack
    } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);
    const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
    return {
      remuxResult,
      chunkMeta
    };
  }
  transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
    return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then((demuxResult) => {
      const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);
      return {
        remuxResult,
        chunkMeta
      };
    });
  }
  configureTransmuxer(data) {
    const {
      config,
      observer,
      typeSupported
    } = this;
    let mux;
    for (let i = 0, len = muxConfig.length; i < len; i++) {
      var _muxConfig$i$demux;
      if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data, this.logger)) {
        mux = muxConfig[i];
        break;
      }
    }
    if (!mux) {
      return new Error("Failed to find demuxer by probing fragment data");
    }
    const demuxer = this.demuxer;
    const remuxer = this.remuxer;
    const Remuxer = mux.remux;
    const Demuxer = mux.demux;
    if (!remuxer || !(remuxer instanceof Remuxer)) {
      this.remuxer = new Remuxer(observer, config, typeSupported, this.logger);
    }
    if (!demuxer || !(demuxer instanceof Demuxer)) {
      this.demuxer = new Demuxer(observer, config, typeSupported, this.logger);
      this.probe = Demuxer.probe;
    }
  }
  needsProbing(discontinuity, trackSwitch) {
    return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  }
  getDecrypter() {
    let decrypter = this.decrypter;
    if (!decrypter) {
      decrypter = this.decrypter = new Decrypter(this.config);
    }
    return decrypter;
  }
};
function getEncryptionType(data, decryptData) {
  let encryptionType = null;
  if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
    encryptionType = decryptData;
  }
  return encryptionType;
}
var emptyResult = (chunkMeta) => ({
  remuxResult: {},
  chunkMeta
});
function isPromise(p) {
  return "then" in p && p.then instanceof Function;
}
var TransmuxConfig = class {
  constructor(audioCodec, videoCodec, initSegmentData, duration5, defaultInitPts) {
    this.audioCodec = void 0;
    this.videoCodec = void 0;
    this.initSegmentData = void 0;
    this.duration = void 0;
    this.defaultInitPts = void 0;
    this.audioCodec = audioCodec;
    this.videoCodec = videoCodec;
    this.initSegmentData = initSegmentData;
    this.duration = duration5;
    this.defaultInitPts = defaultInitPts || null;
  }
};
var TransmuxState = class {
  constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
    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 = discontinuity;
    this.contiguous = contiguous;
    this.accurateTimeOffset = accurateTimeOffset;
    this.trackSwitch = trackSwitch;
    this.timeOffset = timeOffset;
    this.initSegmentChange = initSegmentChange;
  }
};
var transmuxerInstanceCount = 0;
var TransmuxerInterface = class {
  constructor(_hls, id, onTransmuxComplete, onFlush) {
    this.error = null;
    this.hls = void 0;
    this.id = void 0;
    this.instanceNo = transmuxerInstanceCount++;
    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 = (event) => {
      const data = event.data;
      const hls = this.hls;
      if (!hls || !(data != null && data.event) || data.instanceNo !== this.instanceNo) {
        return;
      }
      switch (data.event) {
        case "init": {
          var _this$workerContext;
          const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
          if (objectURL) {
            self.URL.revokeObjectURL(objectURL);
          }
          break;
        }
        case "transmuxComplete": {
          this.handleTransmuxComplete(data.data);
          break;
        }
        case "flush": {
          this.onFlush(data.data);
          break;
        }
        // pass logs from the worker thread to the main logger
        case "workerLog": {
          if (hls.logger[data.data.logType]) {
            hls.logger[data.data.logType](data.data.message);
          }
          break;
        }
        default: {
          data.data = data.data || {};
          data.data.frag = this.frag;
          data.data.part = this.part;
          data.data.id = this.id;
          hls.trigger(data.event, data.data);
          break;
        }
      }
    };
    this.onWorkerError = (event) => {
      if (!this.hls) {
        return;
      }
      const error = new Error(`${event.message}  (${event.filename}:${event.lineno})`);
      this.hls.config.enableWorker = false;
      this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`);
      this.hls.trigger(Events.ERROR, {
        type: ErrorTypes.OTHER_ERROR,
        details: ErrorDetails.INTERNAL_EXCEPTION,
        fatal: false,
        event: "demuxerWorker",
        error
      });
    };
    const config = _hls.config;
    this.hls = _hls;
    this.id = id;
    this.useWorker = !!config.enableWorker;
    this.onTransmuxComplete = onTransmuxComplete;
    this.onFlush = onFlush;
    const forwardMessage = (ev, data) => {
      data = data || {};
      data.frag = this.frag || void 0;
      if (ev === Events.ERROR) {
        data = data;
        data.parent = this.id;
        data.part = this.part;
        this.error = data.error;
      }
      this.hls.trigger(ev, data);
    };
    this.observer = new EventEmitter();
    this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
    this.observer.on(Events.ERROR, forwardMessage);
    const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
    if (this.useWorker && typeof Worker !== "undefined") {
      const logger4 = this.hls.logger;
      const canCreateWorker = config.workerPath || hasUMDWorker();
      if (canCreateWorker) {
        try {
          if (config.workerPath) {
            logger4.log(`loading Web Worker ${config.workerPath} for "${id}"`);
            this.workerContext = loadWorker(config.workerPath);
          } else {
            logger4.log(`injecting Web Worker for "${id}"`);
            this.workerContext = injectWorker();
          }
          const {
            worker
          } = this.workerContext;
          worker.addEventListener("message", this.onWorkerMessage);
          worker.addEventListener("error", this.onWorkerError);
          worker.postMessage({
            instanceNo: this.instanceNo,
            cmd: "init",
            typeSupported: m2tsTypeSupported,
            id,
            config: stringify(config)
          });
        } catch (err) {
          logger4.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err);
          this.terminateWorker();
          this.error = null;
          this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id, _hls.logger);
        }
        return;
      }
    }
    this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id, _hls.logger);
  }
  reset() {
    this.frag = null;
    this.part = null;
    if (this.workerContext) {
      const instanceNo = this.instanceNo;
      this.instanceNo = transmuxerInstanceCount++;
      const config = this.hls.config;
      const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
      this.workerContext.worker.postMessage({
        instanceNo: this.instanceNo,
        cmd: "reset",
        resetNo: instanceNo,
        typeSupported: m2tsTypeSupported,
        id: this.id,
        config: stringify(config)
      });
    }
  }
  terminateWorker() {
    if (this.workerContext) {
      const {
        worker
      } = this.workerContext;
      this.workerContext = null;
      worker.removeEventListener("message", this.onWorkerMessage);
      worker.removeEventListener("error", this.onWorkerError);
      removeWorkerFromStore(this.hls.config.workerPath);
    }
  }
  destroy() {
    if (this.workerContext) {
      this.terminateWorker();
      this.onWorkerMessage = this.onWorkerError = null;
    } else {
      const transmuxer = this.transmuxer;
      if (transmuxer) {
        transmuxer.destroy();
        this.transmuxer = null;
      }
    }
    const observer = this.observer;
    if (observer) {
      observer.removeAllListeners();
    }
    this.frag = null;
    this.part = null;
    this.observer = null;
    this.hls = null;
  }
  push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration5, accurateTimeOffset, chunkMeta, defaultInitPTS) {
    var _frag$initSegment, _lastFrag$initSegment;
    chunkMeta.transmuxing.start = self.performance.now();
    const {
      instanceNo,
      transmuxer
    } = this;
    const timeOffset = part ? part.start : frag.start;
    const decryptdata = frag.decryptdata;
    const lastFrag = this.frag;
    const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
    const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
    const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
    const partDiff = this.part ? chunkMeta.part - this.part.index : -1;
    const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
    const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
    const now2 = self.performance.now();
    if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
      frag.stats.parsing.start = now2;
    }
    if (part && (partDiff || !contiguous)) {
      part.stats.parsing.start = now2;
    }
    const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
    const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
    if (!contiguous || discontinuity || initSegmentChange) {
      this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${frag.type} sn: ${chunkMeta.sn}${chunkMeta.part > -1 ? " part: " + chunkMeta.part : ""} ${this.id === PlaylistLevelType.MAIN ? "level" : "track"}: ${chunkMeta.level} id: ${chunkMeta.id}
        discontinuity: ${discontinuity}
        trackSwitch: ${trackSwitch}
        contiguous: ${contiguous}
        accurateTimeOffset: ${accurateTimeOffset}
        timeOffset: ${timeOffset}
        initSegmentChange: ${initSegmentChange}`);
      const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration5, defaultInitPTS);
      this.configureTransmuxer(config);
    }
    this.frag = frag;
    this.part = part;
    if (this.workerContext) {
      this.workerContext.worker.postMessage({
        instanceNo,
        cmd: "demux",
        data,
        decryptdata,
        chunkMeta,
        state
      }, data instanceof ArrayBuffer ? [data] : []);
    } else if (transmuxer) {
      const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
      if (isPromise(transmuxResult)) {
        transmuxResult.then((data2) => {
          this.handleTransmuxComplete(data2);
        }).catch((error) => {
          this.transmuxerError(error, chunkMeta, "transmuxer-interface push error");
        });
      } else {
        this.handleTransmuxComplete(transmuxResult);
      }
    }
  }
  flush(chunkMeta) {
    chunkMeta.transmuxing.start = self.performance.now();
    const {
      instanceNo,
      transmuxer
    } = this;
    if (this.workerContext) {
      this.workerContext.worker.postMessage({
        instanceNo,
        cmd: "flush",
        chunkMeta
      });
    } else if (transmuxer) {
      const transmuxResult = transmuxer.flush(chunkMeta);
      if (isPromise(transmuxResult)) {
        transmuxResult.then((data) => {
          this.handleFlushResult(data, chunkMeta);
        }).catch((error) => {
          this.transmuxerError(error, chunkMeta, "transmuxer-interface flush error");
        });
      } else {
        this.handleFlushResult(transmuxResult, chunkMeta);
      }
    }
  }
  transmuxerError(error, chunkMeta, reason) {
    if (!this.hls) {
      return;
    }
    this.error = error;
    this.hls.trigger(Events.ERROR, {
      type: ErrorTypes.MEDIA_ERROR,
      details: ErrorDetails.FRAG_PARSING_ERROR,
      chunkMeta,
      frag: this.frag || void 0,
      part: this.part || void 0,
      fatal: false,
      error,
      err: error,
      reason
    });
  }
  handleFlushResult(results, chunkMeta) {
    results.forEach((result) => {
      this.handleTransmuxComplete(result);
    });
    this.onFlush(chunkMeta);
  }
  configureTransmuxer(config) {
    const {
      instanceNo,
      transmuxer
    } = this;
    if (this.workerContext) {
      this.workerContext.worker.postMessage({
        instanceNo,
        cmd: "configure",
        config
      });
    } else if (transmuxer) {
      transmuxer.configure(config);
    }
  }
  handleTransmuxComplete(result) {
    result.chunkMeta.transmuxing.end = self.performance.now();
    this.onTransmuxComplete(result);
  }
};
var TICK_INTERVAL$3 = 100;
var AudioStreamController = class extends BaseStreamController {
  constructor(hls, fragmentTracker, keyLoader) {
    super(hls, fragmentTracker, keyLoader, "audio-stream-controller", PlaylistLevelType.AUDIO);
    this.mainAnchor = null;
    this.mainFragLoading = null;
    this.audioOnly = false;
    this.bufferedTrack = null;
    this.switchingTrack = null;
    this.trackId = -1;
    this.waitingData = null;
    this.mainDetails = null;
    this.flushing = false;
    this.bufferFlushed = false;
    this.cachedTrackLoadedData = null;
    this.registerListeners();
  }
  onHandlerDestroying() {
    this.unregisterListeners();
    super.onHandlerDestroying();
    this.resetItem();
  }
  resetItem() {
    this.mainDetails = this.mainAnchor = this.mainFragLoading = this.bufferedTrack = this.switchingTrack = this.waitingData = this.cachedTrackLoadedData = null;
  }
  registerListeners() {
    super.registerListeners();
    const {
      hls
    } = this;
    hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
    hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
    hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
    hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
    hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
    hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
    hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
    hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
    hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
    hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
    hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  }
  unregisterListeners() {
    const {
      hls
    } = this;
    if (!hls) {
      return;
    }
    super.unregisterListeners();
    hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
    hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
    hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
    hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
    hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
    hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
    hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
    hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
    hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
    hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
    hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  }
  // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
  onInitPtsFound(event, {
    frag,
    id,
    initPTS,
    timescale: timescale2
  }) {
    if (id === PlaylistLevelType.MAIN) {
      const cc = frag.cc;
      const inFlightFrag = this.fragCurrent;
      this.initPTS[cc] = {
        baseTime: initPTS,
        timescale: timescale2
      };
      this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}/${timescale2}`);
      this.mainAnchor = frag;
      if (this.state === State.WAITING_INIT_PTS) {
        const waitingData = this.waitingData;
        if (!waitingData && !this.loadingParts || waitingData && waitingData.frag.cc !== cc) {
          this.nextLoadPosition = this.findSyncFrag(frag).start;
        }
        this.tick();
      } else if (!this.hls.hasEnoughToStart && inFlightFrag && inFlightFrag.cc !== cc) {
        this.startFragRequested = false;
        this.nextLoadPosition = this.findSyncFrag(frag).start;
        inFlightFrag.abortRequests();
        this.resetLoadingState();
      } else if (this.state === State.IDLE) {
        this.tick();
      }
    }
  }
  findSyncFrag(mainFrag) {
    const trackDetails = this.getLevelDetails();
    const cc = mainFrag.cc;
    return findNearestWithCC(trackDetails, cc, mainFrag) || trackDetails && findFragWithCC(trackDetails.fragments, cc) || mainFrag;
  }
  startLoad(startPosition, skipSeekToStartPosition) {
    if (!this.levels) {
      this.startPosition = startPosition;
      this.state = State.STOPPED;
      return;
    }
    const lastCurrentTime = this.lastCurrentTime;
    this.stopLoad();
    this.setInterval(TICK_INTERVAL$3);
    if (lastCurrentTime > 0 && startPosition === -1) {
      this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
      startPosition = lastCurrentTime;
      this.state = State.IDLE;
    } else {
      this.state = State.WAITING_TRACK;
    }
    this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
    this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
    this.tick();
  }
  doTick() {
    switch (this.state) {
      case State.IDLE:
        this.doTickIdle();
        break;
      case State.WAITING_TRACK: {
        const {
          levels,
          trackId
        } = this;
        const currenTrack = levels == null ? void 0 : levels[trackId];
        const details = currenTrack == null ? void 0 : currenTrack.details;
        if (details && !this.waitForLive(currenTrack)) {
          if (this.waitForCdnTuneIn(details)) {
            break;
          }
          this.state = State.WAITING_INIT_PTS;
        }
        break;
      }
      case State.FRAG_LOADING_WAITING_RETRY: {
        var _this$media;
        const now2 = performance.now();
        const retryDate = this.retryDate;
        if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
          const {
            levels,
            trackId
          } = this;
          this.log("RetryDate reached, switch back to IDLE state");
          this.resetStartWhenNotLoaded((levels == null ? void 0 : levels[trackId]) || null);
          this.state = State.IDLE;
        }
        break;
      }
      case State.WAITING_INIT_PTS: {
        const waitingData = this.waitingData;
        if (waitingData) {
          const {
            frag,
            part,
            cache,
            complete
          } = waitingData;
          const mainAnchor = this.mainAnchor;
          if (this.initPTS[frag.cc] !== void 0) {
            this.waitingData = null;
            this.state = State.FRAG_LOADING;
            const payload = cache.flush().buffer;
            const data = {
              frag,
              part,
              payload,
              networkDetails: null
            };
            this._handleFragmentLoadProgress(data);
            if (complete) {
              super._handleFragmentLoadComplete(data);
            }
          } else if (mainAnchor && mainAnchor.cc !== waitingData.frag.cc) {
            this.log(`Waiting fragment cc (${frag.cc}) cancelled because video is at cc ${mainAnchor.cc}`);
            this.nextLoadPosition = this.findSyncFrag(mainAnchor).start;
            this.clearWaitingFragment();
          }
        } else {
          this.state = State.IDLE;
        }
      }
    }
    this.onTickEnd();
  }
  clearWaitingFragment() {
    const waitingData = this.waitingData;
    if (waitingData) {
      if (!this.hls.hasEnoughToStart) {
        this.startFragRequested = false;
      }
      this.fragmentTracker.removeFragment(waitingData.frag);
      this.waitingData = null;
      if (this.state !== State.STOPPED) {
        this.state = State.IDLE;
      }
    }
  }
  resetLoadingState() {
    this.clearWaitingFragment();
    super.resetLoadingState();
  }
  onTickEnd() {
    const {
      media
    } = this;
    if (!(media != null && media.readyState)) {
      return;
    }
    this.lastCurrentTime = media.currentTime;
  }
  doTickIdle() {
    var _this$mainFragLoading;
    const {
      hls,
      levels,
      media,
      trackId
    } = this;
    const config = hls.config;
    if (!this.buffering || !media && !this.primaryPrefetch && (this.startFragRequested || !config.startFragPrefetch) || !(levels != null && levels[trackId])) {
      return;
    }
    const levelInfo = levels[trackId];
    const trackDetails = levelInfo.details;
    if (!trackDetails || this.waitForLive(levelInfo) || this.waitForCdnTuneIn(trackDetails)) {
      this.state = State.WAITING_TRACK;
      this.startFragRequested = false;
      return;
    }
    const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;
    if (this.bufferFlushed && bufferable) {
      this.bufferFlushed = false;
      this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO);
    }
    const bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO);
    if (bufferInfo === null) {
      return;
    }
    if (!this.switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {
      hls.trigger(Events.BUFFER_EOS, {
        type: "audio"
      });
      this.state = State.ENDED;
      return;
    }
    const bufferLen = bufferInfo.len;
    const maxBufLen = hls.maxBufferLength;
    const fragments = trackDetails.fragments;
    const start2 = fragments[0].start;
    const loadPosition = this.getLoadPosition();
    const targetBufferTime = this.flushing ? loadPosition : bufferInfo.end;
    if (this.switchingTrack && media) {
      const pos = loadPosition;
      if (trackDetails.PTSKnown && pos < start2) {
        if (bufferInfo.end > start2 || bufferInfo.nextStart) {
          this.log("Alt audio track ahead of main track, seek to start of alt audio track");
          media.currentTime = start2 + 0.05;
        }
      }
    }
    if (bufferLen >= maxBufLen && !this.switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) {
      return;
    }
    let frag = this.getNextFragment(targetBufferTime, trackDetails);
    if (frag && this.isLoopLoading(frag, targetBufferTime)) {
      frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
    }
    if (!frag) {
      this.bufferFlushed = true;
      return;
    }
    let mainFragLoading = ((_this$mainFragLoading = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading.frag) || null;
    if (!this.audioOnly && this.startFragRequested && mainFragLoading && isMediaFragment(frag) && !frag.endList && (!trackDetails.live || !this.loadingParts && targetBufferTime < this.hls.liveSyncPosition)) {
      if (this.fragmentTracker.getState(mainFragLoading) === FragmentState.OK) {
        this.mainFragLoading = mainFragLoading = null;
      }
      if (mainFragLoading && isMediaFragment(mainFragLoading)) {
        if (frag.start > mainFragLoading.end) {
          const mainFragAtPos = this.fragmentTracker.getFragAtPos(targetBufferTime, PlaylistLevelType.MAIN);
          if (mainFragAtPos && mainFragAtPos.end > mainFragLoading.end) {
            mainFragLoading = mainFragAtPos;
            this.mainFragLoading = {
              frag: mainFragAtPos,
              targetBufferTime: null
            };
          }
        }
        const atBufferSyncLimit = frag.start > mainFragLoading.end;
        if (atBufferSyncLimit) {
          return;
        }
      }
    }
    this.loadFragment(frag, levelInfo, targetBufferTime);
  }
  onMediaDetaching(event, data) {
    this.bufferFlushed = this.flushing = false;
    super.onMediaDetaching(event, data);
  }
  onAudioTracksUpdated(event, {
    audioTracks
  }) {
    this.resetTransmuxer();
    this.levels = audioTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
  }
  onAudioTrackSwitching(event, data) {
    const altAudio = !!data.url;
    this.trackId = data.id;
    const {
      fragCurrent
    } = this;
    if (fragCurrent) {
      fragCurrent.abortRequests();
      this.removeUnbufferedFrags(fragCurrent.start);
    }
    this.resetLoadingState();
    if (altAudio) {
      this.switchingTrack = data;
      this.flushAudioIfNeeded(data);
      if (this.state !== State.STOPPED) {
        this.setInterval(TICK_INTERVAL$3);
        this.state = State.IDLE;
        this.tick();
      }
    } else {
      this.resetTransmuxer();
      this.switchingTrack = null;
      this.bufferedTrack = data;
      this.clearInterval();
    }
  }
  onManifestLoading() {
    super.onManifestLoading();
    this.bufferFlushed = this.flushing = this.audioOnly = false;
    this.resetItem();
    this.trackId = -1;
  }
  onLevelLoaded(event, data) {
    this.mainDetails = data.details;
    const cachedTrackLoadedData = this.cachedTrackLoadedData;
    if (cachedTrackLoadedData) {
      this.cachedTrackLoadedData = null;
      this.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED, cachedTrackLoadedData);
    }
  }
  onAudioTrackLoaded(event, data) {
    var _trackLevel$details;
    const {
      levels
    } = this;
    const {
      details: newDetails,
      id: trackId,
      groupId,
      track
    } = data;
    if (!levels) {
      this.warn(`Audio tracks reset while loading track ${trackId} "${track.name}" of "${groupId}"`);
      return;
    }
    const mainDetails = this.mainDetails;
    if (!mainDetails || newDetails.endCC > mainDetails.endCC || mainDetails.expired) {
      this.cachedTrackLoadedData = data;
      if (this.state !== State.STOPPED) {
        this.state = State.WAITING_TRACK;
      }
      return;
    }
    this.cachedTrackLoadedData = null;
    this.log(`Audio track ${trackId} "${track.name}" of "${groupId}" loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
    const trackLevel = levels[trackId];
    let sliding = 0;
    if (newDetails.live || (_trackLevel$details = trackLevel.details) != null && _trackLevel$details.live) {
      this.checkLiveUpdate(newDetails);
      if (newDetails.deltaUpdateFailed) {
        return;
      }
      if (trackLevel.details) {
        var _this$levelLastLoaded;
        sliding = this.alignPlaylists(newDetails, trackLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
      }
      if (!newDetails.alignedSliding) {
        alignDiscontinuities(newDetails, mainDetails);
        if (!newDetails.alignedSliding) {
          alignMediaPlaylistByPDT(newDetails, mainDetails);
        }
        sliding = newDetails.fragmentStart;
      }
    }
    trackLevel.details = newDetails;
    this.levelLastLoaded = trackLevel;
    if (!this.startFragRequested) {
      this.setStartPosition(mainDetails, sliding);
    }
    this.hls.trigger(Events.AUDIO_TRACK_UPDATED, {
      details: newDetails,
      id: trackId,
      groupId: data.groupId
    });
    if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
      this.state = State.IDLE;
    }
    this.tick();
  }
  _handleFragmentLoadProgress(data) {
    var _frag$initSegment;
    const frag = data.frag;
    const {
      part,
      payload
    } = data;
    const {
      config,
      trackId,
      levels
    } = this;
    if (!levels) {
      this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
      return;
    }
    const track = levels[trackId];
    if (!track) {
      this.warn("Audio track is undefined on fragment load progress");
      return;
    }
    const details = track.details;
    if (!details) {
      this.warn("Audio track details undefined on fragment load progress");
      this.removeUnbufferedFrags(frag.start);
      return;
    }
    const audioCodec = config.defaultAudioCodec || track.audioCodec || "mp4a.40.2";
    let transmuxer = this.transmuxer;
    if (!transmuxer) {
      transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
    }
    const initPTS = this.initPTS[frag.cc];
    const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
    if (initPTS !== void 0) {
      const accurateTimeOffset = false;
      const partIndex = part ? part.index : -1;
      const partial = partIndex !== -1;
      const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
      transmuxer.push(payload, initSegmentData, audioCodec, "", frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
    } else {
      this.log(`Unknown video PTS for cc ${frag.cc}, waiting for video PTS before demuxing audio frag ${frag.sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
      const {
        cache
      } = this.waitingData = this.waitingData || {
        frag,
        part,
        cache: new ChunkCache(),
        complete: false
      };
      cache.push(new Uint8Array(payload));
      if (this.state !== State.STOPPED) {
        this.state = State.WAITING_INIT_PTS;
      }
    }
  }
  _handleFragmentLoadComplete(fragLoadedData) {
    if (this.waitingData) {
      this.waitingData.complete = true;
      return;
    }
    super._handleFragmentLoadComplete(fragLoadedData);
  }
  onBufferReset() {
    this.mediaBuffer = null;
  }
  onBufferCreated(event, data) {
    this.bufferFlushed = this.flushing = false;
    const audioTrack = data.tracks.audio;
    if (audioTrack) {
      this.mediaBuffer = audioTrack.buffer || null;
    }
  }
  onFragLoading(event, data) {
    if (!this.audioOnly && data.frag.type === PlaylistLevelType.MAIN && isMediaFragment(data.frag)) {
      this.mainFragLoading = data;
      if (this.state === State.IDLE) {
        this.tick();
      }
    }
  }
  onFragBuffered(event, data) {
    const {
      frag,
      part
    } = data;
    if (frag.type !== PlaylistLevelType.AUDIO) {
      if (!this.audioOnly && frag.type === PlaylistLevelType.MAIN && !frag.elementaryStreams.video && !frag.elementaryStreams.audiovideo) {
        this.audioOnly = true;
        this.mainFragLoading = null;
      }
      return;
    }
    if (this.fragContextChanged(frag)) {
      this.warn(`Fragment ${frag.sn}${part ? " p: " + part.index : ""} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack ? this.switchingTrack.name : "false"}`);
      return;
    }
    if (isMediaFragment(frag)) {
      this.fragPrevious = frag;
      const track = this.switchingTrack;
      if (track) {
        this.bufferedTrack = track;
        this.switchingTrack = null;
        this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, track));
      }
    }
    this.fragBufferedComplete(frag, part);
    if (this.media) {
      this.tick();
    }
  }
  onError(event, data) {
    var _data$context;
    if (data.fatal) {
      this.state = State.ERROR;
      return;
    }
    switch (data.details) {
      case ErrorDetails.FRAG_GAP:
      case ErrorDetails.FRAG_PARSING_ERROR:
      case ErrorDetails.FRAG_DECRYPT_ERROR:
      case ErrorDetails.FRAG_LOAD_ERROR:
      case ErrorDetails.FRAG_LOAD_TIMEOUT:
      case ErrorDetails.KEY_LOAD_ERROR:
      case ErrorDetails.KEY_LOAD_TIMEOUT:
        this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);
        break;
      case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
      case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
      case ErrorDetails.LEVEL_PARSING_ERROR:
        if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) {
          this.state = State.IDLE;
        }
        break;
      case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
      case ErrorDetails.BUFFER_APPEND_ERROR:
        if (data.parent !== "audio") {
          return;
        }
        this.resetLoadingState();
        break;
      case ErrorDetails.BUFFER_FULL_ERROR:
        if (data.parent !== "audio") {
          return;
        }
        if (this.reduceLengthAndFlushBuffer(data)) {
          this.bufferedTrack = null;
          super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
        }
        break;
      case ErrorDetails.INTERNAL_EXCEPTION:
        this.recoverWorkerError(data);
        break;
    }
  }
  onBufferFlushing(event, {
    type: type2
  }) {
    if (type2 !== ElementaryStreamTypes.VIDEO) {
      this.flushing = true;
    }
  }
  onBufferFlushed(event, {
    type: type2
  }) {
    if (type2 !== ElementaryStreamTypes.VIDEO) {
      this.flushing = false;
      this.bufferFlushed = true;
      if (this.state === State.ENDED) {
        this.state = State.IDLE;
      }
      const mediaBuffer = this.mediaBuffer || this.media;
      if (mediaBuffer) {
        this.afterBufferFlushed(mediaBuffer, type2, PlaylistLevelType.AUDIO);
        this.tick();
      }
    }
  }
  _handleTransmuxComplete(transmuxResult) {
    var _id3$samples;
    const id = "audio";
    const {
      hls
    } = this;
    const {
      remuxResult,
      chunkMeta
    } = transmuxResult;
    const context = this.getCurrentContext(chunkMeta);
    if (!context) {
      this.resetWhenMissingContext(chunkMeta);
      return;
    }
    const {
      frag,
      part,
      level
    } = context;
    const {
      details
    } = level;
    const {
      audio,
      text,
      id3,
      initSegment
    } = remuxResult;
    if (this.fragContextChanged(frag) || !details) {
      this.fragmentTracker.removeFragment(frag);
      return;
    }
    this.state = State.PARSING;
    if (this.switchingTrack && audio) {
      this.completeAudioSwitch(this.switchingTrack);
    }
    if (initSegment != null && initSegment.tracks) {
      const mapFragment = frag.initSegment || frag;
      this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
      hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
        frag: mapFragment,
        id,
        tracks: initSegment.tracks
      });
    }
    if (audio) {
      const {
        startPTS,
        endPTS,
        startDTS,
        endDTS
      } = audio;
      if (part) {
        part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
          startPTS,
          endPTS,
          startDTS,
          endDTS
        };
      }
      frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
      this.bufferFragmentData(audio, frag, part, chunkMeta);
    }
    if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
      const emittedID3 = _extends({
        id,
        frag,
        details
      }, id3);
      hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
    }
    if (text) {
      const emittedText = _extends({
        id,
        frag,
        details
      }, text);
      hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
    }
  }
  _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
    if (this.state !== State.PARSING) {
      return;
    }
    if (tracks.video) {
      delete tracks.video;
    }
    if (tracks.audiovideo) {
      delete tracks.audiovideo;
    }
    if (!tracks.audio) {
      return;
    }
    const track = tracks.audio;
    track.id = PlaylistLevelType.AUDIO;
    const variantAudioCodecs = currentLevel.audioCodec;
    this.log(`Init audio buffer, container:${track.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track.codec}]`);
    if (variantAudioCodecs && variantAudioCodecs.split(",").length === 1) {
      track.levelCodec = variantAudioCodecs;
    }
    this.hls.trigger(Events.BUFFER_CODECS, tracks);
    const initSegment = track.initSegment;
    if (initSegment != null && initSegment.byteLength) {
      const segment = {
        type: "audio",
        frag,
        part: null,
        chunkMeta,
        parent: frag.type,
        data: initSegment
      };
      this.hls.trigger(Events.BUFFER_APPENDING, segment);
    }
    this.tickImmediate();
  }
  loadFragment(frag, track, targetBufferTime) {
    const fragState = this.fragmentTracker.getState(frag);
    if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
      var _track$details;
      if (!isMediaFragment(frag)) {
        this._loadInitSegment(frag, track);
      } else if ((_track$details = track.details) != null && _track$details.live && !this.initPTS[frag.cc]) {
        this.log(`Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`);
        this.state = State.WAITING_INIT_PTS;
        const mainDetails = this.mainDetails;
        if (mainDetails && mainDetails.fragmentStart !== track.details.fragmentStart) {
          alignMediaPlaylistByPDT(track.details, mainDetails);
        }
      } else {
        super.loadFragment(frag, track, targetBufferTime);
      }
    } else {
      this.clearTrackerIfNeeded(frag);
    }
  }
  flushAudioIfNeeded(switchingTrack) {
    if (this.media && this.bufferedTrack) {
      const {
        name,
        lang,
        assocLang,
        characteristics,
        audioCodec,
        channels
      } = this.bufferedTrack;
      if (!matchesOption({
        name,
        lang,
        assocLang,
        characteristics,
        audioCodec,
        channels
      }, switchingTrack, audioMatchPredicate)) {
        if (useAlternateAudio(switchingTrack.url, this.hls)) {
          this.log("Switching audio track : flushing all audio");
          super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
          this.bufferedTrack = null;
        } else {
          this.bufferedTrack = switchingTrack;
        }
      }
    }
  }
  completeAudioSwitch(switchingTrack) {
    const {
      hls
    } = this;
    this.flushAudioIfNeeded(switchingTrack);
    this.bufferedTrack = switchingTrack;
    this.switchingTrack = null;
    hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, switchingTrack));
  }
};
var BasePlaylistController = class extends Logger {
  constructor(hls, logPrefix) {
    super(logPrefix, hls.logger);
    this.hls = void 0;
    this.canLoad = false;
    this.timer = -1;
    this.hls = hls;
  }
  destroy() {
    this.clearTimer();
    this.hls = this.log = this.warn = null;
  }
  clearTimer() {
    if (this.timer !== -1) {
      self.clearTimeout(this.timer);
      this.timer = -1;
    }
  }
  startLoad() {
    this.canLoad = true;
    this.loadPlaylist();
  }
  stopLoad() {
    this.canLoad = false;
    this.clearTimer();
  }
  switchParams(playlistUri, previous, current) {
    const renditionReports = previous == null ? void 0 : previous.renditionReports;
    if (renditionReports) {
      let foundIndex = -1;
      for (let i = 0; i < renditionReports.length; i++) {
        const attr = renditionReports[i];
        let uri;
        try {
          uri = new self.URL(attr.URI, previous.url).href;
        } catch (error) {
          this.warn(`Could not construct new URL for Rendition Report: ${error}`);
          uri = attr.URI || "";
        }
        if (uri === playlistUri) {
          foundIndex = i;
          break;
        } else if (uri === playlistUri.substring(0, uri.length)) {
          foundIndex = i;
        }
      }
      if (foundIndex !== -1) {
        const attr = renditionReports[foundIndex];
        const msn = parseInt(attr["LAST-MSN"]) || (previous == null ? void 0 : previous.lastPartSn);
        let part = parseInt(attr["LAST-PART"]) || (previous == null ? void 0 : previous.lastPartIndex);
        if (this.hls.config.lowLatencyMode) {
          const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
          if (part >= 0 && currentGoal > previous.partTarget) {
            part += 1;
          }
        }
        const skip = current && getSkipValue(current);
        return new HlsUrlParameters(msn, part >= 0 ? part : void 0, skip);
      }
    }
  }
  loadPlaylist(hlsUrlParameters) {
    this.clearTimer();
  }
  loadingPlaylist(playlist, hlsUrlParameters) {
    this.clearTimer();
  }
  shouldLoadPlaylist(playlist) {
    return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  }
  getUrlWithDirectives(uri, hlsUrlParameters) {
    if (hlsUrlParameters) {
      try {
        return hlsUrlParameters.addDirectives(uri);
      } catch (error) {
        this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
      }
    }
    return uri;
  }
  playlistLoaded(index, data, previousDetails) {
    const {
      details,
      stats
    } = data;
    const now2 = self.performance.now();
    const elapsed = stats.loading.first ? Math.max(0, now2 - stats.loading.first) : 0;
    details.advancedDateTime = Date.now() - elapsed;
    const timelineOffset = this.hls.config.timelineOffset;
    if (timelineOffset !== details.appliedTimelineOffset) {
      const offset = Math.max(timelineOffset || 0, 0);
      details.appliedTimelineOffset = offset;
      details.fragments.forEach((frag) => {
        frag.start = frag.playlistOffset + offset;
      });
    }
    if (details.live || previousDetails != null && previousDetails.live) {
      const levelOrTrack = "levelInfo" in data ? data.levelInfo : data.track;
      details.reloaded(previousDetails);
      if (previousDetails && details.fragments.length > 0) {
        mergeDetails(previousDetails, details);
        const error = details.playlistParsingError;
        if (error) {
          this.warn(error);
          const hls = this.hls;
          if (!hls.config.ignorePlaylistParsingErrors) {
            var _details$fragments$;
            const {
              networkDetails
            } = data;
            hls.trigger(Events.ERROR, {
              type: ErrorTypes.NETWORK_ERROR,
              details: ErrorDetails.LEVEL_PARSING_ERROR,
              fatal: false,
              url: details.url,
              error,
              reason: error.message,
              level: data.level || void 0,
              parent: (_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.type,
              networkDetails,
              stats
            });
            return;
          }
          details.playlistParsingError = null;
        }
      }
      if (details.requestScheduled === -1) {
        details.requestScheduled = stats.loading.start;
      }
      const bufferInfo = this.hls.mainForwardBufferInfo;
      const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
      const distanceToLiveEdgeMs = (details.edge - position) * 1e3;
      const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
      if (details.requestScheduled + reloadInterval < now2) {
        details.requestScheduled = now2;
      } else {
        details.requestScheduled += reloadInterval;
      }
      this.log(`live playlist ${index} ${details.advanced ? "REFRESHED " + details.lastPartSn + "-" + details.lastPartIndex : details.updated ? "UPDATED" : "MISSED"}`);
      if (!this.canLoad || !details.live) {
        return;
      }
      let deliveryDirectives;
      let msn = void 0;
      let part = void 0;
      if (details.canBlockReload && details.endSN && details.advanced) {
        const lowLatencyMode = this.hls.config.lowLatencyMode;
        const lastPartSn = details.lastPartSn;
        const endSn = details.endSN;
        const lastPartIndex = details.lastPartIndex;
        const hasParts = lastPartIndex !== -1;
        const atLastPartOfSegment = lastPartSn === endSn;
        if (hasParts) {
          if (atLastPartOfSegment) {
            msn = endSn + 1;
            part = lowLatencyMode ? 0 : lastPartIndex;
          } else {
            msn = lastPartSn;
            part = lowLatencyMode ? lastPartIndex + 1 : details.maxPartIndex;
          }
        } else {
          msn = endSn + 1;
        }
        const lastAdvanced = details.age;
        const cdnAge = lastAdvanced + details.ageHeader;
        let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
        if (currentGoal > 0) {
          if (cdnAge > details.targetduration * 3) {
            this.log(`Playlist last advanced ${lastAdvanced.toFixed(2)}s ago. Omitting segment and part directives.`);
            msn = void 0;
            part = void 0;
          } else if (previousDetails != null && previousDetails.tuneInGoal && cdnAge - details.partTarget > previousDetails.tuneInGoal) {
            this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);
            currentGoal = 0;
          } else {
            const segments = Math.floor(currentGoal / details.targetduration);
            msn += segments;
            if (part !== void 0) {
              const parts = Math.round(currentGoal % details.targetduration / details.partTarget);
              part += parts;
            }
            this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);
          }
          details.tuneInGoal = currentGoal;
        }
        deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
        if (lowLatencyMode || !atLastPartOfSegment) {
          details.requestScheduled = now2;
          this.loadingPlaylist(levelOrTrack, deliveryDirectives);
          return;
        }
      } else if (details.canBlockReload || details.canSkipUntil) {
        deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
      }
      if (deliveryDirectives && msn !== void 0 && details.canBlockReload) {
        details.requestScheduled = stats.loading.first + Math.max(reloadInterval - elapsed * 2, reloadInterval / 2);
      }
      this.scheduleLoading(levelOrTrack, deliveryDirectives, details);
    } else {
      this.clearTimer();
    }
  }
  scheduleLoading(levelOrTrack, deliveryDirectives, updatedDetails) {
    const details = updatedDetails || levelOrTrack.details;
    if (!details) {
      this.loadingPlaylist(levelOrTrack, deliveryDirectives);
      return;
    }
    const now2 = self.performance.now();
    const requestScheduled = details.requestScheduled;
    if (now2 >= requestScheduled) {
      this.loadingPlaylist(levelOrTrack, deliveryDirectives);
      return;
    }
    const estimatedTimeUntilUpdate = requestScheduled - now2;
    this.log(`reload live playlist ${levelOrTrack.name || levelOrTrack.bitrate + "bps"} in ${Math.round(estimatedTimeUntilUpdate)} ms`);
    this.clearTimer();
    this.timer = self.setTimeout(() => this.loadingPlaylist(levelOrTrack, deliveryDirectives), estimatedTimeUntilUpdate);
  }
  getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
    let skip = getSkipValue(details);
    if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
      msn = previousDeliveryDirectives.msn;
      part = previousDeliveryDirectives.part;
      skip = HlsSkip.No;
    }
    return new HlsUrlParameters(msn, part, skip);
  }
  checkRetry(errorEvent) {
    const errorDetails = errorEvent.details;
    const isTimeout = isTimeoutError(errorEvent);
    const errorAction = errorEvent.errorAction;
    const {
      action,
      retryCount = 0,
      retryConfig
    } = errorAction || {};
    const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
    if (retry) {
      var _errorEvent$context;
      if (retryCount >= retryConfig.maxNumRetry) {
        return false;
      }
      if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
        this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`);
        this.loadPlaylist();
      } else {
        const delay = getRetryDelay(retryConfig, retryCount);
        this.clearTimer();
        this.timer = self.setTimeout(() => this.loadPlaylist(), delay);
        this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay}ms`);
      }
      errorEvent.levelRetry = true;
      errorAction.resolved = true;
    }
    return retry;
  }
};
function subtitleOptionsIdentical(trackList1, trackList2) {
  if (trackList1.length !== trackList2.length) {
    return false;
  }
  for (let i = 0; i < trackList1.length; i++) {
    if (!mediaAttributesIdentical(trackList1[i].attrs, trackList2[i].attrs)) {
      return false;
    }
  }
  return true;
}
function mediaAttributesIdentical(attrs1, attrs2, customAttributes) {
  const stableRenditionId = attrs1["STABLE-RENDITION-ID"];
  if (stableRenditionId && !customAttributes) {
    return stableRenditionId === attrs2["STABLE-RENDITION-ID"];
  }
  return !(customAttributes || ["LANGUAGE", "NAME", "CHARACTERISTICS", "AUTOSELECT", "DEFAULT", "FORCED", "ASSOC-LANGUAGE"]).some((subtitleAttribute) => attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]);
}
function subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) {
  return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || "").toLowerCase());
}
var AudioTrackController = class extends BasePlaylistController {
  constructor(hls) {
    super(hls, "audio-track-controller");
    this.tracks = [];
    this.groupIds = null;
    this.tracksInGroup = [];
    this.trackId = -1;
    this.currentTrack = null;
    this.selectDefaultTrack = true;
    this.registerListeners();
  }
  registerListeners() {
    const {
      hls
    } = this;
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
    hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
    hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
    hls.on(Events.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls
    } = this;
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
    hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
    hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
    hls.off(Events.ERROR, this.onError, this);
  }
  destroy() {
    this.unregisterListeners();
    this.tracks.length = 0;
    this.tracksInGroup.length = 0;
    this.currentTrack = null;
    super.destroy();
  }
  onManifestLoading() {
    this.tracks = [];
    this.tracksInGroup = [];
    this.groupIds = null;
    this.currentTrack = null;
    this.trackId = -1;
    this.selectDefaultTrack = true;
  }
  onManifestParsed(event, data) {
    this.tracks = data.audioTracks || [];
  }
  onAudioTrackLoaded(event, data) {
    const {
      id,
      groupId,
      details
    } = data;
    const trackInActiveGroup = this.tracksInGroup[id];
    if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
      this.warn(`Audio track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
      return;
    }
    const curDetails = trackInActiveGroup.details;
    trackInActiveGroup.details = data.details;
    this.log(`Audio track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
    if (id === this.trackId) {
      this.playlistLoaded(id, data, curDetails);
    }
  }
  onLevelLoading(event, data) {
    this.switchLevel(data.level);
  }
  onLevelSwitching(event, data) {
    this.switchLevel(data.level);
  }
  switchLevel(levelIndex) {
    const levelInfo = this.hls.levels[levelIndex];
    if (!levelInfo) {
      return;
    }
    const audioGroups = levelInfo.audioGroups || null;
    const currentGroups = this.groupIds;
    let currentTrack = this.currentTrack;
    if (!audioGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (audioGroups == null ? void 0 : audioGroups.length) || audioGroups != null && audioGroups.some((groupId) => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) {
      this.groupIds = audioGroups;
      this.trackId = -1;
      this.currentTrack = null;
      const audioTracks = this.tracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
      if (audioTracks.length) {
        if (this.selectDefaultTrack && !audioTracks.some((track) => track.default)) {
          this.selectDefaultTrack = false;
        }
        audioTracks.forEach((track, i) => {
          track.id = i;
        });
      } else if (!currentTrack && !this.tracksInGroup.length) {
        return;
      }
      this.tracksInGroup = audioTracks;
      const audioPreference = this.hls.config.audioPreference;
      if (!currentTrack && audioPreference) {
        const groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate);
        if (groupIndex > -1) {
          currentTrack = audioTracks[groupIndex];
        } else {
          const allIndex = findMatchingOption(audioPreference, this.tracks);
          currentTrack = this.tracks[allIndex];
        }
      }
      let trackId = this.findTrackId(currentTrack);
      if (trackId === -1 && currentTrack) {
        trackId = this.findTrackId(null);
      }
      const audioTracksUpdated = {
        audioTracks
      };
      this.log(`Updating audio tracks, ${audioTracks.length} track(s) found in group(s): ${audioGroups == null ? void 0 : audioGroups.join(",")}`);
      this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);
      const selectedTrackId = this.trackId;
      if (trackId !== -1 && selectedTrackId === -1) {
        this.setAudioTrack(trackId);
      } else if (audioTracks.length && selectedTrackId === -1) {
        var _this$groupIds;
        const error = new Error(`No audio track selected for current audio group-ID(s): ${(_this$groupIds = this.groupIds) == null ? void 0 : _this$groupIds.join(",")} track count: ${audioTracks.length}`);
        this.warn(error.message);
        this.hls.trigger(Events.ERROR, {
          type: ErrorTypes.MEDIA_ERROR,
          details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
          fatal: true,
          error
        });
      }
    }
  }
  onError(event, data) {
    if (data.fatal || !data.context) {
      return;
    }
    if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
      this.checkRetry(data);
    }
  }
  get allAudioTracks() {
    return this.tracks;
  }
  get audioTracks() {
    return this.tracksInGroup;
  }
  get audioTrack() {
    return this.trackId;
  }
  set audioTrack(newId) {
    this.selectDefaultTrack = false;
    this.setAudioTrack(newId);
  }
  setAudioOption(audioOption) {
    const hls = this.hls;
    hls.config.audioPreference = audioOption;
    if (audioOption) {
      const allAudioTracks = this.allAudioTracks;
      this.selectDefaultTrack = false;
      if (allAudioTracks.length) {
        const currentTrack = this.currentTrack;
        if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) {
          return currentTrack;
        }
        const groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate);
        if (groupIndex > -1) {
          const track = this.tracksInGroup[groupIndex];
          this.setAudioTrack(groupIndex);
          return track;
        } else if (currentTrack) {
          let searchIndex = hls.loadLevel;
          if (searchIndex === -1) {
            searchIndex = hls.firstAutoLevel;
          }
          const switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate);
          if (switchIndex === -1) {
            return null;
          }
          hls.nextLoadLevel = switchIndex;
        }
        if (audioOption.channels || audioOption.audioCodec) {
          const withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks);
          if (withoutCodecAndChannelsMatch > -1) {
            return allAudioTracks[withoutCodecAndChannelsMatch];
          }
        }
      }
    }
    return null;
  }
  setAudioTrack(newId) {
    const tracks = this.tracksInGroup;
    if (newId < 0 || newId >= tracks.length) {
      this.warn(`Invalid audio track id: ${newId}`);
      return;
    }
    this.selectDefaultTrack = false;
    const lastTrack = this.currentTrack;
    const track = tracks[newId];
    const trackLoaded = track.details && !track.details.live;
    if (newId === this.trackId && track === lastTrack && trackLoaded) {
      return;
    }
    this.log(`Switching to audio-track ${newId} "${track.name}" lang:${track.lang} group:${track.groupId} channels:${track.channels}`);
    this.trackId = newId;
    this.currentTrack = track;
    this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread2({}, track));
    if (trackLoaded) {
      return;
    }
    const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
    this.loadPlaylist(hlsUrlParameters);
  }
  findTrackId(currentTrack) {
    const audioTracks = this.tracksInGroup;
    for (let i = 0; i < audioTracks.length; i++) {
      const track = audioTracks[i];
      if (this.selectDefaultTrack && !track.default) {
        continue;
      }
      if (!currentTrack || matchesOption(currentTrack, track, audioMatchPredicate)) {
        return i;
      }
    }
    if (currentTrack) {
      const {
        name,
        lang,
        assocLang,
        characteristics,
        audioCodec,
        channels
      } = currentTrack;
      for (let i = 0; i < audioTracks.length; i++) {
        const track = audioTracks[i];
        if (matchesOption({
          name,
          lang,
          assocLang,
          characteristics,
          audioCodec,
          channels
        }, track, audioMatchPredicate)) {
          return i;
        }
      }
      for (let i = 0; i < audioTracks.length; i++) {
        const track = audioTracks[i];
        if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
          return i;
        }
      }
      for (let i = 0; i < audioTracks.length; i++) {
        const track = audioTracks[i];
        if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) {
          return i;
        }
      }
    }
    return -1;
  }
  loadPlaylist(hlsUrlParameters) {
    super.loadPlaylist();
    const audioTrack = this.currentTrack;
    if (!this.shouldLoadPlaylist(audioTrack)) {
      return;
    }
    if (useAlternateAudio(audioTrack.url, this.hls)) {
      this.scheduleLoading(audioTrack, hlsUrlParameters);
    }
  }
  loadingPlaylist(audioTrack, hlsUrlParameters) {
    super.loadingPlaylist(audioTrack, hlsUrlParameters);
    const id = audioTrack.id;
    const groupId = audioTrack.groupId;
    const url = this.getUrlWithDirectives(audioTrack.url, hlsUrlParameters);
    const details = audioTrack.details;
    const age = details == null ? void 0 : details.age;
    this.log(`Loading audio-track ${id} "${audioTrack.name}" lang:${audioTrack.lang} group:${groupId}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== void 0 ? " at sn " + hlsUrlParameters.msn + " part " + hlsUrlParameters.part : ""}${age && details.live ? " age " + age.toFixed(1) + (details.type ? " " + details.type || "" : "") : ""} ${url}`);
    this.hls.trigger(Events.AUDIO_TRACK_LOADING, {
      url,
      id,
      groupId,
      deliveryDirectives: hlsUrlParameters || null,
      track: audioTrack
    });
  }
};
var BufferOperationQueue = class {
  constructor(sourceBufferReference) {
    this.tracks = void 0;
    this.queues = {
      video: [],
      audio: [],
      audiovideo: []
    };
    this.tracks = sourceBufferReference;
  }
  destroy() {
    this.tracks = this.queues = null;
  }
  append(operation, type2, pending) {
    if (this.queues === null || this.tracks === null) {
      return;
    }
    const queue = this.queues[type2];
    queue.push(operation);
    if (queue.length === 1 && !pending) {
      this.executeNext(type2);
    }
  }
  appendBlocker(type2) {
    return new Promise((resolve) => {
      const operation = {
        label: "async-blocker",
        execute: resolve,
        onStart: () => {
        },
        onComplete: () => {
        },
        onError: () => {
        }
      };
      this.append(operation, type2);
    });
  }
  prependBlocker(type2) {
    return new Promise((resolve) => {
      if (this.queues) {
        const operation = {
          label: "async-blocker-prepend",
          execute: resolve,
          onStart: () => {
          },
          onComplete: () => {
          },
          onError: () => {
          }
        };
        this.queues[type2].unshift(operation);
      }
    });
  }
  removeBlockers() {
    if (this.queues === null) {
      return;
    }
    [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach((queue) => {
      var _queue$;
      const label = (_queue$ = queue[0]) == null ? void 0 : _queue$.label;
      if (label === "async-blocker" || label === "async-blocker-prepend") {
        queue[0].execute();
        queue.splice(0, 1);
      }
    });
  }
  unblockAudio(op) {
    if (this.queues === null) {
      return;
    }
    const queue = this.queues.audio;
    if (queue[0] === op) {
      this.shiftAndExecuteNext("audio");
    }
  }
  executeNext(type2) {
    if (this.queues === null || this.tracks === null) {
      return;
    }
    const queue = this.queues[type2];
    if (queue.length) {
      const operation = queue[0];
      try {
        operation.execute();
      } catch (error) {
        var _this$tracks$type;
        operation.onError(error);
        if (this.queues === null || this.tracks === null) {
          return;
        }
        const sb = (_this$tracks$type = this.tracks[type2]) == null ? void 0 : _this$tracks$type.buffer;
        if (!(sb != null && sb.updating)) {
          this.shiftAndExecuteNext(type2);
        }
      }
    }
  }
  shiftAndExecuteNext(type2) {
    if (this.queues === null) {
      return;
    }
    this.queues[type2].shift();
    this.executeNext(type2);
  }
  current(type2) {
    var _this$queues;
    return ((_this$queues = this.queues) == null ? void 0 : _this$queues[type2][0]) || null;
  }
  toString() {
    const {
      queues,
      tracks
    } = this;
    if (queues === null || tracks === null) {
      return `<destroyed>`;
    }
    return `
${this.list("video")}
${this.list("audio")}
${this.list("audiovideo")}}`;
  }
  list(type2) {
    var _this$queues2, _this$tracks;
    return (_this$queues2 = this.queues) != null && _this$queues2[type2] || (_this$tracks = this.tracks) != null && _this$tracks[type2] ? `${type2}: (${this.listSbInfo(type2)}) ${this.listOps(type2)}` : "";
  }
  listSbInfo(type2) {
    var _this$tracks2;
    const track = (_this$tracks2 = this.tracks) == null ? void 0 : _this$tracks2[type2];
    const sb = track == null ? void 0 : track.buffer;
    if (!sb) {
      return "none";
    }
    return `SourceBuffer${sb.updating ? " updating" : ""}${track.ended ? " ended" : ""}${track.ending ? " ending" : ""}`;
  }
  listOps(type2) {
    var _this$queues3;
    return ((_this$queues3 = this.queues) == null ? void 0 : _this$queues3[type2].map((op) => op.label).join(", ")) || "";
  }
};
var VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
var TRACK_REMOVED_ERROR_NAME = "HlsJsTrackRemovedError";
var HlsJsTrackRemovedError = class extends Error {
  constructor(message) {
    super(message);
    this.name = TRACK_REMOVED_ERROR_NAME;
  }
};
var BufferController = class extends Logger {
  constructor(hls, fragmentTracker) {
    super("buffer-controller", hls.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 = (event) => {
      var _this$mediaSource;
      if (!this.hls) {
        return;
      }
      if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) !== "open") {
        return;
      }
      this.hls.pauseBuffering();
    };
    this._onStartStreaming = (event) => {
      if (!this.hls) {
        return;
      }
      this.hls.resumeBuffering();
    };
    this._onMediaSourceOpen = (e) => {
      const {
        media,
        mediaSource
      } = this;
      if (e) {
        this.log("Media source opened");
      }
      if (!media || !mediaSource) {
        return;
      }
      mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
      media.removeEventListener("emptied", this._onMediaEmptied);
      this.updateDuration();
      this.hls.trigger(Events.MEDIA_ATTACHED, {
        media,
        mediaSource
      });
      if (this.mediaSource !== null) {
        this.checkPendingTracks();
      }
    };
    this._onMediaSourceClose = () => {
      this.log("Media source closed");
    };
    this._onMediaSourceEnded = () => {
      this.log("Media source ended");
    };
    this._onMediaEmptied = () => {
      const {
        mediaSrc,
        _objectUrl
      } = this;
      if (mediaSrc !== _objectUrl) {
        this.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);
      }
    };
    this.hls = hls;
    this.fragmentTracker = fragmentTracker;
    this.appendSource = isManagedMediaSource(getMediaSource(hls.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;
    if (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
    } = this;
    hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
    hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
    hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
    hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
    hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
    hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
    hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
    hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
    hls.on(Events.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls
    } = this;
    hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
    hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
    hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
    hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
    hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
    hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
    hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
    hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
    hls.off(Events.ERROR, this.onError, this);
  }
  transferMedia() {
    const {
      media,
      mediaSource
    } = this;
    if (!media) {
      return null;
    }
    const tracks = {};
    if (this.operationQueue) {
      const updating2 = this.isUpdating();
      if (!updating2) {
        this.operationQueue.removeBlockers();
      }
      const queued = this.isQueued();
      if (updating2 || queued) {
        this.warn(`Transfering MediaSource with${queued ? " operations in queue" : ""}${updating2 ? " updating SourceBuffer(s)" : ""} ${this.operationQueue}`);
      }
      this.operationQueue.destroy();
    }
    const transferData = this.transferData;
    if (!this.sourceBufferCount && transferData && transferData.mediaSource === mediaSource) {
      _extends(tracks, transferData.tracks);
    } else {
      this.sourceBuffers.forEach((tuple) => {
        const [type2] = tuple;
        if (type2) {
          tracks[type2] = _extends({}, this.tracks[type2]);
          this.removeBuffer(type2);
        }
        tuple[0] = tuple[1] = null;
      });
    }
    return {
      media,
      mediaSource,
      tracks
    };
  }
  initTracks() {
    const tracks = {};
    this.sourceBuffers = [[null, null], [null, null]];
    this.tracks = tracks;
    this.resetQueue();
    this.resetAppendErrors();
    this.lastMpegAudioChunk = this.blockedAudioAppend = null;
    this.lastVideoAppendEnd = 0;
  }
  onManifestLoading() {
    this.bufferCodecEventsTotal = 0;
    this.details = null;
  }
  onManifestParsed(event, data) {
    var _this$transferData;
    let codecEvents = 2;
    if (data.audio && !data.video || !data.altAudio) {
      codecEvents = 1;
    }
    this.bufferCodecEventsTotal = codecEvents;
    this.log(`${codecEvents} bufferCodec event(s) expected.`);
    if ((_this$transferData = this.transferData) != null && _this$transferData.mediaSource && this.sourceBufferCount && codecEvents) {
      this.bufferCreated();
    }
  }
  onMediaAttaching(event, data) {
    const media = this.media = data.media;
    const MediaSource2 = getMediaSource(this.appendSource);
    this.transferData = this.overrides = void 0;
    if (media && MediaSource2) {
      const transferringMedia = !!data.mediaSource;
      if (transferringMedia || data.overrides) {
        this.transferData = data;
        this.overrides = data.overrides;
      }
      const ms = this.mediaSource = data.mediaSource || new MediaSource2();
      this.assignMediaSource(ms);
      if (transferringMedia) {
        this._objectUrl = media.src;
        this.attachTransferred();
      } else {
        const objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
        if (this.appendSource) {
          try {
            media.removeAttribute("src");
            const MMS = self.ManagedMediaSource;
            media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
            removeSourceChildren(media);
            addSource(media, objectUrl);
            media.load();
          } catch (error) {
            media.src = objectUrl;
          }
        } else {
          media.src = objectUrl;
        }
      }
      media.addEventListener("emptied", this._onMediaEmptied);
    }
  }
  assignMediaSource(ms) {
    var _this$transferData2, _ms$constructor;
    this.log(`${((_this$transferData2 = this.transferData) == null ? void 0 : _this$transferData2.mediaSource) === ms ? "transferred" : "created"} media source: ${(_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name}`);
    ms.addEventListener("sourceopen", this._onMediaSourceOpen);
    ms.addEventListener("sourceended", this._onMediaSourceEnded);
    ms.addEventListener("sourceclose", this._onMediaSourceClose);
    if (this.appendSource) {
      ms.addEventListener("startstreaming", this._onStartStreaming);
      ms.addEventListener("endstreaming", this._onEndStreaming);
    }
  }
  attachTransferred() {
    const media = this.media;
    const data = this.transferData;
    if (!data || !media) {
      return;
    }
    const requiredTracks = this.tracks;
    const transferredTracks = data.tracks;
    const trackNames = transferredTracks ? Object.keys(transferredTracks) : null;
    const trackCount = trackNames ? trackNames.length : 0;
    const mediaSourceOpenCallback = () => {
      if (this.media && this.mediaSourceOpenOrEnded) {
        this._onMediaSourceOpen();
      }
    };
    if (transferredTracks && trackNames && trackCount) {
      if (!this.tracksReady) {
        this.hls.config.startFragPrefetch = true;
        this.log(`attachTransferred: waiting for SourceBuffer track info`);
        return;
      }
      this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
required tracks: ${stringify(requiredTracks, (key, value) => key === "initSegment" ? void 0 : value)};
transfer tracks: ${stringify(transferredTracks, (key, value) => key === "initSegment" ? void 0 : value)}}`);
      if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {
        data.mediaSource = null;
        data.tracks = void 0;
        const currentTime = media.currentTime;
        const details = this.details;
        const startTime = Math.max(currentTime, (details == null ? void 0 : details.fragments[0].start) || 0);
        if (startTime - currentTime > 1) {
          this.log(`attachTransferred: waiting for playback to reach new tracks start time ${currentTime} -> ${startTime}`);
          return;
        }
        this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(transferredTracks)}"->"${Object.keys(requiredTracks)}") start time: ${startTime} currentTime: ${currentTime}`);
        this.onMediaDetaching(Events.MEDIA_DETACHING, {});
        this.onMediaAttaching(Events.MEDIA_ATTACHING, data);
        media.currentTime = startTime;
        return;
      }
      this.transferData = void 0;
      trackNames.forEach((trackName) => {
        const type2 = trackName;
        const track = transferredTracks[type2];
        if (track) {
          const sb = track.buffer;
          if (sb) {
            const fragmentTracker = this.fragmentTracker;
            const playlistType = track.id;
            if (fragmentTracker.hasFragments(playlistType) || fragmentTracker.hasParts(playlistType)) {
              const bufferedTimeRanges = BufferHelper.getBuffered(sb);
              fragmentTracker.detectEvictedFragments(type2, bufferedTimeRanges, playlistType, null, true);
            }
            const sbIndex = sourceBufferNameToIndex(type2);
            const sbTuple = [type2, sb];
            this.sourceBuffers[sbIndex] = sbTuple;
            if (sb.updating && this.operationQueue) {
              this.operationQueue.prependBlocker(type2);
            }
            this.trackSourceBuffer(type2, track);
          }
        }
      });
      mediaSourceOpenCallback();
      this.bufferCreated();
    } else {
      this.log(`attachTransferred: MediaSource w/o SourceBuffers`);
      mediaSourceOpenCallback();
    }
  }
  get mediaSourceOpenOrEnded() {
    var _this$mediaSource2;
    const readyState = (_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState;
    return readyState === "open" || readyState === "ended";
  }
  onMediaDetaching(event, data) {
    const transferringMedia = !!data.transferMedia;
    this.transferData = this.overrides = void 0;
    const {
      media,
      mediaSource,
      _objectUrl
    } = this;
    if (mediaSource) {
      this.log(`media source ${transferringMedia ? "transferring" : "detaching"}`);
      if (transferringMedia) {
        this.sourceBuffers.forEach(([type2]) => {
          if (type2) {
            this.removeBuffer(type2);
          }
        });
        this.resetQueue();
      } else {
        if (this.mediaSourceOpenOrEnded) {
          const open = mediaSource.readyState === "open";
          try {
            const sourceBuffers = mediaSource.sourceBuffers;
            for (let i = sourceBuffers.length; i--; ) {
              if (open) {
                sourceBuffers[i].abort();
              }
              mediaSource.removeSourceBuffer(sourceBuffers[i]);
            }
            if (open) {
              mediaSource.endOfStream();
            }
          } catch (err) {
            this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);
          }
        }
        if (this.sourceBufferCount) {
          this.onBufferReset();
        }
      }
      mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
      mediaSource.removeEventListener("sourceended", this._onMediaSourceEnded);
      mediaSource.removeEventListener("sourceclose", this._onMediaSourceClose);
      if (this.appendSource) {
        mediaSource.removeEventListener("startstreaming", this._onStartStreaming);
        mediaSource.removeEventListener("endstreaming", this._onEndStreaming);
      }
      this.mediaSource = null;
      this._objectUrl = null;
    }
    if (media) {
      media.removeEventListener("emptied", this._onMediaEmptied);
      if (!transferringMedia) {
        if (_objectUrl) {
          self.URL.revokeObjectURL(_objectUrl);
        }
        if (this.mediaSrc === _objectUrl) {
          media.removeAttribute("src");
          if (this.appendSource) {
            removeSourceChildren(media);
          }
          media.load();
        } else {
          this.warn("media|source.src was changed by a third party - skip cleanup");
        }
      }
      this.media = null;
    }
    this.hls.trigger(Events.MEDIA_DETACHED, data);
  }
  onBufferReset() {
    this.sourceBuffers.forEach(([type2]) => {
      if (type2) {
        this.resetBuffer(type2);
      }
    });
    this.initTracks();
  }
  resetBuffer(type2) {
    var _this$tracks$type;
    const sb = (_this$tracks$type = this.tracks[type2]) == null ? void 0 : _this$tracks$type.buffer;
    this.removeBuffer(type2);
    if (sb) {
      try {
        var _this$mediaSource3;
        if ((_this$mediaSource3 = this.mediaSource) != null && _this$mediaSource3.sourceBuffers.length) {
          this.mediaSource.removeSourceBuffer(sb);
        }
      } catch (err) {
        this.warn(`onBufferReset ${type2}`, err);
      }
    }
    delete this.tracks[type2];
  }
  removeBuffer(type2) {
    this.removeBufferListeners(type2);
    this.sourceBuffers[sourceBufferNameToIndex(type2)] = [null, null];
    const track = this.tracks[type2];
    if (track) {
      track.buffer = void 0;
    }
  }
  resetQueue() {
    if (this.operationQueue) {
      this.operationQueue.destroy();
    }
    this.operationQueue = new BufferOperationQueue(this.tracks);
  }
  onBufferCodecs(event, data) {
    const tracks = this.tracks;
    const trackNames = Object.keys(data);
    this.log(`BUFFER_CODECS: "${trackNames}" (current SB count ${this.sourceBufferCount})`);
    const unmuxedToMuxed = "audiovideo" in data && (tracks.audio || tracks.video) || tracks.audiovideo && ("audio" in data || "video" in data);
    const muxedToUnmuxed = !unmuxedToMuxed && this.sourceBufferCount && this.media && trackNames.some((sbName) => !tracks[sbName]);
    if (unmuxedToMuxed || muxedToUnmuxed) {
      this.warn(`Unsupported transition between "${Object.keys(tracks)}" and "${trackNames}" SourceBuffers`);
      return;
    }
    trackNames.forEach((trackName) => {
      var _this$transferData3, _this$transferData3$t, _trackCodec;
      const parsedTrack = data[trackName];
      const {
        id,
        codec,
        levelCodec,
        container,
        metadata,
        supplemental
      } = parsedTrack;
      let track = tracks[trackName];
      const transferredTrack = (_this$transferData3 = this.transferData) == null ? void 0 : (_this$transferData3$t = _this$transferData3.tracks) == null ? void 0 : _this$transferData3$t[trackName];
      const sbTrack = transferredTrack != null && transferredTrack.buffer ? transferredTrack : track;
      const sbCodec = (sbTrack == null ? void 0 : sbTrack.pendingCodec) || (sbTrack == null ? void 0 : sbTrack.codec);
      const trackLevelCodec = sbTrack == null ? void 0 : sbTrack.levelCodec;
      if (!track) {
        track = tracks[trackName] = {
          buffer: void 0,
          listeners: [],
          codec,
          supplemental,
          container,
          levelCodec,
          metadata,
          id
        };
      }
      const currentCodecFull = pickMostCompleteCodecName(sbCodec, trackLevelCodec);
      const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
      let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
      const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
      if (trackCodec && currentCodecFull && currentCodec !== nextCodec) {
        if (trackName.slice(0, 5) === "audio") {
          trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
        }
        this.log(`switching codec ${sbCodec} to ${trackCodec}`);
        if (trackCodec !== (track.pendingCodec || track.codec)) {
          track.pendingCodec = trackCodec;
        }
        track.container = container;
        this.appendChangeType(trackName, container, trackCodec);
      }
    });
    if (this.tracksReady || this.sourceBufferCount) {
      data.tracks = this.sourceBufferTracks;
    }
    if (this.sourceBufferCount) {
      return;
    }
    if (this.mediaSourceOpenOrEnded) {
      this.checkPendingTracks();
    }
  }
  get sourceBufferTracks() {
    return Object.keys(this.tracks).reduce((baseTracks, type2) => {
      const track = this.tracks[type2];
      baseTracks[type2] = {
        id: track.id,
        container: track.container,
        codec: track.codec,
        levelCodec: track.levelCodec
      };
      return baseTracks;
    }, {});
  }
  appendChangeType(type2, container, codec) {
    const mimeType = `${container};codecs=${codec}`;
    const operation = {
      label: `change-type=${mimeType}`,
      execute: () => {
        const track = this.tracks[type2];
        if (track) {
          const sb = track.buffer;
          if (sb != null && sb.changeType) {
            this.log(`changing ${type2} sourceBuffer type to ${mimeType}`);
            sb.changeType(mimeType);
            track.codec = codec;
            track.container = container;
          }
        }
        this.shiftAndExecuteNext(type2);
      },
      onStart: () => {
      },
      onComplete: () => {
      },
      onError: (error) => {
        this.warn(`Failed to change ${type2} SourceBuffer type`, error);
      }
    };
    this.append(operation, type2, this.isPending(this.tracks[type2]));
  }
  blockAudio(partOrFrag) {
    var _this$fragmentTracker;
    const pStart = partOrFrag.start;
    const pTime = pStart + partOrFrag.duration * 0.05;
    const atGap = ((_this$fragmentTracker = this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker.gap) === true;
    if (atGap) {
      return;
    }
    const op = {
      label: "block-audio",
      execute: () => {
        var _this$fragmentTracker2;
        const videoTrack = this.tracks.video;
        if (this.lastVideoAppendEnd > pTime || videoTrack != null && videoTrack.buffer && BufferHelper.isBuffered(videoTrack.buffer, pTime) || ((_this$fragmentTracker2 = this.fragmentTracker.getAppendedFrag(pTime, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker2.gap) === true) {
          this.blockedAudioAppend = null;
          this.shiftAndExecuteNext("audio");
        }
      },
      onStart: () => {
      },
      onComplete: () => {
      },
      onError: (error) => {
        this.warn("Error executing block-audio operation", error);
      }
    };
    this.blockedAudioAppend = {
      op,
      frag: partOrFrag
    };
    this.append(op, "audio", true);
  }
  unblockAudio() {
    const {
      blockedAudioAppend,
      operationQueue
    } = this;
    if (blockedAudioAppend && operationQueue) {
      this.blockedAudioAppend = null;
      operationQueue.unblockAudio(blockedAudioAppend.op);
    }
  }
  onBufferAppending(event, eventData) {
    const {
      tracks
    } = this;
    const {
      data,
      type: type2,
      parent,
      frag,
      part,
      chunkMeta
    } = eventData;
    const chunkStats = chunkMeta.buffering[type2];
    const sn = frag.sn;
    const bufferAppendingStart = self.performance.now();
    chunkStats.start = bufferAppendingStart;
    const fragBuffering = frag.stats.buffering;
    const partBuffering = part ? part.stats.buffering : null;
    if (fragBuffering.start === 0) {
      fragBuffering.start = bufferAppendingStart;
    }
    if (partBuffering && partBuffering.start === 0) {
      partBuffering.start = bufferAppendingStart;
    }
    const audioTrack = tracks.audio;
    let checkTimestampOffset = false;
    if (type2 === "audio" && (audioTrack == null ? void 0 : audioTrack.container) === "audio/mpeg") {
      checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
      this.lastMpegAudioChunk = chunkMeta;
    }
    const videoTrack = this.tracks.video;
    const videoSb = videoTrack == null ? void 0 : videoTrack.buffer;
    if (videoSb && sn !== "initSegment") {
      const partOrFrag = part || frag;
      const blockedAudioAppend = this.blockedAudioAppend;
      if (type2 === "audio" && parent !== "main" && !this.blockedAudioAppend) {
        const pStart = partOrFrag.start;
        const pTime = pStart + partOrFrag.duration * 0.05;
        const vbuffered = videoSb.buffered;
        const vappending = this.currentOp("video");
        if (!vbuffered.length && !vappending) {
          this.blockAudio(partOrFrag);
        } else if (!vappending && !BufferHelper.isBuffered(videoSb, pTime) && this.lastVideoAppendEnd < pTime) {
          this.blockAudio(partOrFrag);
        }
      } else if (type2 === "video") {
        const videoAppendEnd = partOrFrag.end;
        if (blockedAudioAppend) {
          const audioStart = blockedAudioAppend.frag.start;
          if (videoAppendEnd > audioStart || videoAppendEnd < this.lastVideoAppendEnd || BufferHelper.isBuffered(videoSb, audioStart)) {
            this.unblockAudio();
          }
        }
        this.lastVideoAppendEnd = videoAppendEnd;
      }
    }
    const fragStart = (part || frag).start;
    const operation = {
      label: `append-${type2}`,
      execute: () => {
        chunkStats.executeStart = self.performance.now();
        if (checkTimestampOffset) {
          const track = this.tracks[type2];
          if (track) {
            const sb = track.buffer;
            if (sb) {
              const delta = fragStart - sb.timestampOffset;
              if (Math.abs(delta) >= 0.1) {
                this.log(`Updating audio SourceBuffer timestampOffset to ${fragStart} (delta: ${delta}) sn: ${sn})`);
                sb.timestampOffset = fragStart;
              }
            }
          }
        }
        this.appendExecutor(data, type2);
      },
      onStart: () => {
      },
      onComplete: () => {
        const end = self.performance.now();
        chunkStats.executeEnd = chunkStats.end = end;
        if (fragBuffering.first === 0) {
          fragBuffering.first = end;
        }
        if (partBuffering && partBuffering.first === 0) {
          partBuffering.first = end;
        }
        const timeRanges = {};
        this.sourceBuffers.forEach(([type3, sb]) => {
          if (type3) {
            timeRanges[type3] = BufferHelper.getBuffered(sb);
          }
        });
        this.appendErrors[type2] = 0;
        if (type2 === "audio" || type2 === "video") {
          this.appendErrors.audiovideo = 0;
        } else {
          this.appendErrors.audio = 0;
          this.appendErrors.video = 0;
        }
        this.hls.trigger(Events.BUFFER_APPENDED, {
          type: type2,
          frag,
          part,
          chunkMeta,
          parent: frag.type,
          timeRanges
        });
      },
      onError: (error) => {
        var _this$media;
        const event2 = {
          type: ErrorTypes.MEDIA_ERROR,
          parent: frag.type,
          details: ErrorDetails.BUFFER_APPEND_ERROR,
          sourceBufferName: type2,
          frag,
          part,
          chunkMeta,
          error,
          err: error,
          fatal: false
        };
        const mediaError = (_this$media = this.media) == null ? void 0 : _this$media.error;
        if (error.code === DOMException.QUOTA_EXCEEDED_ERR) {
          event2.details = ErrorDetails.BUFFER_FULL_ERROR;
        } else if (error.code === DOMException.INVALID_STATE_ERR && this.mediaSourceOpenOrEnded && !mediaError) {
          event2.errorAction = createDoNothingErrorAction(true);
        } else if (error.name === TRACK_REMOVED_ERROR_NAME && this.sourceBufferCount === 0) {
          event2.errorAction = createDoNothingErrorAction(true);
        } else {
          const appendErrorCount = ++this.appendErrors[type2];
          this.warn(`Failed ${appendErrorCount}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${type2}" sourceBuffer (${mediaError ? mediaError : "no media error"})`);
          if (appendErrorCount >= this.hls.config.appendErrorMaxRetry || !!mediaError) {
            event2.fatal = true;
          }
        }
        this.hls.trigger(Events.ERROR, event2);
      }
    };
    this.append(operation, type2, this.isPending(this.tracks[type2]));
  }
  getFlushOp(type2, start2, end) {
    this.log(`queuing "${type2}" remove ${start2}-${end}`);
    return {
      label: "remove",
      execute: () => {
        this.removeExecutor(type2, start2, end);
      },
      onStart: () => {
      },
      onComplete: () => {
        this.hls.trigger(Events.BUFFER_FLUSHED, {
          type: type2
        });
      },
      onError: (error) => {
        this.warn(`Failed to remove ${start2}-${end} from "${type2}" SourceBuffer`, error);
      }
    };
  }
  onBufferFlushing(event, data) {
    const {
      type: type2,
      startOffset,
      endOffset
    } = data;
    if (type2) {
      this.append(this.getFlushOp(type2, startOffset, endOffset), type2);
    } else {
      this.sourceBuffers.forEach(([type3]) => {
        if (type3) {
          this.append(this.getFlushOp(type3, startOffset, endOffset), type3);
        }
      });
    }
  }
  onFragParsed(event, data) {
    const {
      frag,
      part
    } = data;
    const buffersAppendedTo = [];
    const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
    if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
      buffersAppendedTo.push("audiovideo");
    } else {
      if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
        buffersAppendedTo.push("audio");
      }
      if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
        buffersAppendedTo.push("video");
      }
    }
    const onUnblocked = () => {
      const now2 = self.performance.now();
      frag.stats.buffering.end = now2;
      if (part) {
        part.stats.buffering.end = now2;
      }
      const stats = part ? part.stats : frag.stats;
      this.hls.trigger(Events.FRAG_BUFFERED, {
        frag,
        part,
        stats,
        id: frag.type
      });
    };
    if (buffersAppendedTo.length === 0) {
      this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);
    }
    this.blockBuffers(onUnblocked, buffersAppendedTo).catch((error) => {
      this.warn(`Fragment buffered callback ${error}`);
      this.stepOperationQueue(this.sourceBufferTypes);
    });
  }
  onFragChanged(event, data) {
    this.trimBuffers();
  }
  get bufferedToEnd() {
    return this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type2]) => {
      var _this$tracks$type2, _this$tracks$type3;
      return type2 && (!((_this$tracks$type2 = this.tracks[type2]) != null && _this$tracks$type2.ended) || ((_this$tracks$type3 = this.tracks[type2]) == null ? void 0 : _this$tracks$type3.ending));
    });
  }
  // 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(event, data) {
    var _this$overrides;
    this.sourceBuffers.forEach(([type2]) => {
      if (type2) {
        const track = this.tracks[type2];
        if (!data.type || data.type === type2) {
          track.ending = true;
          if (!track.ended) {
            track.ended = true;
            this.log(`${type2} buffer reached EOS`);
          }
        }
      }
    });
    const allowEndOfStream = ((_this$overrides = this.overrides) == null ? void 0 : _this$overrides.endOfStream) !== false;
    const allTracksEnding = this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type2]) => {
      var _this$tracks$type4;
      return type2 && !((_this$tracks$type4 = this.tracks[type2]) != null && _this$tracks$type4.ended);
    });
    if (allTracksEnding) {
      if (allowEndOfStream) {
        this.log(`Queueing EOS`);
        this.blockUntilOpen(() => {
          this.tracksEnded();
          const {
            mediaSource
          } = this;
          if (!mediaSource || mediaSource.readyState !== "open") {
            if (mediaSource) {
              this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);
            }
            return;
          }
          this.log(`Calling mediaSource.endOfStream()`);
          mediaSource.endOfStream();
          this.hls.trigger(Events.BUFFERED_TO_END, void 0);
        });
      } else {
        this.tracksEnded();
        this.hls.trigger(Events.BUFFERED_TO_END, void 0);
      }
    }
  }
  tracksEnded() {
    this.sourceBuffers.forEach(([type2]) => {
      if (type2 !== null) {
        const track = this.tracks[type2];
        if (track) {
          track.ending = false;
        }
      }
    });
  }
  onLevelUpdated(event, {
    details
  }) {
    if (!details.fragments.length) {
      return;
    }
    this.details = details;
    this.updateDuration();
  }
  updateDuration() {
    const durationAndRange = this.getDurationAndRange();
    if (!durationAndRange) {
      return;
    }
    this.blockUntilOpen(() => this.updateMediaSource(durationAndRange));
  }
  onError(event, data) {
    if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && data.frag) {
      var _data$errorAction;
      const nextAutoLevel = (_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.nextAutoLevel;
      if (isFiniteNumber(nextAutoLevel) && nextAutoLevel !== data.frag.level) {
        this.resetAppendErrors();
      }
    }
  }
  resetAppendErrors() {
    this.appendErrors = {
      audio: 0,
      video: 0,
      audiovideo: 0
    };
  }
  trimBuffers() {
    const {
      hls,
      details,
      media
    } = this;
    if (!media || details === null) {
      return;
    }
    if (!this.sourceBufferCount) {
      return;
    }
    const config = hls.config;
    const currentTime = media.currentTime;
    const targetDuration = details.levelTargetDuration;
    const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
    if (isFiniteNumber(backBufferLength) && backBufferLength >= 0) {
      const maxBackBufferLength = Math.max(backBufferLength, targetDuration);
      const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
      this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
    }
    if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
      const frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
      const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
      const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
      this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
    }
  }
  flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
    this.sourceBuffers.forEach(([type2, sb]) => {
      if (sb) {
        const buffered = BufferHelper.getBuffered(sb);
        if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
          var _this$details;
          this.hls.trigger(Events.BACK_BUFFER_REACHED, {
            bufferEnd: targetBackBufferPosition
          });
          const track = this.tracks[type2];
          if ((_this$details = this.details) != null && _this$details.live) {
            this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
              bufferEnd: targetBackBufferPosition
            });
          } else if (track != null && track.ended) {
            this.log(`Cannot flush ${type2} back buffer while SourceBuffer is in ended state`);
            return;
          }
          this.hls.trigger(Events.BUFFER_FLUSHING, {
            startOffset: 0,
            endOffset: targetBackBufferPosition,
            type: type2
          });
        }
      }
    });
  }
  flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
    this.sourceBuffers.forEach(([type2, sb]) => {
      if (sb) {
        const buffered = BufferHelper.getBuffered(sb);
        const numBufferedRanges = buffered.length;
        if (numBufferedRanges < 2) {
          return;
        }
        const bufferStart = buffered.start(numBufferedRanges - 1);
        const bufferEnd = buffered.end(numBufferedRanges - 1);
        if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
          return;
        }
        this.hls.trigger(Events.BUFFER_FLUSHING, {
          startOffset: bufferStart,
          endOffset: Infinity,
          type: type2
        });
      }
    });
  }
  /**
   * 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 _this$overrides2;
    const {
      details,
      mediaSource
    } = this;
    if (!details || !this.media || (mediaSource == null ? void 0 : mediaSource.readyState) !== "open") {
      return null;
    }
    const playlistEnd3 = details.edge;
    if (details.live && this.hls.config.liveDurationInfinity) {
      const len = details.fragments.length;
      if (len && details.live && !!mediaSource.setLiveSeekableRange) {
        const start2 = Math.max(0, details.fragmentStart);
        const end = Math.max(start2, playlistEnd3);
        return {
          duration: Infinity,
          start: start2,
          end
        };
      }
      return {
        duration: Infinity
      };
    }
    const overrideDuration = (_this$overrides2 = this.overrides) == null ? void 0 : _this$overrides2.duration;
    if (overrideDuration) {
      if (!isFiniteNumber(overrideDuration)) {
        return null;
      }
      return {
        duration: overrideDuration
      };
    }
    const mediaDuration3 = this.media.duration;
    const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
    if (playlistEnd3 > msDuration && playlistEnd3 > mediaDuration3 || !isFiniteNumber(mediaDuration3)) {
      return {
        duration: playlistEnd3
      };
    }
    return null;
  }
  updateMediaSource({
    duration: duration5,
    start: start2,
    end
  }) {
    const mediaSource = this.mediaSource;
    if (!this.media || !mediaSource || mediaSource.readyState !== "open") {
      return;
    }
    if (mediaSource.duration !== duration5) {
      if (isFiniteNumber(duration5)) {
        this.log(`Updating MediaSource duration to ${duration5.toFixed(3)}`);
      }
      mediaSource.duration = duration5;
    }
    if (start2 !== void 0 && end !== void 0) {
      this.log(`MediaSource duration is set to ${mediaSource.duration}. Setting seekable range to ${start2}-${end}.`);
      mediaSource.setLiveSeekableRange(start2, end);
    }
  }
  get tracksReady() {
    const pendingTrackCount = this.pendingTrackCount;
    return pendingTrackCount > 0 && (pendingTrackCount >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  }
  checkPendingTracks() {
    const {
      bufferCodecEventsTotal,
      pendingTrackCount,
      tracks
    } = this;
    this.log(`checkPendingTracks (pending: ${pendingTrackCount} codec events expected: ${bufferCodecEventsTotal}) ${stringify(tracks)}`);
    if (this.tracksReady) {
      var _this$transferData4;
      const transferredTracks = (_this$transferData4 = this.transferData) == null ? void 0 : _this$transferData4.tracks;
      if (transferredTracks && Object.keys(transferredTracks).length) {
        this.attachTransferred();
      } else {
        this.createSourceBuffers();
      }
    }
  }
  bufferCreated() {
    if (this.sourceBufferCount) {
      const tracks = {};
      this.sourceBuffers.forEach(([type2, buffer]) => {
        if (type2) {
          const track = this.tracks[type2];
          tracks[type2] = {
            buffer,
            container: track.container,
            codec: track.codec,
            supplemental: track.supplemental,
            levelCodec: track.levelCodec,
            id: track.id,
            metadata: track.metadata
          };
        }
      });
      this.hls.trigger(Events.BUFFER_CREATED, {
        tracks
      });
      this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`);
      this.sourceBuffers.forEach(([type2]) => {
        this.executeNext(type2);
      });
    } else {
      const error = new Error("could not create source buffer for media codec(s)");
      this.hls.trigger(Events.ERROR, {
        type: ErrorTypes.MEDIA_ERROR,
        details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
        fatal: true,
        error,
        reason: error.message
      });
    }
  }
  createSourceBuffers() {
    const {
      tracks,
      sourceBuffers,
      mediaSource
    } = this;
    if (!mediaSource) {
      throw new Error("createSourceBuffers called when mediaSource was null");
    }
    for (const trackName in tracks) {
      const type2 = trackName;
      const track = tracks[type2];
      if (this.isPending(track)) {
        const codec = this.getTrackCodec(track, type2);
        const mimeType = `${track.container};codecs=${codec}`;
        track.codec = codec;
        this.log(`creating sourceBuffer(${mimeType})${this.currentOp(type2) ? " Queued" : ""} ${stringify(track)}`);
        try {
          const sb = mediaSource.addSourceBuffer(mimeType);
          const sbIndex = sourceBufferNameToIndex(type2);
          const sbTuple = [type2, sb];
          sourceBuffers[sbIndex] = sbTuple;
          track.buffer = sb;
        } catch (error) {
          var _this$operationQueue;
          this.error(`error while trying to add sourceBuffer: ${error.message}`);
          this.shiftAndExecuteNext(type2);
          (_this$operationQueue = this.operationQueue) == null ? void 0 : _this$operationQueue.removeBlockers();
          delete this.tracks[type2];
          this.hls.trigger(Events.ERROR, {
            type: ErrorTypes.MEDIA_ERROR,
            details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
            fatal: false,
            error,
            sourceBufferName: type2,
            mimeType,
            parent: track.id
          });
          return;
        }
        this.trackSourceBuffer(type2, track);
      }
    }
    this.bufferCreated();
  }
  getTrackCodec(track, trackName) {
    const supplementalCodec = track.supplemental;
    let trackCodec = track.codec;
    if (supplementalCodec && (trackName === "video" || trackName === "audiovideo") && areCodecsMediaSourceSupported(supplementalCodec, "video")) {
      trackCodec = replaceVideoCodec(trackCodec, supplementalCodec);
    }
    const codec = pickMostCompleteCodecName(trackCodec, track.levelCodec);
    if (codec) {
      if (trackName.slice(0, 5) === "audio") {
        return getCodecCompatibleName(codec, this.appendSource);
      }
      return codec;
    }
    return "";
  }
  trackSourceBuffer(type2, track) {
    const buffer = track.buffer;
    if (!buffer) {
      return;
    }
    const codec = this.getTrackCodec(track, type2);
    this.tracks[type2] = {
      buffer,
      codec,
      container: track.container,
      levelCodec: track.levelCodec,
      supplemental: track.supplemental,
      metadata: track.metadata,
      id: track.id,
      listeners: []
    };
    this.removeBufferListeners(type2);
    this.addBufferListener(type2, "updatestart", this.onSBUpdateStart);
    this.addBufferListener(type2, "updateend", this.onSBUpdateEnd);
    this.addBufferListener(type2, "error", this.onSBUpdateError);
    if (this.appendSource) {
      this.addBufferListener(type2, "bufferedchange", (type3, event) => {
        const removedRanges = event.removedRanges;
        if (removedRanges != null && removedRanges.length) {
          this.hls.trigger(Events.BUFFER_FLUSHED, {
            type: type3
          });
        }
      });
    }
  }
  get mediaSrc() {
    var _this$media2, _this$media2$querySel;
    const media = ((_this$media2 = this.media) == null ? void 0 : (_this$media2$querySel = _this$media2.querySelector) == null ? void 0 : _this$media2$querySel.call(_this$media2, "source")) || this.media;
    return media == null ? void 0 : media.src;
  }
  onSBUpdateStart(type2) {
    const operation = this.currentOp(type2);
    if (!operation) {
      return;
    }
    operation.onStart();
  }
  onSBUpdateEnd(type2) {
    var _this$mediaSource4;
    if (((_this$mediaSource4 = this.mediaSource) == null ? void 0 : _this$mediaSource4.readyState) === "closed") {
      this.resetBuffer(type2);
      return;
    }
    const operation = this.currentOp(type2);
    if (!operation) {
      return;
    }
    operation.onComplete();
    this.shiftAndExecuteNext(type2);
  }
  onSBUpdateError(type2, event) {
    var _this$mediaSource5;
    const error = new Error(`${type2} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource5 = this.mediaSource) == null ? void 0 : _this$mediaSource5.readyState}`);
    this.error(`${error}`, event);
    this.hls.trigger(Events.ERROR, {
      type: ErrorTypes.MEDIA_ERROR,
      details: ErrorDetails.BUFFER_APPENDING_ERROR,
      sourceBufferName: type2,
      error,
      fatal: false
    });
    const operation = this.currentOp(type2);
    if (operation) {
      operation.onError(error);
    }
  }
  // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually
  removeExecutor(type2, startOffset, endOffset) {
    const {
      media,
      mediaSource
    } = this;
    const track = this.tracks[type2];
    const sb = track == null ? void 0 : track.buffer;
    if (!media || !mediaSource || !sb) {
      this.warn(`Attempting to remove from the ${type2} SourceBuffer, but it does not exist`);
      this.shiftAndExecuteNext(type2);
      return;
    }
    const mediaDuration3 = isFiniteNumber(media.duration) ? media.duration : Infinity;
    const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
    const removeStart = Math.max(0, startOffset);
    const removeEnd = Math.min(endOffset, mediaDuration3, msDuration);
    if (removeEnd > removeStart && (!track.ending || track.ended)) {
      track.ended = false;
      this.log(`Removing [${removeStart},${removeEnd}] from the ${type2} SourceBuffer`);
      sb.remove(removeStart, removeEnd);
    } else {
      this.shiftAndExecuteNext(type2);
    }
  }
  // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually
  appendExecutor(data, type2) {
    const track = this.tracks[type2];
    const sb = track == null ? void 0 : track.buffer;
    if (!sb) {
      throw new HlsJsTrackRemovedError(`Attempting to append to the ${type2} SourceBuffer, but it does not exist`);
    }
    track.ending = false;
    track.ended = false;
    sb.appendBuffer(data);
  }
  blockUntilOpen(callback2) {
    if (this.isUpdating() || this.isQueued()) {
      this.blockBuffers(callback2).catch((error) => {
        this.warn(`SourceBuffer blocked callback ${error}`);
        this.stepOperationQueue(this.sourceBufferTypes);
      });
    } else {
      try {
        callback2();
      } catch (error) {
        this.warn(`Callback run without blocking ${this.operationQueue} ${error}`);
      }
    }
  }
  isUpdating() {
    return this.sourceBuffers.some(([type2, sb]) => type2 && sb.updating);
  }
  isQueued() {
    return this.sourceBuffers.some(([type2]) => type2 && !!this.currentOp(type2));
  }
  isPending(track) {
    return !!track && !track.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(onUnblocked, bufferNames = this.sourceBufferTypes) {
    if (!bufferNames.length) {
      this.log("Blocking operation requested, but no SourceBuffers exist");
      return Promise.resolve().then(onUnblocked);
    }
    const {
      operationQueue
    } = this;
    const blockingOperations = bufferNames.map((type2) => this.appendBlocker(type2));
    const audioBlocked = bufferNames.length > 1 && !!this.blockedAudioAppend;
    if (audioBlocked) {
      this.unblockAudio();
    }
    return Promise.all(blockingOperations).then((result) => {
      if (operationQueue !== this.operationQueue) {
        return;
      }
      onUnblocked();
      this.stepOperationQueue(this.sourceBufferTypes);
    });
  }
  stepOperationQueue(bufferNames) {
    bufferNames.forEach((type2) => {
      var _this$tracks$type5;
      const sb = (_this$tracks$type5 = this.tracks[type2]) == null ? void 0 : _this$tracks$type5.buffer;
      if (!sb || sb.updating) {
        return;
      }
      this.shiftAndExecuteNext(type2);
    });
  }
  append(operation, type2, pending) {
    if (this.operationQueue) {
      this.operationQueue.append(operation, type2, pending);
    }
  }
  appendBlocker(type2) {
    if (this.operationQueue) {
      return this.operationQueue.appendBlocker(type2);
    }
  }
  currentOp(type2) {
    if (this.operationQueue) {
      return this.operationQueue.current(type2);
    }
    return null;
  }
  executeNext(type2) {
    if (type2 && this.operationQueue) {
      this.operationQueue.executeNext(type2);
    }
  }
  shiftAndExecuteNext(type2) {
    if (this.operationQueue) {
      this.operationQueue.shiftAndExecuteNext(type2);
    }
  }
  get pendingTrackCount() {
    return Object.keys(this.tracks).reduce((acc, type2) => acc + (this.isPending(this.tracks[type2]) ? 1 : 0), 0);
  }
  get sourceBufferCount() {
    return this.sourceBuffers.reduce((acc, [type2]) => acc + (type2 ? 1 : 0), 0);
  }
  get sourceBufferTypes() {
    return this.sourceBuffers.map(([type2]) => type2).filter((type2) => !!type2);
  }
  addBufferListener(type2, event, fn) {
    const track = this.tracks[type2];
    if (!track) {
      return;
    }
    const buffer = track.buffer;
    if (!buffer) {
      return;
    }
    const listener = fn.bind(this, type2);
    track.listeners.push({
      event,
      listener
    });
    buffer.addEventListener(event, listener);
  }
  removeBufferListeners(type2) {
    const track = this.tracks[type2];
    if (!track) {
      return;
    }
    const buffer = track.buffer;
    if (!buffer) {
      return;
    }
    track.listeners.forEach((l) => {
      buffer.removeEventListener(l.event, l.listener);
    });
    track.listeners.length = 0;
  }
};
function removeSourceChildren(node) {
  const sourceChildren = node.querySelectorAll("source");
  [].slice.call(sourceChildren).forEach((source) => {
    node.removeChild(source);
  });
}
function addSource(media, url) {
  const source = self.document.createElement("source");
  source.type = "video/mp4";
  source.src = url;
  media.appendChild(source);
}
function sourceBufferNameToIndex(type2) {
  return type2 === "audio" ? 1 : 0;
}
var CapLevelController = class _CapLevelController {
  constructor(hls) {
    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 = hls;
    this.autoLevelCapping = Number.POSITIVE_INFINITY;
    this.firstLevel = -1;
    this.media = null;
    this.restrictedLevels = [];
    this.timer = void 0;
    this.clientRect = null;
    this.registerListeners();
  }
  setStreamController(streamController) {
    this.streamController = streamController;
  }
  destroy() {
    if (this.hls) {
      this.unregisterListener();
    }
    if (this.timer) {
      this.stopCapping();
    }
    this.media = null;
    this.clientRect = null;
    this.hls = this.streamController = null;
  }
  registerListeners() {
    const {
      hls
    } = this;
    hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
    hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
    hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
    hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  unregisterListener() {
    const {
      hls
    } = this;
    hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
    hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
    hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
    hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  onFpsDropLevelCapping(event, data) {
    const level = this.hls.levels[data.droppedLevel];
    if (this.isLevelAllowed(level)) {
      this.restrictedLevels.push({
        bitrate: level.bitrate,
        height: level.height,
        width: level.width
      });
    }
  }
  onMediaAttaching(event, data) {
    this.media = data.media instanceof HTMLVideoElement ? data.media : null;
    this.clientRect = null;
    if (this.timer && this.hls.levels.length) {
      this.detectPlayerSize();
    }
  }
  onManifestParsed(event, data) {
    const hls = this.hls;
    this.restrictedLevels = [];
    this.firstLevel = data.firstLevel;
    if (hls.config.capLevelToPlayerSize && data.video) {
      this.startCapping();
    }
  }
  onLevelsUpdated(event, data) {
    if (this.timer && isFiniteNumber(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(event, data) {
    const hls = this.hls;
    if (hls.config.capLevelToPlayerSize && data.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 levels = this.hls.levels;
      if (levels.length) {
        const hls = this.hls;
        const maxLevel = this.getMaxLevel(levels.length - 1);
        if (maxLevel !== this.autoLevelCapping) {
          hls.logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);
        }
        hls.autoLevelCapping = maxLevel;
        if (hls.autoLevelEnabled && hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
          this.streamController.nextLevelSwitch();
        }
        this.autoLevelCapping = hls.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(capLevelIndex) {
    const levels = this.hls.levels;
    if (!levels.length) {
      return -1;
    }
    const validLevels = levels.filter((level, index) => this.isLevelAllowed(level) && index <= capLevelIndex);
    this.clientRect = null;
    return _CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  }
  startCapping() {
    if (this.timer) {
      return;
    }
    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;
    if (this.timer) {
      self.clearInterval(this.timer);
      this.timer = void 0;
    }
  }
  getDimensions() {
    if (this.clientRect) {
      return this.clientRect;
    }
    const media = this.media;
    const boundsRect = {
      width: 0,
      height: 0
    };
    if (media) {
      const clientRect = media.getBoundingClientRect();
      boundsRect.width = clientRect.width;
      boundsRect.height = clientRect.height;
      if (!boundsRect.width && !boundsRect.height) {
        boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
        boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
      }
    }
    this.clientRect = boundsRect;
    return boundsRect;
  }
  get mediaWidth() {
    return this.getDimensions().width * this.contentScaleFactor;
  }
  get mediaHeight() {
    return this.getDimensions().height * this.contentScaleFactor;
  }
  get contentScaleFactor() {
    let pixelRatio = 1;
    if (!this.hls.config.ignoreDevicePixelRatio) {
      try {
        pixelRatio = self.devicePixelRatio;
      } catch (e) {
      }
    }
    return Math.min(pixelRatio, this.hls.config.maxDevicePixelRatio);
  }
  isLevelAllowed(level) {
    const restrictedLevels = this.restrictedLevels;
    return !restrictedLevels.some((restrictedLevel) => {
      return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
    });
  }
  static getMaxLevelByMediaSize(levels, width2, height2) {
    if (!(levels != null && levels.length)) {
      return -1;
    }
    const atGreatestBandwidth = (curLevel, nextLevel) => {
      if (!nextLevel) {
        return true;
      }
      return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
    };
    let maxLevelIndex = levels.length - 1;
    const squareSize = Math.max(width2, height2);
    for (let i = 0; i < levels.length; i += 1) {
      const level = levels[i];
      if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
        maxLevelIndex = i;
        break;
      }
    }
    return maxLevelIndex;
  }
};
var CmObjectType = {
  /**
   * text file, such as a manifest or playlist
   */
  MANIFEST: "m",
  /**
   * audio only
   */
  AUDIO: "a",
  /**
   * video only
   */
  VIDEO: "v",
  /**
   * muxed audio and video
   */
  MUXED: "av",
  /**
   * init segment
   */
  INIT: "i",
  /**
   * caption or subtitle
   */
  CAPTION: "c",
  /**
   * ISOBMFF timed text track
   */
  TIMED_TEXT: "tt",
  /**
   * cryptographic key, license or certificate.
   */
  KEY: "k",
  /**
   * other
   */
  OTHER: "o"
};
var CmcdObjectType = CmObjectType;
var CmStreamingFormat = {
  /**
   * HTTP Live Streaming (HLS)
   */
  HLS: "h"
};
var CmcdStreamingFormat = CmStreamingFormat;
var CMCD_OBJECT = "CMCD-Object";
var CMCD_REQUEST = "CMCD-Request";
var CMCD_SESSION = "CMCD-Session";
var CMCD_STATUS = "CMCD-Status";
var CmcdHeaderField = {
  /**
   * keys whose values vary with the object being requested.
   */
  OBJECT: CMCD_OBJECT,
  /**
   * keys whose values vary with each request.
   */
  REQUEST: CMCD_REQUEST,
  /**
   * keys whose values are expected to be invariant over the life of the session.
   */
  SESSION: CMCD_SESSION,
  /**
   * keys whose values do not vary with every request or object.
   */
  STATUS: CMCD_STATUS
};
var CmcdHeaderMap = {
  [CmcdHeaderField.OBJECT]: ["br", "d", "ot", "tb"],
  [CmcdHeaderField.REQUEST]: ["bl", "dl", "mtp", "nor", "nrr", "su"],
  [CmcdHeaderField.SESSION]: ["cid", "pr", "sf", "sid", "st", "v"],
  [CmcdHeaderField.STATUS]: ["bs", "rtp"]
};
var SfItem = class _SfItem {
  constructor(value, params) {
    if (Array.isArray(value)) {
      value = value.map((v) => v instanceof _SfItem ? v : new _SfItem(v));
    }
    this.value = value;
    this.params = params;
  }
};
var DICT = "Dict";
function format(value) {
  if (Array.isArray(value)) {
    return JSON.stringify(value);
  }
  if (value instanceof Map) {
    return "Map{}";
  }
  if (value instanceof Set) {
    return "Set{}";
  }
  if (typeof value === "object") {
    return JSON.stringify(value);
  }
  return String(value);
}
function throwError(action, src, type2, cause) {
  return new Error(`failed to ${action} "${format(src)}" as ${type2}`, {
    cause
  });
}
function serializeError(src, type2, cause) {
  return throwError("serialize", src, type2, cause);
}
var SfToken = class {
  constructor(description) {
    this.description = description;
  }
};
var BARE_ITEM = "Bare Item";
var BOOLEAN = "Boolean";
function serializeBoolean(value) {
  if (typeof value !== "boolean") {
    throw serializeError(value, BOOLEAN);
  }
  return value ? "?1" : "?0";
}
var BYTES = "Byte Sequence";
function serializeByteSequence(value) {
  if (ArrayBuffer.isView(value) === false) {
    throw serializeError(value, BYTES);
  }
  return `:${base64encode(value)}:`;
}
var INTEGER = "Integer";
function isInvalidInt(value) {
  return value < -999999999999999 || 999999999999999 < value;
}
function serializeInteger(value) {
  if (isInvalidInt(value)) {
    throw serializeError(value, INTEGER);
  }
  return value.toString();
}
function serializeDate(value) {
  return `@${serializeInteger(value.getTime() / 1e3)}`;
}
var DECIMAL = "Decimal";
function serializeDecimal(value) {
  const roundedValue = roundToEven(value, 3);
  if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {
    throw serializeError(value, DECIMAL);
  }
  const stringValue = roundedValue.toString();
  return stringValue.includes(".") ? stringValue : `${stringValue}.0`;
}
var STRING = "String";
var STRING_REGEX = /[\x00-\x1f\x7f]+/;
function serializeString(value) {
  if (STRING_REGEX.test(value)) {
    throw serializeError(value, STRING);
  }
  return `"${value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`)}"`;
}
function symbolToStr(symbol) {
  return symbol.description || symbol.toString().slice(7, -1);
}
var TOKEN = "Token";
function serializeToken(token) {
  const value = symbolToStr(token);
  if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value) === false) {
    throw serializeError(value, TOKEN);
  }
  return value;
}
function serializeBareItem(value) {
  switch (typeof value) {
    case "number":
      if (!isFiniteNumber(value)) {
        throw serializeError(value, BARE_ITEM);
      }
      if (Number.isInteger(value)) {
        return serializeInteger(value);
      }
      return serializeDecimal(value);
    case "string":
      return serializeString(value);
    case "symbol":
      return serializeToken(value);
    case "boolean":
      return serializeBoolean(value);
    case "object":
      if (value instanceof Date) {
        return serializeDate(value);
      }
      if (value instanceof Uint8Array) {
        return serializeByteSequence(value);
      }
      if (value instanceof SfToken) {
        return serializeToken(value);
      }
    default:
      throw serializeError(value, BARE_ITEM);
  }
}
var KEY = "Key";
function serializeKey(value) {
  if (/^[a-z*][a-z0-9\-_.*]*$/.test(value) === false) {
    throw serializeError(value, KEY);
  }
  return value;
}
function serializeParams(params) {
  if (params == null) {
    return "";
  }
  return Object.entries(params).map(([key, value]) => {
    if (value === true) {
      return `;${serializeKey(key)}`;
    }
    return `;${serializeKey(key)}=${serializeBareItem(value)}`;
  }).join("");
}
function serializeItem(value) {
  if (value instanceof SfItem) {
    return `${serializeBareItem(value.value)}${serializeParams(value.params)}`;
  } else {
    return serializeBareItem(value);
  }
}
function serializeInnerList(value) {
  return `(${value.value.map(serializeItem).join(" ")})${serializeParams(value.params)}`;
}
function serializeDict(dict, options = {
  whitespace: true
}) {
  if (typeof dict !== "object") {
    throw serializeError(dict, DICT);
  }
  const entries = dict instanceof Map ? dict.entries() : Object.entries(dict);
  const optionalWhiteSpace = (options === null || options === void 0 ? void 0 : options.whitespace) ? " " : "";
  return Array.from(entries).map(([key, item]) => {
    if (item instanceof SfItem === false) {
      item = new SfItem(item);
    }
    let output = serializeKey(key);
    if (item.value === true) {
      output += serializeParams(item.params);
    } else {
      output += "=";
      if (Array.isArray(item.value)) {
        output += serializeInnerList(item);
      } else {
        output += serializeItem(item);
      }
    }
    return output;
  }).join(`,${optionalWhiteSpace}`);
}
function encodeSfDict(value, options) {
  return serializeDict(value, options);
}
function isTokenField(key) {
  return key === "ot" || key === "sf" || key === "st";
}
function isValid(value) {
  if (typeof value === "number") {
    return isFiniteNumber(value);
  }
  return value != null && value !== "" && value !== false;
}
var toRounded = (value) => Math.round(value);
var toUrlSafe = (value, options) => {
  if (options === null || options === void 0 ? void 0 : options.baseUrl) {
    value = urlToRelativePath(value, options.baseUrl);
  }
  return encodeURIComponent(value);
};
var toHundred = (value) => toRounded(value / 100) * 100;
var CmcdFormatters = {
  /**
   * Bitrate (kbps) rounded integer
   */
  br: toRounded,
  /**
   * Duration (milliseconds) rounded integer
   */
  d: toRounded,
  /**
   * Buffer Length (milliseconds) rounded nearest 100ms
   */
  bl: toHundred,
  /**
   * Deadline (milliseconds) rounded nearest 100ms
   */
  dl: toHundred,
  /**
   * Measured Throughput (kbps) rounded nearest 100kbps
   */
  mtp: toHundred,
  /**
   * Next Object Request URL encoded
   */
  nor: toUrlSafe,
  /**
   * Requested maximum throughput (kbps) rounded nearest 100kbps
   */
  rtp: toHundred,
  /**
   * Top Bitrate (kbps) rounded integer
   */
  tb: toRounded
};
function processCmcd(obj, options) {
  const results = {};
  if (obj == null || typeof obj !== "object") {
    return results;
  }
  const keys3 = Object.keys(obj).sort();
  const formatters = _extends({}, CmcdFormatters, options === null || options === void 0 ? void 0 : options.formatters);
  const filter = options === null || options === void 0 ? void 0 : options.filter;
  keys3.forEach((key) => {
    if (filter === null || filter === void 0 ? void 0 : filter(key)) {
      return;
    }
    let value = obj[key];
    const formatter = formatters[key];
    if (formatter) {
      value = formatter(value, options);
    }
    if (key === "v" && value === 1) {
      return;
    }
    if (key == "pr" && value === 1) {
      return;
    }
    if (!isValid(value)) {
      return;
    }
    if (isTokenField(key) && typeof value === "string") {
      value = new SfToken(value);
    }
    results[key] = value;
  });
  return results;
}
function encodeCmcd(cmcd, options = {}) {
  if (!cmcd) {
    return "";
  }
  return encodeSfDict(processCmcd(cmcd, options), _extends({
    whitespace: false
  }, options));
}
function toCmcdHeaders(cmcd, options = {}) {
  const result = {};
  if (!cmcd) {
    return result;
  }
  const entries = Object.entries(cmcd);
  const headerMap = Object.entries(CmcdHeaderMap).concat(Object.entries((options === null || options === void 0 ? void 0 : options.customHeaderMap) || {}));
  const shards = entries.reduce((acc, entry) => {
    var _a, _b;
    const [key, value] = entry;
    const field = ((_a = headerMap.find((entry2) => entry2[1].includes(key))) === null || _a === void 0 ? void 0 : _a[0]) || CmcdHeaderField.REQUEST;
    (_b = acc[field]) !== null && _b !== void 0 ? _b : acc[field] = {};
    acc[field][key] = value;
    return acc;
  }, {});
  return Object.entries(shards).reduce((acc, [field, value]) => {
    acc[field] = encodeCmcd(value, options);
    return acc;
  }, result);
}
function appendCmcdHeaders(headers, cmcd, options) {
  return _extends(headers, toCmcdHeaders(cmcd, options));
}
var CMCD_PARAM = "CMCD";
function toCmcdQuery(cmcd, options = {}) {
  if (!cmcd) {
    return "";
  }
  const params = encodeCmcd(cmcd, options);
  return `${CMCD_PARAM}=${encodeURIComponent(params)}`;
}
var REGEX = /CMCD=[^&#]+/;
function appendCmcdQuery(url, cmcd, options) {
  const query = toCmcdQuery(cmcd, options);
  if (!query) {
    return url;
  }
  if (REGEX.test(url)) {
    return url.replace(REGEX, query);
  }
  const separator = url.includes("?") ? "&" : "?";
  return `${url}${separator}${query}`;
}
var CMCDController = class {
  constructor(hls) {
    this.hls = void 0;
    this.config = void 0;
    this.media = void 0;
    this.sid = void 0;
    this.cid = void 0;
    this.useHeaders = false;
    this.includeKeys = void 0;
    this.initialized = false;
    this.starved = false;
    this.buffering = true;
    this.audioBuffer = void 0;
    this.videoBuffer = void 0;
    this.onWaiting = () => {
      if (this.initialized) {
        this.starved = true;
      }
      this.buffering = true;
    };
    this.onPlaying = () => {
      if (!this.initialized) {
        this.initialized = true;
      }
      this.buffering = false;
    };
    this.applyPlaylistData = (context) => {
      try {
        this.apply(context, {
          ot: CmcdObjectType.MANIFEST,
          su: !this.initialized
        });
      } catch (error) {
        this.hls.logger.warn("Could not generate manifest CMCD data.", error);
      }
    };
    this.applyFragmentData = (context) => {
      try {
        const {
          frag,
          part
        } = context;
        const level = this.hls.levels[frag.level];
        const ot = this.getObjectType(frag);
        const data = {
          d: (part || frag).duration * 1e3,
          ot
        };
        if (ot === CmcdObjectType.VIDEO || ot === CmcdObjectType.AUDIO || ot == CmcdObjectType.MUXED) {
          data.br = level.bitrate / 1e3;
          data.tb = this.getTopBandwidth(ot) / 1e3;
          data.bl = this.getBufferLength(ot);
        }
        const next = part ? this.getNextPart(part) : this.getNextFrag(frag);
        if (next != null && next.url && next.url !== frag.url) {
          data.nor = next.url;
        }
        this.apply(context, data);
      } catch (error) {
        this.hls.logger.warn("Could not generate segment CMCD data.", error);
      }
    };
    this.hls = hls;
    const config = this.config = hls.config;
    const {
      cmcd
    } = config;
    if (cmcd != null) {
      config.pLoader = this.createPlaylistLoader();
      config.fLoader = this.createFragmentLoader();
      this.sid = cmcd.sessionId || hls.sessionId;
      this.cid = cmcd.contentId;
      this.useHeaders = cmcd.useHeaders === true;
      this.includeKeys = cmcd.includeKeys;
      this.registerListeners();
    }
  }
  registerListeners() {
    const hls = this.hls;
    hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
    hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  }
  unregisterListeners() {
    const hls = this.hls;
    hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
    hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  }
  destroy() {
    this.unregisterListeners();
    this.onMediaDetached();
    this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
    this.onWaiting = this.onPlaying = this.media = null;
  }
  onMediaAttached(event, data) {
    this.media = data.media;
    this.media.addEventListener("waiting", this.onWaiting);
    this.media.addEventListener("playing", this.onPlaying);
  }
  onMediaDetached() {
    if (!this.media) {
      return;
    }
    this.media.removeEventListener("waiting", this.onWaiting);
    this.media.removeEventListener("playing", this.onPlaying);
    this.media = null;
  }
  onBufferCreated(event, data) {
    var _data$tracks$audio, _data$tracks$video;
    this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer;
    this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer;
  }
  /**
   * Create baseline CMCD data
   */
  createData() {
    var _this$media;
    return {
      v: 1,
      sf: CmcdStreamingFormat.HLS,
      sid: this.sid,
      cid: this.cid,
      pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate,
      mtp: this.hls.bandwidthEstimate / 1e3
    };
  }
  /**
   * Apply CMCD data to a request.
   */
  apply(context, data = {}) {
    _extends(data, this.createData());
    const isVideo = data.ot === CmcdObjectType.INIT || data.ot === CmcdObjectType.VIDEO || data.ot === CmcdObjectType.MUXED;
    if (this.starved && isVideo) {
      data.bs = true;
      data.su = true;
      this.starved = false;
    }
    if (data.su == null) {
      data.su = this.buffering;
    }
    const {
      includeKeys
    } = this;
    if (includeKeys) {
      data = Object.keys(data).reduce((acc, key) => {
        includeKeys.includes(key) && (acc[key] = data[key]);
        return acc;
      }, {});
    }
    const options = {
      baseUrl: context.url
    };
    if (this.useHeaders) {
      if (!context.headers) {
        context.headers = {};
      }
      appendCmcdHeaders(context.headers, data, options);
    } else {
      context.url = appendCmcdQuery(context.url, data, options);
    }
  }
  getNextFrag(fragment) {
    var _this$hls$levels$frag;
    const levelDetails = (_this$hls$levels$frag = this.hls.levels[fragment.level]) == null ? void 0 : _this$hls$levels$frag.details;
    if (levelDetails) {
      const index = fragment.sn - levelDetails.startSN;
      return levelDetails.fragments[index + 1];
    }
    return void 0;
  }
  getNextPart(part) {
    var _this$hls$levels$frag2, _this$hls$levels$frag3;
    const {
      index,
      fragment
    } = part;
    const partList = (_this$hls$levels$frag2 = this.hls.levels[fragment.level]) == null ? void 0 : (_this$hls$levels$frag3 = _this$hls$levels$frag2.details) == null ? void 0 : _this$hls$levels$frag3.partList;
    if (partList) {
      const {
        sn
      } = fragment;
      for (let i = partList.length - 1; i >= 0; i--) {
        const p = partList[i];
        if (p.index === index && p.fragment.sn === sn) {
          return partList[i + 1];
        }
      }
    }
    return void 0;
  }
  /**
   * The CMCD object type.
   */
  getObjectType(fragment) {
    const {
      type: type2
    } = fragment;
    if (type2 === "subtitle") {
      return CmcdObjectType.TIMED_TEXT;
    }
    if (fragment.sn === "initSegment") {
      return CmcdObjectType.INIT;
    }
    if (type2 === "audio") {
      return CmcdObjectType.AUDIO;
    }
    if (type2 === "main") {
      if (!this.hls.audioTracks.length) {
        return CmcdObjectType.MUXED;
      }
      return CmcdObjectType.VIDEO;
    }
    return void 0;
  }
  /**
   * Get the highest bitrate.
   */
  getTopBandwidth(type2) {
    let bitrate = 0;
    let levels;
    const hls = this.hls;
    if (type2 === CmcdObjectType.AUDIO) {
      levels = hls.audioTracks;
    } else {
      const max = hls.maxAutoLevel;
      const len = max > -1 ? max + 1 : hls.levels.length;
      levels = hls.levels.slice(0, len);
    }
    for (const level of levels) {
      if (level.bitrate > bitrate) {
        bitrate = level.bitrate;
      }
    }
    return bitrate > 0 ? bitrate : NaN;
  }
  /**
   * Get the buffer length for a media type in milliseconds
   */
  getBufferLength(type2) {
    const media = this.media;
    const buffer = type2 === CmcdObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;
    if (!buffer || !media) {
      return NaN;
    }
    const info = BufferHelper.bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);
    return info.len * 1e3;
  }
  /**
   * Create a playlist loader
   */
  createPlaylistLoader() {
    const {
      pLoader
    } = this.config;
    const apply = this.applyPlaylistData;
    const Ctor = pLoader || this.config.loader;
    return class CmcdPlaylistLoader {
      constructor(config) {
        this.loader = void 0;
        this.loader = new Ctor(config);
      }
      get stats() {
        return this.loader.stats;
      }
      get context() {
        return this.loader.context;
      }
      destroy() {
        this.loader.destroy();
      }
      abort() {
        this.loader.abort();
      }
      load(context, config, callbacks) {
        apply(context);
        this.loader.load(context, config, callbacks);
      }
    };
  }
  /**
   * Create a playlist loader
   */
  createFragmentLoader() {
    const {
      fLoader
    } = this.config;
    const apply = this.applyFragmentData;
    const Ctor = fLoader || this.config.loader;
    return class CmcdFragmentLoader {
      constructor(config) {
        this.loader = void 0;
        this.loader = new Ctor(config);
      }
      get stats() {
        return this.loader.stats;
      }
      get context() {
        return this.loader.context;
      }
      destroy() {
        this.loader.destroy();
      }
      abort() {
        this.loader.abort();
      }
      load(context, config, callbacks) {
        apply(context);
        this.loader.load(context, config, callbacks);
      }
    };
  }
};
var PATHWAY_PENALTY_DURATION_MS = 3e5;
var ContentSteeringController = class extends Logger {
  constructor(hls) {
    super("content-steering", hls.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 = false;
    this.enabled = true;
    this.levels = null;
    this.audioTracks = null;
    this.subtitleTracks = null;
    this.penalizedPathways = {};
    this.hls = hls;
    this.registerListeners();
  }
  registerListeners() {
    const hls = this.hls;
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
    hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.on(Events.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const hls = this.hls;
    if (!hls) {
      return;
    }
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
    hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.off(Events.ERROR, this.onError, this);
  }
  pathways() {
    return (this.levels || []).reduce((pathways, level) => {
      if (pathways.indexOf(level.pathwayId) === -1) {
        pathways.push(level.pathwayId);
      }
      return pathways;
    }, []);
  }
  get pathwayPriority() {
    return this._pathwayPriority;
  }
  set pathwayPriority(pathwayPriority) {
    this.updatePathwayPriority(pathwayPriority);
  }
  startLoad() {
    this.started = true;
    this.clearTimeout();
    if (this.enabled && this.uri) {
      if (this.updated) {
        const ttl = this.timeToLoad * 1e3 - (performance.now() - this.updated);
        if (ttl > 0) {
          this.scheduleRefresh(this.uri, ttl);
          return;
        }
      }
      this.loadSteeringManifest(this.uri);
    }
  }
  stopLoad() {
    this.started = false;
    if (this.loader) {
      this.loader.destroy();
      this.loader = null;
    }
    this.clearTimeout();
  }
  clearTimeout() {
    if (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(levelToRemove) {
    const levels = this.levels;
    if (levels) {
      this.levels = levels.filter((level) => level !== levelToRemove);
    }
  }
  onManifestLoading() {
    this.stopLoad();
    this.enabled = true;
    this.timeToLoad = 300;
    this.updated = 0;
    this.uri = null;
    this.pathwayId = ".";
    this.levels = this.audioTracks = this.subtitleTracks = null;
  }
  onManifestLoaded(event, data) {
    const {
      contentSteering
    } = data;
    if (contentSteering === null) {
      return;
    }
    this.pathwayId = contentSteering.pathwayId;
    this.uri = contentSteering.uri;
    if (this.started) {
      this.startLoad();
    }
  }
  onManifestParsed(event, data) {
    this.audioTracks = data.audioTracks;
    this.subtitleTracks = data.subtitleTracks;
  }
  onError(event, data) {
    const {
      errorAction
    } = data;
    if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
      const levels = this.levels;
      let pathwayPriority = this._pathwayPriority;
      let errorPathway = this.pathwayId;
      if (data.context) {
        const {
          groupId,
          pathwayId,
          type: type2
        } = data.context;
        if (groupId && levels) {
          errorPathway = this.getPathwayForGroupId(groupId, type2, errorPathway);
        } else if (pathwayId) {
          errorPathway = pathwayId;
        }
      }
      if (!(errorPathway in this.penalizedPathways)) {
        this.penalizedPathways[errorPathway] = performance.now();
      }
      if (!pathwayPriority && levels) {
        pathwayPriority = this.pathways();
      }
      if (pathwayPriority && pathwayPriority.length > 1) {
        this.updatePathwayPriority(pathwayPriority);
        errorAction.resolved = this.pathwayId !== errorPathway;
      }
      if (!errorAction.resolved) {
        this.warn(`Could not resolve ${data.details} ("${data.error.message}") with content-steering for Pathway: ${errorPathway} levels: ${levels ? levels.length : levels} priorities: ${stringify(pathwayPriority)} penalized: ${stringify(this.penalizedPathways)}`);
      }
    }
  }
  filterParsedLevels(levels) {
    this.levels = levels;
    let pathwayLevels = this.getLevelsForPathway(this.pathwayId);
    if (pathwayLevels.length === 0) {
      const pathwayId = levels[0].pathwayId;
      this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`);
      pathwayLevels = this.getLevelsForPathway(pathwayId);
      this.pathwayId = pathwayId;
    }
    if (pathwayLevels.length !== levels.length) {
      this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`);
    }
    return pathwayLevels;
  }
  getLevelsForPathway(pathwayId) {
    if (this.levels === null) {
      return [];
    }
    return this.levels.filter((level) => pathwayId === level.pathwayId);
  }
  updatePathwayPriority(pathwayPriority) {
    this._pathwayPriority = pathwayPriority;
    let levels;
    const penalizedPathways = this.penalizedPathways;
    const now2 = performance.now();
    Object.keys(penalizedPathways).forEach((pathwayId) => {
      if (now2 - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
        delete penalizedPathways[pathwayId];
      }
    });
    for (let i = 0; i < pathwayPriority.length; i++) {
      const pathwayId = pathwayPriority[i];
      if (pathwayId in penalizedPathways) {
        continue;
      }
      if (pathwayId === this.pathwayId) {
        return;
      }
      const selectedIndex = this.hls.nextLoadLevel;
      const selectedLevel = this.hls.levels[selectedIndex];
      levels = this.getLevelsForPathway(pathwayId);
      if (levels.length > 0) {
        this.log(`Setting Pathway to "${pathwayId}"`);
        this.pathwayId = pathwayId;
        reassignFragmentLevelIndexes(levels);
        this.hls.trigger(Events.LEVELS_UPDATED, {
          levels
        });
        const levelAfterChange = this.hls.levels[selectedIndex];
        if (selectedLevel && levelAfterChange && this.levels) {
          if (levelAfterChange.attrs["STABLE-VARIANT-ID"] !== selectedLevel.attrs["STABLE-VARIANT-ID"] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
            this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);
          }
          this.hls.nextLoadLevel = selectedIndex;
        }
        break;
      }
    }
  }
  getPathwayForGroupId(groupId, type2, defaultPathway) {
    const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
    for (let i = 0; i < levels.length; i++) {
      if (type2 === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type2 === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
        return levels[i].pathwayId;
      }
    }
    return defaultPathway;
  }
  clonePathways(pathwayClones) {
    const levels = this.levels;
    if (!levels) {
      return;
    }
    const audioGroupCloneMap = {};
    const subtitleGroupCloneMap = {};
    pathwayClones.forEach((pathwayClone) => {
      const {
        ID: cloneId,
        "BASE-ID": baseId,
        "URI-REPLACEMENT": uriReplacement
      } = pathwayClone;
      if (levels.some((level) => level.pathwayId === cloneId)) {
        return;
      }
      const clonedVariants = this.getLevelsForPathway(baseId).map((baseLevel) => {
        const attributes = new AttrList(baseLevel.attrs);
        attributes["PATHWAY-ID"] = cloneId;
        const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;
        const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;
        if (clonedAudioGroupId) {
          audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
          attributes.AUDIO = clonedAudioGroupId;
        }
        if (clonedSubtitleGroupId) {
          subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
          attributes.SUBTITLES = clonedSubtitleGroupId;
        }
        const url = performUriReplacement(baseLevel.uri, attributes["STABLE-VARIANT-ID"], "PER-VARIANT-URIS", uriReplacement);
        const clonedLevel = new Level({
          attrs: attributes,
          audioCodec: baseLevel.audioCodec,
          bitrate: baseLevel.bitrate,
          height: baseLevel.height,
          name: baseLevel.name,
          url,
          videoCodec: baseLevel.videoCodec,
          width: baseLevel.width
        });
        if (baseLevel.audioGroups) {
          for (let i = 1; i < baseLevel.audioGroups.length; i++) {
            clonedLevel.addGroupId("audio", `${baseLevel.audioGroups[i]}_clone_${cloneId}`);
          }
        }
        if (baseLevel.subtitleGroups) {
          for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {
            clonedLevel.addGroupId("text", `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`);
          }
        }
        return clonedLevel;
      });
      levels.push(...clonedVariants);
      cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
      cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
    });
  }
  loadSteeringManifest(uri) {
    const config = this.hls.config;
    const Loader = config.loader;
    if (this.loader) {
      this.loader.destroy();
    }
    this.loader = new Loader(config);
    let url;
    try {
      url = new self.URL(uri);
    } catch (error) {
      this.enabled = false;
      this.log(`Failed to parse Steering Manifest URI: ${uri}`);
      return;
    }
    if (url.protocol !== "data:") {
      const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
      url.searchParams.set("_HLS_pathway", this.pathwayId);
      url.searchParams.set("_HLS_throughput", "" + throughput);
    }
    const context = {
      responseType: "json",
      url: url.href
    };
    const loadPolicy = config.steeringManifestLoadPolicy.default;
    const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
    const loaderConfig = {
      loadPolicy,
      timeout: loadPolicy.maxLoadTimeMs,
      maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
      retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
      maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
    };
    const callbacks = {
      onSuccess: (response, stats, context2, networkDetails) => {
        this.log(`Loaded steering manifest: "${url}"`);
        const steeringData = response.data;
        if ((steeringData == null ? void 0 : steeringData.VERSION) !== 1) {
          this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);
          return;
        }
        this.updated = performance.now();
        this.timeToLoad = steeringData.TTL;
        const {
          "RELOAD-URI": reloadUri,
          "PATHWAY-CLONES": pathwayClones,
          "PATHWAY-PRIORITY": pathwayPriority
        } = steeringData;
        if (reloadUri) {
          try {
            this.uri = new self.URL(reloadUri, url).href;
          } catch (error) {
            this.enabled = false;
            this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);
            return;
          }
        }
        this.scheduleRefresh(this.uri || context2.url);
        if (pathwayClones) {
          this.clonePathways(pathwayClones);
        }
        const loadedSteeringData = {
          steeringManifest: steeringData,
          url: url.toString()
        };
        this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
        if (pathwayPriority) {
          this.updatePathwayPriority(pathwayPriority);
        }
      },
      onError: (error, context2, networkDetails, stats) => {
        this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context2.url})`);
        this.stopLoad();
        if (error.code === 410) {
          this.enabled = false;
          this.log(`Steering manifest ${context2.url} no longer available`);
          return;
        }
        let ttl = this.timeToLoad * 1e3;
        if (error.code === 429) {
          const loader = this.loader;
          if (typeof (loader == null ? void 0 : loader.getResponseHeader) === "function") {
            const retryAfter = loader.getResponseHeader("Retry-After");
            if (retryAfter) {
              ttl = parseFloat(retryAfter) * 1e3;
            }
          }
          this.log(`Steering manifest ${context2.url} rate limited`);
          return;
        }
        this.scheduleRefresh(this.uri || context2.url, ttl);
      },
      onTimeout: (stats, context2, networkDetails) => {
        this.log(`Timeout loading steering manifest (${context2.url})`);
        this.scheduleRefresh(this.uri || context2.url);
      }
    };
    this.log(`Requesting steering manifest: ${url}`);
    this.loader.load(context, loaderConfig, callbacks);
  }
  scheduleRefresh(uri, ttlMs = this.timeToLoad * 1e3) {
    this.clearTimeout();
    this.reloadTimer = self.setTimeout(() => {
      var _this$hls;
      const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;
      if (media && !media.ended) {
        this.loadSteeringManifest(uri);
        return;
      }
      this.scheduleRefresh(uri, this.timeToLoad * 1e3);
    }, ttlMs);
  }
};
function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  if (!tracks) {
    return;
  }
  Object.keys(groupCloneMap).forEach((audioGroupId) => {
    const clonedTracks = tracks.filter((track) => track.groupId === audioGroupId).map((track) => {
      const clonedTrack = _extends({}, track);
      clonedTrack.details = void 0;
      clonedTrack.attrs = new AttrList(clonedTrack.attrs);
      clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs["STABLE-RENDITION-ID"], "PER-RENDITION-URIS", uriReplacement);
      clonedTrack.groupId = clonedTrack.attrs["GROUP-ID"] = groupCloneMap[audioGroupId];
      clonedTrack.attrs["PATHWAY-ID"] = cloneId;
      return clonedTrack;
    });
    tracks.push(...clonedTracks);
  });
}
function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  const {
    HOST: host,
    PARAMS: params,
    [perOptionKey]: perOptionUris
  } = uriReplacement;
  let perVariantUri;
  if (stableId) {
    perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
    if (perVariantUri) {
      uri = perVariantUri;
    }
  }
  const url = new self.URL(uri);
  if (host && !perVariantUri) {
    url.host = host;
  }
  if (params) {
    Object.keys(params).sort().forEach((key) => {
      if (key) {
        url.searchParams.set(key, params[key]);
      }
    });
  }
  return url.href;
}
var EMEController = class _EMEController extends Logger {
  constructor(hls) {
    super("eme", hls.logger);
    this.hls = void 0;
    this.config = void 0;
    this.media = null;
    this.keyFormatPromise = null;
    this.keySystemAccessPromises = {};
    this._requestLicenseFailureCount = 0;
    this.mediaKeySessions = [];
    this.keyIdToKeySessionPromise = {};
    this.setMediaKeysQueue = _EMEController.CDMCleanupPromise ? [_EMEController.CDMCleanupPromise] : [];
    this.onMediaEncrypted = (event) => {
      const {
        initDataType,
        initData
      } = event;
      const logMessage = `"${event.type}" event: init data type: "${initDataType}"`;
      this.debug(logMessage);
      if (initData === null) {
        return;
      }
      if (!this.keyFormatPromise) {
        let keySystems = Object.keys(this.keySystemAccessPromises);
        if (!keySystems.length) {
          keySystems = getKeySystemsForConfig(this.config);
        }
        const keyFormats = keySystems.map(keySystemDomainToKeySystemFormat).filter((k) => !!k);
        this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
      }
      this.keyFormatPromise.then((keySystemFormat) => {
        const keySystem = keySystemFormatToKeySystemDomain(keySystemFormat);
        let keyId;
        let keySystemDomain;
        if (initDataType === "sinf") {
          if (keySystem !== KeySystems.FAIRPLAY) {
            this.warn(`Ignoring unexpected "${event.type}" event with init data type: "${initDataType}" for selected key-system ${keySystem}`);
            return;
          }
          const json = bin2str(new Uint8Array(initData));
          try {
            const sinf = base64Decode(JSON.parse(json).sinf);
            const tenc = parseSinf(sinf);
            if (!tenc) {
              throw new Error(`'schm' box missing or not cbcs/cenc with schi > tenc`);
            }
            keyId = new Uint8Array(tenc.subarray(8, 24));
            keySystemDomain = KeySystems.FAIRPLAY;
          } catch (error) {
            this.warn(`${logMessage} Failed to parse sinf: ${error}`);
            return;
          }
        } else {
          if (keySystem !== KeySystems.WIDEVINE && keySystem !== KeySystems.PLAYREADY) {
            this.warn(`Ignoring unexpected "${event.type}" event with init data type: "${initDataType}" for selected key-system ${keySystem}`);
            return;
          }
          const psshResults = parseMultiPssh(initData);
          const psshInfos = psshResults.filter((pssh) => !!pssh.systemId && keySystemIdToKeySystemDomain(pssh.systemId) === keySystem);
          if (psshInfos.length > 1) {
            this.warn(`${logMessage} Using first of ${psshInfos.length} pssh found for selected key-system ${keySystem}`);
          }
          const psshInfo = psshInfos[0];
          if (!psshInfo) {
            if (psshResults.length === 0 || psshResults.some((pssh) => !pssh.systemId)) {
              this.warn(`${logMessage} contains incomplete or invalid pssh data`);
            } else {
              this.log(`ignoring ${logMessage} for ${psshResults.map((pssh) => keySystemIdToKeySystemDomain(pssh.systemId)).join(",")} pssh data in favor of playlist keys`);
            }
            return;
          }
          keySystemDomain = keySystemIdToKeySystemDomain(psshInfo.systemId);
          if (psshInfo.version === 0 && psshInfo.data) {
            if (keySystemDomain === KeySystems.WIDEVINE) {
              const offset = psshInfo.data.length - 22;
              keyId = new Uint8Array(psshInfo.data.subarray(offset, offset + 16));
            } else if (keySystemDomain === KeySystems.PLAYREADY) {
              keyId = parsePlayReadyWRM(psshInfo.data);
            }
          }
        }
        if (!keySystemDomain || !keyId) {
          return;
        }
        const keyIdHex = Hex.hexDump(keyId);
        const {
          keyIdToKeySessionPromise,
          mediaKeySessions
        } = this;
        let keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex];
        for (let i = 0; i < mediaKeySessions.length; i++) {
          const keyContext = mediaKeySessions[i];
          const decryptdata = keyContext.decryptdata;
          if (!decryptdata.keyId) {
            continue;
          }
          const oldKeyIdHex = Hex.hexDump(decryptdata.keyId);
          if (keyIdHex === oldKeyIdHex || decryptdata.uri.replace(/-/g, "").indexOf(keyIdHex) !== -1) {
            keySessionContextPromise = keyIdToKeySessionPromise[oldKeyIdHex];
            if (decryptdata.pssh) {
              break;
            }
            delete keyIdToKeySessionPromise[oldKeyIdHex];
            decryptdata.pssh = new Uint8Array(initData);
            decryptdata.keyId = keyId;
            keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] = keySessionContextPromise.then(() => {
              return this.generateRequestWithPreferredKeySession(keyContext, initDataType, initData, "encrypted-event-key-match");
            });
            keySessionContextPromise.catch((error) => this.handleError(error));
            break;
          }
        }
        if (!keySessionContextPromise) {
          if (keySystemDomain !== keySystem) {
            this.log(`Ignoring "${event.type}" event with ${keySystemDomain} init data for selected key-system ${keySystem}`);
            return;
          }
          keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] = this.getKeySystemSelectionPromise([keySystemDomain]).then(({
            keySystem: keySystem2,
            mediaKeys
          }) => {
            var _keySystemToKeySystem;
            this.throwIfDestroyed();
            const decryptdata = new LevelKey("ISO-23001-7", keyIdHex, (_keySystemToKeySystem = keySystemDomainToKeySystemFormat(keySystem2)) != null ? _keySystemToKeySystem : "");
            decryptdata.pssh = new Uint8Array(initData);
            decryptdata.keyId = keyId;
            return this.attemptSetMediaKeys(keySystem2, mediaKeys).then(() => {
              this.throwIfDestroyed();
              const keySessionContext = this.createMediaKeySessionContext({
                decryptdata,
                keySystem: keySystem2,
                mediaKeys
              });
              return this.generateRequestWithPreferredKeySession(keySessionContext, initDataType, initData, "encrypted-event-no-match");
            });
          });
          keySessionContextPromise.catch((error) => this.handleError(error));
        }
      });
    };
    this.onWaitingForKey = (event) => {
      this.log(`"${event.type}" event`);
    };
    this.hls = hls;
    this.config = hls.config;
    this.registerListeners();
  }
  destroy() {
    const media = this.media;
    this.unregisterListeners();
    this.onMediaDetached();
    this._clear(media);
    const config = this.config;
    config.requestMediaKeySystemAccessFunc = null;
    config.licenseXhrSetup = config.licenseResponseCallback = void 0;
    config.drmSystems = config.drmSystemOptions = {};
    this.hls = this.config = this.keyIdToKeySessionPromise = null;
    this.onMediaEncrypted = this.onWaitingForKey = null;
  }
  registerListeners() {
    this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
    this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  }
  unregisterListeners() {
    this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
    this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  }
  getLicenseServerUrl(keySystem) {
    const {
      drmSystems,
      widevineLicenseUrl
    } = this.config;
    const keySystemConfiguration = drmSystems[keySystem];
    if (keySystemConfiguration) {
      return keySystemConfiguration.licenseUrl;
    }
    if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {
      return widevineLicenseUrl;
    }
  }
  getLicenseServerUrlOrThrow(keySystem) {
    const url = this.getLicenseServerUrl(keySystem);
    if (url === void 0) {
      throw new Error(`no license server URL configured for key-system "${keySystem}"`);
    }
    return url;
  }
  getServerCertificateUrl(keySystem) {
    const {
      drmSystems
    } = this.config;
    const keySystemConfiguration = drmSystems[keySystem];
    if (keySystemConfiguration) {
      return keySystemConfiguration.serverCertificateUrl;
    } else {
      this.log(`No Server Certificate in config.drmSystems["${keySystem}"]`);
    }
  }
  attemptKeySystemAccess(keySystemsToAttempt) {
    const levels = this.hls.levels;
    const uniqueCodec = (value, i, a) => !!value && a.indexOf(value) === i;
    const audioCodecs = levels.map((level) => level.audioCodec).filter(uniqueCodec);
    const videoCodecs = levels.map((level) => level.videoCodec).filter(uniqueCodec);
    if (audioCodecs.length + videoCodecs.length === 0) {
      videoCodecs.push("avc1.42e01e");
    }
    return new Promise((resolve, reject) => {
      const attempt = (keySystems) => {
        const keySystem = keySystems.shift();
        this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then((mediaKeys) => resolve({
          keySystem,
          mediaKeys
        })).catch((error) => {
          if (keySystems.length) {
            attempt(keySystems);
          } else if (error instanceof EMEKeyError) {
            reject(error);
          } else {
            reject(new EMEKeyError({
              type: ErrorTypes.KEY_SYSTEM_ERROR,
              details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
              error,
              fatal: true
            }, error.message));
          }
        });
      };
      attempt(keySystemsToAttempt);
    });
  }
  requestMediaKeySystemAccess(keySystem, supportedConfigurations) {
    const {
      requestMediaKeySystemAccessFunc
    } = this.config;
    if (!(typeof requestMediaKeySystemAccessFunc === "function")) {
      let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;
      if (requestMediaKeySystemAccess === null && self.location.protocol === "http:") {
        errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;
      }
      return Promise.reject(new Error(errMessage));
    }
    return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);
  }
  getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) {
    const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions);
    const keySystemAccessPromises = this.keySystemAccessPromises[keySystem];
    let keySystemAccess = keySystemAccessPromises == null ? void 0 : keySystemAccessPromises.keySystemAccess;
    if (!keySystemAccess) {
      this.log(`Requesting encrypted media "${keySystem}" key-system access with config: ${stringify(mediaKeySystemConfigs)}`);
      keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
      const _keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = {
        keySystemAccess
      };
      keySystemAccess.catch((error) => {
        this.log(`Failed to obtain access to key-system "${keySystem}": ${error}`);
      });
      return keySystemAccess.then((mediaKeySystemAccess) => {
        this.log(`Access for key-system "${mediaKeySystemAccess.keySystem}" obtained`);
        const certificateRequest = this.fetchServerCertificate(keySystem);
        this.log(`Create media-keys for "${keySystem}"`);
        _keySystemAccessPromises.mediaKeys = mediaKeySystemAccess.createMediaKeys().then((mediaKeys) => {
          this.log(`Media-keys created for "${keySystem}"`);
          return certificateRequest.then((certificate) => {
            if (certificate) {
              return this.setMediaKeysServerCertificate(mediaKeys, keySystem, certificate);
            }
            return mediaKeys;
          });
        });
        _keySystemAccessPromises.mediaKeys.catch((error) => {
          this.error(`Failed to create media-keys for "${keySystem}"}: ${error}`);
        });
        return _keySystemAccessPromises.mediaKeys;
      });
    }
    return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys);
  }
  createMediaKeySessionContext({
    decryptdata,
    keySystem,
    mediaKeys
  }) {
    this.log(`Creating key-system session "${keySystem}" keyId: ${Hex.hexDump(decryptdata.keyId || [])}`);
    const mediaKeysSession = mediaKeys.createSession();
    const mediaKeySessionContext = {
      decryptdata,
      keySystem,
      mediaKeys,
      mediaKeysSession,
      keyStatus: "status-pending"
    };
    this.mediaKeySessions.push(mediaKeySessionContext);
    return mediaKeySessionContext;
  }
  renewKeySession(mediaKeySessionContext) {
    const decryptdata = mediaKeySessionContext.decryptdata;
    if (decryptdata.pssh) {
      const keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext);
      const keyId = this.getKeyIdString(decryptdata);
      const scheme = "cenc";
      this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh.buffer, "expired");
    } else {
      this.warn(`Could not renew expired session. Missing pssh initData.`);
    }
    this.removeSession(mediaKeySessionContext);
  }
  getKeyIdString(decryptdata) {
    if (!decryptdata) {
      throw new Error("Could not read keyId of undefined decryptdata");
    }
    if (decryptdata.keyId === null) {
      throw new Error("keyId is null");
    }
    return Hex.hexDump(decryptdata.keyId);
  }
  updateKeySession(mediaKeySessionContext, data) {
    var _mediaKeySessionConte;
    const keySession = mediaKeySessionContext.mediaKeysSession;
    this.log(`Updating key-session "${keySession.sessionId}" for keyID ${Hex.hexDump(((_mediaKeySessionConte = mediaKeySessionContext.decryptdata) == null ? void 0 : _mediaKeySessionConte.keyId) || [])}
      } (data length: ${data ? data.byteLength : data})`);
    return keySession.update(data);
  }
  selectKeySystemFormat(frag) {
    const keyFormats = Object.keys(frag.levelkeys || {});
    if (!this.keyFormatPromise) {
      this.log(`Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${frag.level}) key formats ${keyFormats.join(", ")}`);
      this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
    }
    return this.keyFormatPromise;
  }
  getKeyFormatPromise(keyFormats) {
    return new Promise((resolve, reject) => {
      const keySystemsInConfig = getKeySystemsForConfig(this.config);
      const keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter((value) => !!value && keySystemsInConfig.indexOf(value) !== -1);
      return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
        keySystem
      }) => {
        const keySystemFormat = keySystemDomainToKeySystemFormat(keySystem);
        if (keySystemFormat) {
          resolve(keySystemFormat);
        } else {
          reject(new Error(`Unable to find format for key-system "${keySystem}"`));
        }
      }).catch(reject);
    });
  }
  loadKey(data) {
    const decryptdata = data.keyInfo.decryptdata;
    const keyId = this.getKeyIdString(decryptdata);
    const keyDetails = `(keyId: ${keyId} format: "${decryptdata.keyFormat}" method: ${decryptdata.method} uri: ${decryptdata.uri})`;
    this.log(`Starting session for key ${keyDetails}`);
    let keyContextPromise = this.keyIdToKeySessionPromise[keyId];
    if (!keyContextPromise) {
      keyContextPromise = this.getKeySystemForKeyPromise(decryptdata).then(({
        keySystem,
        mediaKeys
      }) => {
        this.throwIfDestroyed();
        this.log(`Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`);
        return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {
          this.throwIfDestroyed();
          return this.createMediaKeySessionContext({
            keySystem,
            mediaKeys,
            decryptdata
          });
        });
      });
      const keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] = keyContextPromise.then((keySessionContext) => {
        const scheme = "cenc";
        const initData = decryptdata.pssh ? decryptdata.pssh.buffer : null;
        return this.generateRequestWithPreferredKeySession(keySessionContext, scheme, initData, "playlist-key");
      });
      keySessionContextPromise.catch((error) => this.handleError(error));
    }
    return keyContextPromise;
  }
  throwIfDestroyed(message = "Invalid state") {
    if (!this.hls) {
      throw new Error("invalid state");
    }
  }
  handleError(error) {
    if (!this.hls) {
      return;
    }
    this.error(error.message);
    if (error instanceof EMEKeyError) {
      this.hls.trigger(Events.ERROR, error.data);
    } else {
      this.hls.trigger(Events.ERROR, {
        type: ErrorTypes.KEY_SYSTEM_ERROR,
        details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
        error,
        fatal: true
      });
    }
  }
  getKeySystemForKeyPromise(decryptdata) {
    const keyId = this.getKeyIdString(decryptdata);
    const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];
    if (!mediaKeySessionContext) {
      const keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat);
      const keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config);
      return this.attemptKeySystemAccess(keySystemsToAttempt);
    }
    return mediaKeySessionContext;
  }
  getKeySystemSelectionPromise(keySystemsToAttempt) {
    if (!keySystemsToAttempt.length) {
      keySystemsToAttempt = getKeySystemsForConfig(this.config);
    }
    if (keySystemsToAttempt.length === 0) {
      throw new EMEKeyError({
        type: ErrorTypes.KEY_SYSTEM_ERROR,
        details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,
        fatal: true
      }, `Missing key-system license configuration options ${stringify({
        drmSystems: this.config.drmSystems
      })}`);
    }
    return this.attemptKeySystemAccess(keySystemsToAttempt);
  }
  attemptSetMediaKeys(keySystem, mediaKeys) {
    const queue = this.setMediaKeysQueue.slice();
    this.log(`Setting media-keys for "${keySystem}"`);
    const setMediaKeysPromise = Promise.all(queue).then(() => {
      if (!this.media) {
        throw new Error("Attempted to set mediaKeys without media element attached");
      }
      return this.media.setMediaKeys(mediaKeys);
    });
    this.setMediaKeysQueue.push(setMediaKeysPromise);
    return setMediaKeysPromise.then(() => {
      this.log(`Media-keys set for "${keySystem}"`);
      queue.push(setMediaKeysPromise);
      this.setMediaKeysQueue = this.setMediaKeysQueue.filter((p) => queue.indexOf(p) === -1);
    });
  }
  generateRequestWithPreferredKeySession(context, initDataType, initData, reason) {
    var _this$config$drmSyste, _this$config$drmSyste2;
    const generateRequestFilter = (_this$config$drmSyste = this.config.drmSystems) == null ? void 0 : (_this$config$drmSyste2 = _this$config$drmSyste[context.keySystem]) == null ? void 0 : _this$config$drmSyste2.generateRequest;
    if (generateRequestFilter) {
      try {
        const mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData, context);
        if (!mappedInitData) {
          throw new Error("Invalid response from configured generateRequest filter");
        }
        initDataType = mappedInitData.initDataType;
        initData = mappedInitData.initData ? mappedInitData.initData : null;
        context.decryptdata.pssh = initData ? new Uint8Array(initData) : null;
      } catch (error) {
        var _this$hls;
        this.warn(error.message);
        if ((_this$hls = this.hls) != null && _this$hls.config.debug) {
          throw error;
        }
      }
    }
    if (initData === null) {
      this.log(`Skipping key-session request for "${reason}" (no initData)`);
      return Promise.resolve(context);
    }
    const keyId = this.getKeyIdString(context.decryptdata);
    this.log(`Generating key-session request for "${reason}": ${keyId} (init data type: ${initDataType} length: ${initData ? initData.byteLength : null})`);
    const licenseStatus = new EventEmitter();
    const onmessage = context._onmessage = (event) => {
      const keySession = context.mediaKeysSession;
      if (!keySession) {
        licenseStatus.emit("error", new Error("invalid state"));
        return;
      }
      const {
        messageType,
        message
      } = event;
      this.log(`"${messageType}" message event for session "${keySession.sessionId}" message size: ${message.byteLength}`);
      if (messageType === "license-request" || messageType === "license-renewal") {
        this.renewLicense(context, message).catch((error) => {
          if (licenseStatus.eventNames().length) {
            licenseStatus.emit("error", error);
          } else {
            this.handleError(error);
          }
        });
      } else if (messageType === "license-release") {
        if (context.keySystem === KeySystems.FAIRPLAY) {
          this.updateKeySession(context, strToUtf8array("acknowledged"));
          this.removeSession(context);
        }
      } else {
        this.warn(`unhandled media key message type "${messageType}"`);
      }
    };
    const onkeystatuseschange = context._onkeystatuseschange = (event) => {
      const keySession = context.mediaKeysSession;
      if (!keySession) {
        licenseStatus.emit("error", new Error("invalid state"));
        return;
      }
      this.onKeyStatusChange(context);
      const keyStatus = context.keyStatus;
      licenseStatus.emit("keyStatus", keyStatus);
      if (keyStatus === "expired") {
        this.warn(`${context.keySystem} expired for key ${keyId}`);
        this.renewKeySession(context);
      }
    };
    context.mediaKeysSession.addEventListener("message", onmessage);
    context.mediaKeysSession.addEventListener("keystatuseschange", onkeystatuseschange);
    const keyUsablePromise = new Promise((resolve, reject) => {
      licenseStatus.on("error", reject);
      licenseStatus.on("keyStatus", (keyStatus) => {
        if (keyStatus.startsWith("usable")) {
          resolve();
        } else if (keyStatus === "output-restricted") {
          reject(new EMEKeyError({
            type: ErrorTypes.KEY_SYSTEM_ERROR,
            details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,
            fatal: false
          }, "HDCP level output restricted"));
        } else if (keyStatus === "internal-error") {
          reject(new EMEKeyError({
            type: ErrorTypes.KEY_SYSTEM_ERROR,
            details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,
            fatal: true
          }, `key status changed to "${keyStatus}"`));
        } else if (keyStatus === "expired") {
          reject(new Error("key expired while generating request"));
        } else {
          this.warn(`unhandled key status change "${keyStatus}"`);
        }
      });
    });
    return context.mediaKeysSession.generateRequest(initDataType, initData).then(() => {
      var _context$mediaKeysSes;
      this.log(`Request generated for key-session "${(_context$mediaKeysSes = context.mediaKeysSession) == null ? void 0 : _context$mediaKeysSes.sessionId}" keyId: ${keyId}`);
    }).catch((error) => {
      throw new EMEKeyError({
        type: ErrorTypes.KEY_SYSTEM_ERROR,
        details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
        error,
        fatal: false
      }, `Error generating key-session request: ${error}`);
    }).then(() => keyUsablePromise).catch((error) => {
      licenseStatus.removeAllListeners();
      this.removeSession(context);
      throw error;
    }).then(() => {
      licenseStatus.removeAllListeners();
      return context;
    });
  }
  onKeyStatusChange(mediaKeySessionContext) {
    mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach((status2, keyId) => {
      if (typeof keyId === "string" && typeof status2 === "object") {
        const temp = keyId;
        keyId = status2;
        status2 = temp;
      }
      this.log(`key status change "${status2}" for keyStatuses keyId: ${Hex.hexDump("buffer" in keyId ? new Uint8Array(keyId.buffer, keyId.byteOffset, keyId.byteLength) : new Uint8Array(keyId))} session keyId: ${Hex.hexDump(new Uint8Array(mediaKeySessionContext.decryptdata.keyId || []))} uri: ${mediaKeySessionContext.decryptdata.uri}`);
      mediaKeySessionContext.keyStatus = status2;
    });
  }
  fetchServerCertificate(keySystem) {
    const config = this.config;
    const Loader = config.loader;
    const certLoader = new Loader(config);
    const url = this.getServerCertificateUrl(keySystem);
    if (!url) {
      return Promise.resolve();
    }
    this.log(`Fetching server certificate for "${keySystem}"`);
    return new Promise((resolve, reject) => {
      const loaderContext = {
        responseType: "arraybuffer",
        url
      };
      const loadPolicy = config.certLoadPolicy.default;
      const loaderConfig = {
        loadPolicy,
        timeout: loadPolicy.maxLoadTimeMs,
        maxRetry: 0,
        retryDelay: 0,
        maxRetryDelay: 0
      };
      const loaderCallbacks = {
        onSuccess: (response, stats, context, networkDetails) => {
          resolve(response.data);
        },
        onError: (response, contex, networkDetails, stats) => {
          reject(new EMEKeyError({
            type: ErrorTypes.KEY_SYSTEM_ERROR,
            details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
            fatal: true,
            networkDetails,
            response: _objectSpread2({
              url: loaderContext.url,
              data: void 0
            }, response)
          }, `"${keySystem}" certificate request failed (${url}). Status: ${response.code} (${response.text})`));
        },
        onTimeout: (stats, context, networkDetails) => {
          reject(new EMEKeyError({
            type: ErrorTypes.KEY_SYSTEM_ERROR,
            details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
            fatal: true,
            networkDetails,
            response: {
              url: loaderContext.url,
              data: void 0
            }
          }, `"${keySystem}" certificate request timed out (${url})`));
        },
        onAbort: (stats, context, networkDetails) => {
          reject(new Error("aborted"));
        }
      };
      certLoader.load(loaderContext, loaderConfig, loaderCallbacks);
    });
  }
  setMediaKeysServerCertificate(mediaKeys, keySystem, cert) {
    return new Promise((resolve, reject) => {
      mediaKeys.setServerCertificate(cert).then((success) => {
        this.log(`setServerCertificate ${success ? "success" : "not supported by CDM"} (${cert == null ? void 0 : cert.byteLength}) on "${keySystem}"`);
        resolve(mediaKeys);
      }).catch((error) => {
        reject(new EMEKeyError({
          type: ErrorTypes.KEY_SYSTEM_ERROR,
          details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,
          error,
          fatal: true
        }, error.message));
      });
    });
  }
  renewLicense(context, keyMessage) {
    return this.requestLicense(context, new Uint8Array(keyMessage)).then((data) => {
      return this.updateKeySession(context, new Uint8Array(data)).catch((error) => {
        throw new EMEKeyError({
          type: ErrorTypes.KEY_SYSTEM_ERROR,
          details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,
          error,
          fatal: true
        }, error.message);
      });
    });
  }
  unpackPlayReadyKeyMessage(xhr, licenseChallenge) {
    const xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer));
    if (!xmlString.includes("PlayReadyKeyMessage")) {
      xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
      return licenseChallenge;
    }
    const keyMessageXml = new DOMParser().parseFromString(xmlString, "application/xml");
    const headers = keyMessageXml.querySelectorAll("HttpHeader");
    if (headers.length > 0) {
      let header;
      for (let i = 0, len = headers.length; i < len; i++) {
        var _header$querySelector, _header$querySelector2;
        header = headers[i];
        const name = (_header$querySelector = header.querySelector("name")) == null ? void 0 : _header$querySelector.textContent;
        const value = (_header$querySelector2 = header.querySelector("value")) == null ? void 0 : _header$querySelector2.textContent;
        if (name && value) {
          xhr.setRequestHeader(name, value);
        }
      }
    }
    const challengeElement = keyMessageXml.querySelector("Challenge");
    const challengeText = challengeElement == null ? void 0 : challengeElement.textContent;
    if (!challengeText) {
      throw new Error(`Cannot find <Challenge> in key message`);
    }
    return strToUtf8array(atob(challengeText));
  }
  setupLicenseXHR(xhr, url, keysListItem, licenseChallenge) {
    const licenseXhrSetup = this.config.licenseXhrSetup;
    if (!licenseXhrSetup) {
      xhr.open("POST", url, true);
      return Promise.resolve({
        xhr,
        licenseChallenge
      });
    }
    return Promise.resolve().then(() => {
      if (!keysListItem.decryptdata) {
        throw new Error("Key removed");
      }
      return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
    }).catch((error) => {
      if (!keysListItem.decryptdata) {
        throw error;
      }
      xhr.open("POST", url, true);
      return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
    }).then((licenseXhrSetupResult) => {
      if (!xhr.readyState) {
        xhr.open("POST", url, true);
      }
      const finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge;
      return {
        xhr,
        licenseChallenge: finalLicenseChallenge
      };
    });
  }
  requestLicense(keySessionContext, licenseChallenge) {
    const keyLoadPolicy = this.config.keyLoadPolicy.default;
    return new Promise((resolve, reject) => {
      const url = this.getLicenseServerUrlOrThrow(keySessionContext.keySystem);
      this.log(`Sending license request to URL: ${url}`);
      const xhr = new XMLHttpRequest();
      xhr.responseType = "arraybuffer";
      xhr.onreadystatechange = () => {
        if (!this.hls || !keySessionContext.mediaKeysSession) {
          return reject(new Error("invalid state"));
        }
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            this._requestLicenseFailureCount = 0;
            let data = xhr.response;
            this.log(`License received ${data instanceof ArrayBuffer ? data.byteLength : data}`);
            const licenseResponseCallback = this.config.licenseResponseCallback;
            if (licenseResponseCallback) {
              try {
                data = licenseResponseCallback.call(this.hls, xhr, url, keySessionContext);
              } catch (error) {
                this.error(error);
              }
            }
            resolve(data);
          } else {
            const retryConfig = keyLoadPolicy.errorRetry;
            const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;
            this._requestLicenseFailureCount++;
            if (this._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) {
              reject(new EMEKeyError({
                type: ErrorTypes.KEY_SYSTEM_ERROR,
                details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
                fatal: true,
                networkDetails: xhr,
                response: {
                  url,
                  data: void 0,
                  code: xhr.status,
                  text: xhr.statusText
                }
              }, `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`));
            } else {
              const attemptsLeft = maxNumRetry - this._requestLicenseFailureCount + 1;
              this.warn(`Retrying license request, ${attemptsLeft} attempts left`);
              this.requestLicense(keySessionContext, licenseChallenge).then(resolve, reject);
            }
          }
        }
      };
      if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) {
        keySessionContext.licenseXhr.abort();
      }
      keySessionContext.licenseXhr = xhr;
      this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(({
        xhr: xhr2,
        licenseChallenge: licenseChallenge2
      }) => {
        if (keySessionContext.keySystem == KeySystems.PLAYREADY) {
          licenseChallenge2 = this.unpackPlayReadyKeyMessage(xhr2, licenseChallenge2);
        }
        xhr2.send(licenseChallenge2);
      });
    });
  }
  onMediaAttached(event, data) {
    if (!this.config.emeEnabled) {
      return;
    }
    const media = data.media;
    this.media = media;
    media.removeEventListener("encrypted", this.onMediaEncrypted);
    media.removeEventListener("waitingforkey", this.onWaitingForKey);
    media.addEventListener("encrypted", this.onMediaEncrypted);
    media.addEventListener("waitingforkey", this.onWaitingForKey);
  }
  onMediaDetached() {
    const media = this.media;
    if (media) {
      media.removeEventListener("encrypted", this.onMediaEncrypted);
      media.removeEventListener("waitingforkey", this.onWaitingForKey);
      this.media = null;
    }
  }
  _clear(media) {
    var _media$setMediaKeys;
    const mediaKeysList = this.mediaKeySessions;
    this._requestLicenseFailureCount = 0;
    this.setMediaKeysQueue = [];
    this.mediaKeySessions = [];
    this.keyIdToKeySessionPromise = {};
    LevelKey.clearKeyUriToKeyIdMap();
    const keySessionCount = mediaKeysList.length;
    _EMEController.CDMCleanupPromise = Promise.all(mediaKeysList.map((mediaKeySessionContext) => this.removeSession(mediaKeySessionContext)).concat(media == null ? void 0 : (_media$setMediaKeys = media.setMediaKeys(null)) == null ? void 0 : _media$setMediaKeys.catch((error) => {
      var _this$hls2;
      this.log(`Could not clear media keys: ${error}`);
      (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.trigger(Events.ERROR, {
        type: ErrorTypes.OTHER_ERROR,
        details: ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,
        fatal: false,
        error: new Error(`Could not clear media keys: ${error}`)
      });
    }))).then(() => {
      if (keySessionCount) {
        this.log("finished closing key sessions and clearing media keys");
        mediaKeysList.length = 0;
      }
    }).catch((error) => {
      var _this$hls3;
      this.log(`Could not close sessions and clear media keys: ${error}`);
      (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.trigger(Events.ERROR, {
        type: ErrorTypes.OTHER_ERROR,
        details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
        fatal: false,
        error: new Error(`Could not close sessions and clear media keys: ${error}`)
      });
    });
  }
  onManifestLoading() {
    this.keyFormatPromise = null;
  }
  onManifestLoaded(event, {
    sessionKeys
  }) {
    if (!sessionKeys || !this.config.emeEnabled) {
      return;
    }
    if (!this.keyFormatPromise) {
      const keyFormats = sessionKeys.reduce((formats, sessionKey) => {
        if (formats.indexOf(sessionKey.keyFormat) === -1) {
          formats.push(sessionKey.keyFormat);
        }
        return formats;
      }, []);
      this.log(`Selecting key-system from session-keys ${keyFormats.join(", ")}`);
      this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
    }
  }
  removeSession(mediaKeySessionContext) {
    const {
      mediaKeysSession,
      licenseXhr
    } = mediaKeySessionContext;
    if (mediaKeysSession) {
      this.log(`Remove licenses and keys and close session ${mediaKeysSession.sessionId}`);
      if (mediaKeySessionContext._onmessage) {
        mediaKeysSession.removeEventListener("message", mediaKeySessionContext._onmessage);
        mediaKeySessionContext._onmessage = void 0;
      }
      if (mediaKeySessionContext._onkeystatuseschange) {
        mediaKeysSession.removeEventListener("keystatuseschange", mediaKeySessionContext._onkeystatuseschange);
        mediaKeySessionContext._onkeystatuseschange = void 0;
      }
      if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {
        licenseXhr.abort();
      }
      mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = void 0;
      const index = this.mediaKeySessions.indexOf(mediaKeySessionContext);
      if (index > -1) {
        this.mediaKeySessions.splice(index, 1);
      }
      const {
        drmSystemOptions
      } = this.config;
      const removePromise = isPersistentSessionType(drmSystemOptions) ? new Promise((resolve, reject) => {
        self.setTimeout(() => reject(new Error(`MediaKeySession.remove() timeout`)), 8e3);
        mediaKeysSession.remove().then(resolve);
      }) : Promise.resolve();
      return removePromise.catch((error) => {
        var _this$hls4;
        this.log(`Could not remove session: ${error}`);
        (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.trigger(Events.ERROR, {
          type: ErrorTypes.OTHER_ERROR,
          details: ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,
          fatal: false,
          error: new Error(`Could not remove session: ${error}`)
        });
      }).then(() => {
        return mediaKeysSession.close();
      }).catch((error) => {
        var _this$hls5;
        this.log(`Could not close session: ${error}`);
        (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.trigger(Events.ERROR, {
          type: ErrorTypes.OTHER_ERROR,
          details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
          fatal: false,
          error: new Error(`Could not close session: ${error}`)
        });
      });
    }
  }
};
EMEController.CDMCleanupPromise = void 0;
var EMEKeyError = class extends Error {
  constructor(data, message) {
    super(message);
    this.data = void 0;
    data.error || (data.error = new Error(message));
    this.data = data;
    data.err = data.error;
  }
};
var FPSController = class {
  constructor(hls) {
    this.hls = void 0;
    this.isVideoPlaybackQualityAvailable = false;
    this.timer = void 0;
    this.media = null;
    this.lastTime = void 0;
    this.lastDroppedFrames = 0;
    this.lastDecodedFrames = 0;
    this.streamController = void 0;
    this.hls = hls;
    this.registerListeners();
  }
  setStreamController(streamController) {
    this.streamController = streamController;
  }
  registerListeners() {
    this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  unregisterListeners() {
    this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  destroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    this.unregisterListeners();
    this.isVideoPlaybackQualityAvailable = false;
    this.media = null;
  }
  onMediaAttaching(event, data) {
    const config = this.hls.config;
    if (config.capLevelOnFPSDrop) {
      const media = data.media instanceof self.HTMLVideoElement ? data.media : null;
      this.media = media;
      if (media && typeof media.getVideoPlaybackQuality === "function") {
        this.isVideoPlaybackQualityAvailable = true;
      }
      self.clearInterval(this.timer);
      this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
    }
  }
  onMediaDetaching() {
    this.media = null;
  }
  checkFPS(video, decodedFrames, droppedFrames) {
    const currentTime = performance.now();
    if (decodedFrames) {
      if (this.lastTime) {
        const currentPeriod = currentTime - this.lastTime;
        const currentDropped = droppedFrames - this.lastDroppedFrames;
        const currentDecoded = decodedFrames - this.lastDecodedFrames;
        const droppedFPS = 1e3 * currentDropped / currentPeriod;
        const hls = this.hls;
        hls.trigger(Events.FPS_DROP, {
          currentDropped,
          currentDecoded,
          totalDroppedFrames: droppedFrames
        });
        if (droppedFPS > 0) {
          if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
            let currentLevel = hls.currentLevel;
            hls.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: " + currentLevel);
            if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
              currentLevel = currentLevel - 1;
              hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
                level: currentLevel,
                droppedLevel: hls.currentLevel
              });
              hls.autoLevelCapping = currentLevel;
              this.streamController.nextLevelSwitch();
            }
          }
        }
      }
      this.lastTime = currentTime;
      this.lastDroppedFrames = droppedFrames;
      this.lastDecodedFrames = decodedFrames;
    }
  }
  checkFPSInterval() {
    const video = this.media;
    if (video) {
      if (this.isVideoPlaybackQualityAvailable) {
        const videoPlaybackQuality = video.getVideoPlaybackQuality();
        this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
      } else {
        this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
      }
    }
  }
};
function sendAddTrackEvent(track, videoEl) {
  let event;
  try {
    event = new Event("addtrack");
  } catch (err) {
    event = document.createEvent("Event");
    event.initEvent("addtrack", false, false);
  }
  event.track = track;
  videoEl.dispatchEvent(event);
}
function addCueToTrack(track, cue) {
  const mode = track.mode;
  if (mode === "disabled") {
    track.mode = "hidden";
  }
  if (track.cues && !track.cues.getCueById(cue.id)) {
    try {
      track.addCue(cue);
      if (!track.cues.getCueById(cue.id)) {
        throw new Error(`addCue is failed for: ${cue}`);
      }
    } catch (err) {
      logger.debug(`[texttrack-utils]: ${err}`);
      try {
        const textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
        textTrackCue.id = cue.id;
        track.addCue(textTrackCue);
      } catch (err2) {
        logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`);
      }
    }
  }
  if (mode === "disabled") {
    track.mode = mode;
  }
}
function clearCurrentCues(track, enterHandler) {
  const mode = track.mode;
  if (mode === "disabled") {
    track.mode = "hidden";
  }
  if (track.cues) {
    for (let i = track.cues.length; i--; ) {
      if (enterHandler) {
        track.cues[i].removeEventListener("enter", enterHandler);
      }
      track.removeCue(track.cues[i]);
    }
  }
  if (mode === "disabled") {
    track.mode = mode;
  }
}
function removeCuesInRange(track, start2, end, predicate) {
  const mode = track.mode;
  if (mode === "disabled") {
    track.mode = "hidden";
  }
  if (track.cues && track.cues.length > 0) {
    const cues = getCuesInRange(track.cues, start2, end);
    for (let i = 0; i < cues.length; i++) {
      if (!predicate || predicate(cues[i])) {
        track.removeCue(cues[i]);
      }
    }
  }
  if (mode === "disabled") {
    track.mode = mode;
  }
}
function getFirstCueIndexFromTime(cues, time) {
  if (time <= cues[0].startTime) {
    return 0;
  }
  const len = cues.length - 1;
  if (time > cues[len].endTime) {
    return -1;
  }
  let left = 0;
  let right = len;
  let mid;
  while (left <= right) {
    mid = Math.floor((right + left) / 2);
    if (time < cues[mid].startTime) {
      right = mid - 1;
    } else if (time > cues[mid].startTime && left < len) {
      left = mid + 1;
    } else {
      return mid;
    }
  }
  return cues[left].startTime - time < time - cues[right].startTime ? left : right;
}
function getCuesInRange(cues, start2, end) {
  const cuesFound = [];
  const firstCueInRange = getFirstCueIndexFromTime(cues, start2);
  if (firstCueInRange > -1) {
    for (let i = firstCueInRange, len = cues.length; i < len; i++) {
      const cue = cues[i];
      if (cue.startTime >= start2 && cue.endTime <= end) {
        cuesFound.push(cue);
      } else if (cue.startTime > end) {
        return cuesFound;
      }
    }
  }
  return cuesFound;
}
function filterSubtitleTracks(textTrackList) {
  const tracks = [];
  for (let i = 0; i < textTrackList.length; i++) {
    const track = textTrackList[i];
    if ((track.kind === "subtitles" || track.kind === "captions") && track.label) {
      tracks.push(textTrackList[i]);
    }
  }
  return tracks;
}
var SubtitleTrackController = class extends BasePlaylistController {
  constructor(hls) {
    super(hls, "subtitle-track-controller");
    this.media = null;
    this.tracks = [];
    this.groupIds = null;
    this.tracksInGroup = [];
    this.trackId = -1;
    this.currentTrack = null;
    this.selectDefaultTrack = true;
    this.queuedDefaultTrack = -1;
    this.useTextTrackPolling = false;
    this.subtitlePollingInterval = -1;
    this._subtitleDisplay = true;
    this.asyncPollTrackChange = () => this.pollTrackChange(0);
    this.onTextTracksChanged = () => {
      if (!this.useTextTrackPolling) {
        self.clearInterval(this.subtitlePollingInterval);
      }
      if (!this.media || !this.hls.config.renderTextTracksNatively) {
        return;
      }
      let textTrack = null;
      const tracks = filterSubtitleTracks(this.media.textTracks);
      for (let i = 0; i < tracks.length; i++) {
        if (tracks[i].mode === "hidden") {
          textTrack = tracks[i];
        } else if (tracks[i].mode === "showing") {
          textTrack = tracks[i];
          break;
        }
      }
      const trackId = this.findTrackForTextTrack(textTrack);
      if (this.subtitleTrack !== trackId) {
        this.setSubtitleTrack(trackId);
      }
    };
    this.registerListeners();
  }
  destroy() {
    this.unregisterListeners();
    this.tracks.length = 0;
    this.tracksInGroup.length = 0;
    this.currentTrack = null;
    this.onTextTracksChanged = this.asyncPollTrackChange = null;
    super.destroy();
  }
  get subtitleDisplay() {
    return this._subtitleDisplay;
  }
  set subtitleDisplay(value) {
    this._subtitleDisplay = value;
    if (this.trackId > -1) {
      this.toggleTrackModes();
    }
  }
  registerListeners() {
    const {
      hls
    } = this;
    hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
    hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
    hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
    hls.on(Events.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls
    } = this;
    hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
    hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
    hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
    hls.off(Events.ERROR, this.onError, this);
  }
  // Listen for subtitle track change, then extract the current track ID.
  onMediaAttached(event, data) {
    this.media = data.media;
    if (!this.media) {
      return;
    }
    if (this.queuedDefaultTrack > -1) {
      this.subtitleTrack = this.queuedDefaultTrack;
      this.queuedDefaultTrack = -1;
    }
    this.useTextTrackPolling = !(this.media.textTracks && "onchange" in this.media.textTracks);
    if (this.useTextTrackPolling) {
      this.pollTrackChange(500);
    } else {
      this.media.textTracks.addEventListener("change", this.asyncPollTrackChange);
    }
  }
  pollTrackChange(timeout) {
    self.clearInterval(this.subtitlePollingInterval);
    this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout);
  }
  onMediaDetaching(event, data) {
    const media = this.media;
    if (!media) {
      return;
    }
    const transferringMedia = !!data.transferMedia;
    self.clearInterval(this.subtitlePollingInterval);
    if (!this.useTextTrackPolling) {
      media.textTracks.removeEventListener("change", this.asyncPollTrackChange);
    }
    if (this.trackId > -1) {
      this.queuedDefaultTrack = this.trackId;
    }
    this.subtitleTrack = -1;
    this.media = null;
    if (transferringMedia) {
      return;
    }
    const textTracks = filterSubtitleTracks(media.textTracks);
    textTracks.forEach((track) => {
      clearCurrentCues(track);
    });
  }
  onManifestLoading() {
    this.tracks = [];
    this.groupIds = null;
    this.tracksInGroup = [];
    this.trackId = -1;
    this.currentTrack = null;
    this.selectDefaultTrack = true;
  }
  // Fired whenever a new manifest is loaded.
  onManifestParsed(event, data) {
    this.tracks = data.subtitleTracks;
  }
  onSubtitleTrackLoaded(event, data) {
    const {
      id,
      groupId,
      details
    } = data;
    const trackInActiveGroup = this.tracksInGroup[id];
    if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
      this.warn(`Subtitle track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
      return;
    }
    const curDetails = trackInActiveGroup.details;
    trackInActiveGroup.details = data.details;
    this.log(`Subtitle track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
    if (id === this.trackId) {
      this.playlistLoaded(id, data, curDetails);
    }
  }
  onLevelLoading(event, data) {
    this.switchLevel(data.level);
  }
  onLevelSwitching(event, data) {
    this.switchLevel(data.level);
  }
  switchLevel(levelIndex) {
    const levelInfo = this.hls.levels[levelIndex];
    if (!levelInfo) {
      return;
    }
    const subtitleGroups = levelInfo.subtitleGroups || null;
    const currentGroups = this.groupIds;
    let currentTrack = this.currentTrack;
    if (!subtitleGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (subtitleGroups == null ? void 0 : subtitleGroups.length) || subtitleGroups != null && subtitleGroups.some((groupId) => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) {
      this.groupIds = subtitleGroups;
      this.trackId = -1;
      this.currentTrack = null;
      const subtitleTracks = this.tracks.filter((track) => !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1);
      if (subtitleTracks.length) {
        if (this.selectDefaultTrack && !subtitleTracks.some((track) => track.default)) {
          this.selectDefaultTrack = false;
        }
        subtitleTracks.forEach((track, i) => {
          track.id = i;
        });
      } else if (!currentTrack && !this.tracksInGroup.length) {
        return;
      }
      this.tracksInGroup = subtitleTracks;
      const subtitlePreference = this.hls.config.subtitlePreference;
      if (!currentTrack && subtitlePreference) {
        this.selectDefaultTrack = false;
        const groupIndex = findMatchingOption(subtitlePreference, subtitleTracks);
        if (groupIndex > -1) {
          currentTrack = subtitleTracks[groupIndex];
        } else {
          const allIndex = findMatchingOption(subtitlePreference, this.tracks);
          currentTrack = this.tracks[allIndex];
        }
      }
      let trackId = this.findTrackId(currentTrack);
      if (trackId === -1 && currentTrack) {
        trackId = this.findTrackId(null);
      }
      const subtitleTracksUpdated = {
        subtitleTracks
      };
      this.log(`Updating subtitle tracks, ${subtitleTracks.length} track(s) found in "${subtitleGroups == null ? void 0 : subtitleGroups.join(",")}" group-id`);
      this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
      if (trackId !== -1 && this.trackId === -1) {
        this.setSubtitleTrack(trackId);
      }
    }
  }
  findTrackId(currentTrack) {
    const tracks = this.tracksInGroup;
    const selectDefault = this.selectDefaultTrack;
    for (let i = 0; i < tracks.length; i++) {
      const track = tracks[i];
      if (selectDefault && !track.default || !selectDefault && !currentTrack) {
        continue;
      }
      if (!currentTrack || matchesOption(track, currentTrack)) {
        return i;
      }
    }
    if (currentTrack) {
      for (let i = 0; i < tracks.length; i++) {
        const track = tracks[i];
        if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
          return i;
        }
      }
      for (let i = 0; i < tracks.length; i++) {
        const track = tracks[i];
        if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) {
          return i;
        }
      }
    }
    return -1;
  }
  findTrackForTextTrack(textTrack) {
    if (textTrack) {
      const tracks = this.tracksInGroup;
      for (let i = 0; i < tracks.length; i++) {
        const track = tracks[i];
        if (subtitleTrackMatchesTextTrack(track, textTrack)) {
          return i;
        }
      }
    }
    return -1;
  }
  onError(event, data) {
    if (data.fatal || !data.context) {
      return;
    }
    if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
      this.checkRetry(data);
    }
  }
  get allSubtitleTracks() {
    return this.tracks;
  }
  /** get alternate subtitle tracks list from playlist **/
  get subtitleTracks() {
    return this.tracksInGroup;
  }
  /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
  get subtitleTrack() {
    return this.trackId;
  }
  set subtitleTrack(newId) {
    this.selectDefaultTrack = false;
    this.setSubtitleTrack(newId);
  }
  setSubtitleOption(subtitleOption) {
    this.hls.config.subtitlePreference = subtitleOption;
    if (subtitleOption) {
      if (subtitleOption.id === -1) {
        this.setSubtitleTrack(-1);
        return null;
      }
      const allSubtitleTracks = this.allSubtitleTracks;
      this.selectDefaultTrack = false;
      if (allSubtitleTracks.length) {
        const currentTrack = this.currentTrack;
        if (currentTrack && matchesOption(subtitleOption, currentTrack)) {
          return currentTrack;
        }
        const groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup);
        if (groupIndex > -1) {
          const track = this.tracksInGroup[groupIndex];
          this.setSubtitleTrack(groupIndex);
          return track;
        } else if (currentTrack) {
          return null;
        } else {
          const allIndex = findMatchingOption(subtitleOption, allSubtitleTracks);
          if (allIndex > -1) {
            return allSubtitleTracks[allIndex];
          }
        }
      }
    }
    return null;
  }
  loadPlaylist(hlsUrlParameters) {
    super.loadPlaylist();
    if (this.shouldLoadPlaylist(this.currentTrack)) {
      this.scheduleLoading(this.currentTrack, hlsUrlParameters);
    }
  }
  loadingPlaylist(currentTrack, hlsUrlParameters) {
    super.loadingPlaylist(currentTrack, hlsUrlParameters);
    const id = currentTrack.id;
    const groupId = currentTrack.groupId;
    const url = this.getUrlWithDirectives(currentTrack.url, hlsUrlParameters);
    const details = currentTrack.details;
    const age = details == null ? void 0 : details.age;
    this.log(`Loading subtitle ${id} "${currentTrack.name}" lang:${currentTrack.lang} group:${groupId}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== void 0 ? " at sn " + hlsUrlParameters.msn + " part " + hlsUrlParameters.part : ""}${age && details.live ? " age " + age.toFixed(1) + (details.type ? " " + details.type || "" : "") : ""} ${url}`);
    this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {
      url,
      id,
      groupId,
      deliveryDirectives: hlsUrlParameters || null,
      track: currentTrack
    });
  }
  /**
   * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
   * This operates on the DOM textTracks.
   * A value of -1 will disable all subtitle tracks.
   */
  toggleTrackModes() {
    const {
      media
    } = this;
    if (!media) {
      return;
    }
    const textTracks = filterSubtitleTracks(media.textTracks);
    const currentTrack = this.currentTrack;
    let nextTrack;
    if (currentTrack) {
      nextTrack = textTracks.filter((textTrack) => subtitleTrackMatchesTextTrack(currentTrack, textTrack))[0];
      if (!nextTrack) {
        this.warn(`Unable to find subtitle TextTrack with name "${currentTrack.name}" and language "${currentTrack.lang}"`);
      }
    }
    [].slice.call(textTracks).forEach((track) => {
      if (track.mode !== "disabled" && track !== nextTrack) {
        track.mode = "disabled";
      }
    });
    if (nextTrack) {
      const mode = this.subtitleDisplay ? "showing" : "hidden";
      if (nextTrack.mode !== mode) {
        nextTrack.mode = mode;
      }
    }
  }
  /**
   * This method is responsible for validating the subtitle index and periodically reloading if live.
   * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
   */
  setSubtitleTrack(newId) {
    const tracks = this.tracksInGroup;
    if (!this.media) {
      this.queuedDefaultTrack = newId;
      return;
    }
    if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) {
      this.warn(`Invalid subtitle track id: ${newId}`);
      return;
    }
    this.selectDefaultTrack = false;
    const lastTrack = this.currentTrack;
    const track = tracks[newId] || null;
    this.trackId = newId;
    this.currentTrack = track;
    this.toggleTrackModes();
    if (!track) {
      this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
        id: newId
      });
      return;
    }
    const trackLoaded = !!track.details && !track.details.live;
    if (newId === this.trackId && track === lastTrack && trackLoaded) {
      return;
    }
    this.log(`Switching to subtitle-track ${newId}` + (track ? ` "${track.name}" lang:${track.lang} group:${track.groupId}` : ""));
    const {
      id,
      groupId = "",
      name,
      type: type2,
      url
    } = track;
    this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
      id,
      groupId,
      name,
      type: type2,
      url
    });
    const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
    this.loadPlaylist(hlsUrlParameters);
  }
};
function hash(text) {
  let hash2 = 5381;
  let i = text.length;
  while (i) {
    hash2 = hash2 * 33 ^ text.charCodeAt(--i);
  }
  return (hash2 >>> 0).toString();
}
var ALIGNED_END_THRESHOLD_SECONDS = 0.025;
var TimelineOccupancy = /* @__PURE__ */ function(TimelineOccupancy2) {
  TimelineOccupancy2[TimelineOccupancy2["Point"] = 0] = "Point";
  TimelineOccupancy2[TimelineOccupancy2["Range"] = 1] = "Range";
  return TimelineOccupancy2;
}({});
function generateAssetIdentifier(interstitial, uri, assetListIndex) {
  return `${interstitial.identifier}-${assetListIndex + 1}-${hash(uri)}`;
}
var InterstitialEvent = class {
  constructor(dateRange, base) {
    this.base = void 0;
    this._duration = null;
    this._timelineStart = null;
    this.appendInPlaceDisabled = void 0;
    this.appendInPlaceStarted = void 0;
    this.dateRange = void 0;
    this.hasPlayed = false;
    this.cumulativeDuration = 0;
    this.resumeOffset = NaN;
    this.playoutLimit = NaN;
    this.restrictions = {
      skip: false,
      jump: false
    };
    this.snapOptions = {
      out: false,
      in: false
    };
    this.assetList = [];
    this.assetListLoader = void 0;
    this.assetListResponse = null;
    this.resumeAnchor = void 0;
    this.error = void 0;
    this.resetOnResume = void 0;
    this.base = base;
    this.dateRange = dateRange;
    this.setDateRange(dateRange);
  }
  setDateRange(dateRange) {
    this.dateRange = dateRange;
    this.resumeOffset = dateRange.attr.optionalFloat("X-RESUME-OFFSET", this.resumeOffset);
    this.playoutLimit = dateRange.attr.optionalFloat("X-PLAYOUT-LIMIT", this.playoutLimit);
    this.restrictions = dateRange.attr.enumeratedStringList("X-RESTRICT", this.restrictions);
    this.snapOptions = dateRange.attr.enumeratedStringList("X-SNAP", this.snapOptions);
  }
  reset() {
    var _this$assetListLoader;
    this.appendInPlaceStarted = false;
    (_this$assetListLoader = this.assetListLoader) == null ? void 0 : _this$assetListLoader.destroy();
    this.assetListLoader = void 0;
    if (!this.supplementsPrimary) {
      this.assetListResponse = null;
      this.assetList = [];
      this._duration = null;
    }
  }
  isAssetPastPlayoutLimit(assetIndex) {
    if (assetIndex >= this.assetList.length) {
      return true;
    }
    const playoutLimit = this.playoutLimit;
    if (assetIndex <= 0 || isNaN(playoutLimit)) {
      return false;
    }
    const assetOffset = this.assetList[assetIndex].startOffset;
    return assetOffset > playoutLimit;
  }
  findAssetIndex(asset) {
    const index = this.assetList.indexOf(asset);
    return index;
  }
  get identifier() {
    return this.dateRange.id;
  }
  get startDate() {
    return this.dateRange.startDate;
  }
  get startTime() {
    const startTime = this.dateRange.startTime;
    if (this.snapOptions.out) {
      const frag = this.dateRange.tagAnchor;
      if (frag) {
        return getSnapToFragmentTime(startTime, frag);
      }
    }
    return startTime;
  }
  get startOffset() {
    return this.cue.pre ? 0 : this.startTime;
  }
  get startIsAligned() {
    if (this.startTime === 0 || this.snapOptions.out) {
      return true;
    }
    const frag = this.dateRange.tagAnchor;
    if (frag) {
      const startTime = this.dateRange.startTime;
      const snappedStart = getSnapToFragmentTime(startTime, frag);
      return startTime - snappedStart < 0.1;
    }
    return false;
  }
  get resumptionOffset() {
    const resumeOffset = this.resumeOffset;
    const offset = isFiniteNumber(resumeOffset) ? resumeOffset : this.duration;
    return this.cumulativeDuration + offset;
  }
  get resumeTime() {
    const resumeTime = this.startOffset + this.resumptionOffset;
    if (this.snapOptions.in) {
      const frag = this.resumeAnchor;
      if (frag) {
        return getSnapToFragmentTime(resumeTime, frag);
      }
    }
    return resumeTime;
  }
  get appendInPlace() {
    if (this.appendInPlaceStarted) {
      return true;
    }
    if (this.appendInPlaceDisabled) {
      return false;
    }
    if (!this.cue.once && !this.cue.pre && // preroll starts at startPosition before startPosition is known (live)
    this.startIsAligned && (isNaN(this.playoutLimit) && isNaN(this.resumeOffset) || this.resumeOffset && this.duration && Math.abs(this.resumeOffset - this.duration) < ALIGNED_END_THRESHOLD_SECONDS)) {
      return true;
    }
    return false;
  }
  set appendInPlace(value) {
    if (this.appendInPlaceStarted) {
      this.resetOnResume = !value;
      return;
    }
    this.appendInPlaceDisabled = !value;
  }
  // Extended timeline start time
  get timelineStart() {
    if (this._timelineStart !== null) {
      return this._timelineStart;
    }
    return this.startTime;
  }
  set timelineStart(value) {
    this._timelineStart = value;
  }
  get duration() {
    const playoutLimit = this.playoutLimit;
    let duration5;
    if (this._duration !== null) {
      duration5 = this._duration;
    } else if (this.dateRange.duration) {
      duration5 = this.dateRange.duration;
    } else {
      duration5 = this.dateRange.plannedDuration || 0;
    }
    if (!isNaN(playoutLimit) && playoutLimit < duration5) {
      duration5 = playoutLimit;
    }
    return duration5;
  }
  set duration(value) {
    this._duration = value;
  }
  get cue() {
    return this.dateRange.cue;
  }
  get timelineOccupancy() {
    if (this.dateRange.attr["X-TIMELINE-OCCUPIES"] === "RANGE") {
      return TimelineOccupancy.Range;
    }
    return TimelineOccupancy.Point;
  }
  get supplementsPrimary() {
    return this.dateRange.attr["X-TIMELINE-STYLE"] === "PRIMARY";
  }
  get contentMayVary() {
    return this.dateRange.attr["X-CONTENT-MAY-VARY"] !== "NO";
  }
  get assetUrl() {
    return this.dateRange.attr["X-ASSET-URI"];
  }
  get assetListUrl() {
    return this.dateRange.attr["X-ASSET-LIST"];
  }
  get baseUrl() {
    return this.base.url;
  }
  get assetListLoaded() {
    return this.assetList.length > 0 || this.assetListResponse !== null;
  }
  toString() {
    return eventToString(this);
  }
};
function getSnapToFragmentTime(time, frag) {
  return time - frag.start < frag.duration / 2 && !(Math.abs(time - (frag.start + frag.duration)) < ALIGNED_END_THRESHOLD_SECONDS) ? frag.start : frag.start + frag.duration;
}
function getInterstitialUrl(uri, sessionId, baseUrl) {
  const url = new self.URL(uri, baseUrl);
  if (url.protocol !== "data:") {
    url.searchParams.set("_HLS_primary_id", sessionId);
  }
  return url;
}
function eventToString(interstitial) {
  return `["${interstitial.identifier}" ${interstitial.cue.pre ? "<pre>" : interstitial.cue.post ? "<post>" : ""}${interstitial.timelineStart.toFixed(2)}-${interstitial.resumeTime.toFixed(2)}]`;
}
function eventAssetToString(asset) {
  const start2 = asset.timelineStart;
  const duration5 = asset.duration || 0;
  return `["${asset.identifier}" ${start2.toFixed(2)}-${(start2 + duration5).toFixed(2)}]`;
}
var HlsAssetPlayer = class {
  constructor(HlsPlayerClass, userConfig, _interstitial, assetItem) {
    this.hls = void 0;
    this.interstitial = void 0;
    this.assetItem = void 0;
    this.tracks = null;
    this.hasDetails = false;
    this.mediaAttached = null;
    this._currentTime = void 0;
    this._bufferedEosTime = void 0;
    this.checkPlayout = () => {
      const interstitial = this.interstitial;
      const playoutLimit = interstitial.playoutLimit;
      const currentTime = this.currentTime;
      if (this.startOffset + currentTime >= playoutLimit) {
        this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED, {});
      }
    };
    const hls = this.hls = new HlsPlayerClass(userConfig);
    this.interstitial = _interstitial;
    this.assetItem = assetItem;
    let uri = assetItem.uri;
    try {
      uri = getInterstitialUrl(uri, hls.sessionId).href;
    } catch (error) {
    }
    hls.loadSource(uri);
    const detailsLoaded = () => {
      this.hasDetails = true;
    };
    hls.once(Events.LEVEL_LOADED, detailsLoaded);
    hls.once(Events.AUDIO_TRACK_LOADED, detailsLoaded);
    hls.once(Events.SUBTITLE_TRACK_LOADED, detailsLoaded);
    hls.on(Events.MEDIA_ATTACHING, (name, {
      media
    }) => {
      this.removeMediaListeners();
      this.mediaAttached = media;
      const event = this.interstitial;
      if (event.playoutLimit) {
        media.addEventListener("timeupdate", this.checkPlayout);
      }
    });
  }
  bufferedInPlaceToEnd(media) {
    var _this$hls;
    if (!this.interstitial.appendInPlace) {
      return false;
    }
    if ((_this$hls = this.hls) != null && _this$hls.bufferedToEnd) {
      return true;
    }
    if (!media || !this._bufferedEosTime) {
      return false;
    }
    const start2 = this.timelineOffset;
    const bufferInfo = BufferHelper.bufferInfo(media, start2, 0);
    const bufferedEnd = this.getAssetTime(bufferInfo.end);
    return bufferedEnd >= this._bufferedEosTime - 0.02;
  }
  get destroyed() {
    var _this$hls2;
    return !((_this$hls2 = this.hls) != null && _this$hls2.userConfig);
  }
  get assetId() {
    return this.assetItem.identifier;
  }
  get interstitialId() {
    return this.assetItem.parentIdentifier;
  }
  get media() {
    var _this$hls3;
    return ((_this$hls3 = this.hls) == null ? void 0 : _this$hls3.media) || null;
  }
  get bufferedEnd() {
    const media = this.media || this.mediaAttached;
    if (!media) {
      if (this._bufferedEosTime) {
        return this._bufferedEosTime;
      }
      return this.currentTime;
    }
    const bufferInfo = BufferHelper.bufferInfo(media, media.currentTime, 1e-3);
    return this.getAssetTime(bufferInfo.end);
  }
  get currentTime() {
    const media = this.media || this.mediaAttached;
    if (!media) {
      return this._currentTime || 0;
    }
    return this.getAssetTime(media.currentTime);
  }
  get duration() {
    const duration5 = this.assetItem.duration;
    if (!duration5) {
      return 0;
    }
    return duration5;
  }
  get remaining() {
    const duration5 = this.duration;
    if (!duration5) {
      return 0;
    }
    return Math.max(0, duration5 - this.currentTime);
  }
  get startOffset() {
    return this.assetItem.startOffset;
  }
  get timelineOffset() {
    var _this$hls4;
    return ((_this$hls4 = this.hls) == null ? void 0 : _this$hls4.config.timelineOffset) || 0;
  }
  set timelineOffset(value) {
    const timelineOffset = this.timelineOffset;
    if (value !== timelineOffset) {
      const diff = value - timelineOffset;
      if (Math.abs(diff) > 1 / 9e4) {
        if (this.hasDetails) {
          throw new Error(`Cannot set timelineOffset after playlists are loaded`);
        }
        this.hls.config.timelineOffset = value;
      }
    }
  }
  getAssetTime(time) {
    const timelineOffset = this.timelineOffset;
    const duration5 = this.duration;
    return Math.min(Math.max(0, time - timelineOffset), duration5);
  }
  removeMediaListeners() {
    const media = this.mediaAttached;
    if (media) {
      this._currentTime = media.currentTime;
      this.bufferSnapShot();
      media.removeEventListener("timeupdate", this.checkPlayout);
    }
  }
  bufferSnapShot() {
    if (this.mediaAttached) {
      var _this$hls5;
      if ((_this$hls5 = this.hls) != null && _this$hls5.bufferedToEnd) {
        this._bufferedEosTime = this.bufferedEnd;
      }
    }
  }
  destroy() {
    this.removeMediaListeners();
    this.hls.destroy();
    this.hls = this.interstitial = null;
    this.tracks = this.mediaAttached = this.checkPlayout = null;
  }
  attachMedia(data) {
    this.hls.attachMedia(data);
  }
  detachMedia() {
    this.removeMediaListeners();
    this.mediaAttached = null;
    this.hls.detachMedia();
  }
  resumeBuffering() {
    this.hls.resumeBuffering();
  }
  pauseBuffering() {
    this.hls.pauseBuffering();
  }
  transferMedia() {
    this.bufferSnapShot();
    return this.hls.transferMedia();
  }
  on(event, listener, context) {
    this.hls.on(event, listener);
  }
  once(event, listener, context) {
    this.hls.once(event, listener);
  }
  off(event, listener, context) {
    this.hls.off(event, listener);
  }
  toString() {
    var _this$hls6, _this$interstitial;
    return `HlsAssetPlayer: ${eventAssetToString(this.assetItem)} ${(_this$hls6 = this.hls) == null ? void 0 : _this$hls6.sessionId} ${(_this$interstitial = this.interstitial) != null && _this$interstitial.appendInPlace ? "append-in-place" : ""}`;
  }
};
var ABUTTING_THRESHOLD_SECONDS = 0.033;
var InterstitialsSchedule = class extends Logger {
  constructor(onScheduleUpdate, logger4) {
    super("interstitials-sched", logger4);
    this.onScheduleUpdate = void 0;
    this.eventMap = {};
    this.events = null;
    this.items = null;
    this.durations = {
      primary: 0,
      playout: 0,
      integrated: 0
    };
    this.onScheduleUpdate = onScheduleUpdate;
  }
  destroy() {
    this.reset();
    this.onScheduleUpdate = null;
  }
  reset() {
    this.eventMap = {};
    this.setDurations(0, 0, 0);
    if (this.events) {
      this.events.forEach((interstitial) => interstitial.reset());
    }
    this.events = this.items = null;
  }
  resetErrorsInRange(start2, end) {
    if (this.events) {
      return this.events.reduce((count, interstitial) => {
        if (start2 <= interstitial.startOffset && end > interstitial.startOffset) {
          delete interstitial.error;
          return count + 1;
        }
        return count;
      }, 0);
    }
    return 0;
  }
  get duration() {
    const items = this.items;
    return items ? items[items.length - 1].end : 0;
  }
  get length() {
    return this.items ? this.items.length : 0;
  }
  getEvent(identifier) {
    return identifier ? this.eventMap[identifier] || null : null;
  }
  hasEvent(identifier) {
    return identifier in this.eventMap;
  }
  findItemIndex(item, time) {
    if (item.event) {
      return this.findEventIndex(item.event.identifier);
    }
    let index = -1;
    if (item.nextEvent) {
      index = this.findEventIndex(item.nextEvent.identifier) - 1;
    } else if (item.previousEvent) {
      index = this.findEventIndex(item.previousEvent.identifier) + 1;
    }
    const items = this.items;
    if (items) {
      if (!items[index]) {
        if (time === void 0) {
          time = item.start;
        }
        index = this.findItemIndexAtTime(time);
      }
      while (index >= 0 && (_items$index = items[index]) != null && _items$index.event) {
        var _items$index;
        index--;
      }
    }
    return index;
  }
  findItemIndexAtTime(timelinePos, timelineType) {
    const items = this.items;
    if (items) {
      for (let i = 0; i < items.length; i++) {
        let timeRange = items[i];
        if (timelineType && timelineType !== "primary") {
          timeRange = timeRange[timelineType];
        }
        if (timelinePos === timeRange.start || timelinePos > timeRange.start && timelinePos < timeRange.end) {
          return i;
        }
      }
    }
    return -1;
  }
  findJumpRestrictedIndex(startIndex, endIndex) {
    const items = this.items;
    if (items) {
      for (let i = startIndex; i <= endIndex; i++) {
        if (!items[i]) {
          break;
        }
        const event = items[i].event;
        if (event != null && event.restrictions.jump && !event.appendInPlace) {
          return i;
        }
      }
    }
    return -1;
  }
  findEventIndex(identifier) {
    const items = this.items;
    if (items) {
      for (let i = items.length; i--; ) {
        var _items$i$event;
        if (((_items$i$event = items[i].event) == null ? void 0 : _items$i$event.identifier) === identifier) {
          return i;
        }
      }
    }
    return -1;
  }
  findAssetIndex(event, timelinePos) {
    const assetList = event.assetList;
    const length = assetList.length;
    if (length > 1) {
      for (let i = 0; i < length; i++) {
        const asset = assetList[i];
        if (!asset.error) {
          const timelineStart = asset.timelineStart;
          if (timelinePos === timelineStart || timelinePos > timelineStart && timelinePos < timelineStart + (asset.duration || 0)) {
            return i;
          }
        }
      }
    }
    return 0;
  }
  get assetIdAtEnd() {
    var _this$items, _this$items2;
    const interstitialAtEnd = (_this$items = this.items) == null ? void 0 : (_this$items2 = _this$items[this.length - 1]) == null ? void 0 : _this$items2.event;
    if (interstitialAtEnd) {
      const assetList = interstitialAtEnd.assetList;
      const assetAtEnd = assetList[assetList.length - 1];
      if (assetAtEnd) {
        return assetAtEnd.identifier;
      }
    }
    return null;
  }
  parseInterstitialDateRanges(mediaSelection, enableAppendInPlace) {
    const details = mediaSelection.main.details;
    const {
      dateRanges
    } = details;
    const previousInterstitialEvents = this.events;
    const interstitialEvents = this.parseDateRanges(dateRanges, {
      url: details.url
    }, enableAppendInPlace);
    const ids = Object.keys(dateRanges);
    const removedInterstitials = previousInterstitialEvents ? previousInterstitialEvents.filter((event) => !ids.includes(event.identifier)) : [];
    if (interstitialEvents.length) {
      interstitialEvents.sort((a, b) => {
        const aPre = a.cue.pre;
        const aPost = a.cue.post;
        const bPre = b.cue.pre;
        const bPost = b.cue.post;
        if (aPre && !bPre) {
          return -1;
        }
        if (bPre && !aPre) {
          return 1;
        }
        if (aPost && !bPost) {
          return 1;
        }
        if (bPost && !aPost) {
          return -1;
        }
        if (!aPre && !bPre && !aPost && !bPost) {
          const startA = a.startTime;
          const startB = b.startTime;
          if (startA !== startB) {
            return startA - startB;
          }
        }
        return a.dateRange.tagOrder - b.dateRange.tagOrder;
      });
    }
    this.events = interstitialEvents;
    removedInterstitials.forEach((interstitial) => {
      this.removeEvent(interstitial);
    });
    this.updateSchedule(mediaSelection, removedInterstitials);
  }
  updateSchedule(mediaSelection, removedInterstitials = []) {
    const events = this.events || [];
    if (events.length || removedInterstitials.length || this.length < 2) {
      const currentItems = this.items;
      const updatedItems = this.parseSchedule(events, mediaSelection);
      const updated = removedInterstitials.length || (currentItems == null ? void 0 : currentItems.length) !== updatedItems.length || updatedItems.some((item, i) => {
        return Math.abs(item.playout.start - currentItems[i].playout.start) > 5e-3 || Math.abs(item.playout.end - currentItems[i].playout.end) > 5e-3;
      });
      if (updated) {
        this.items = updatedItems;
        this.onScheduleUpdate(removedInterstitials, currentItems);
      }
    }
  }
  parseDateRanges(dateRanges, baseData, enableAppendInPlace) {
    const interstitialEvents = [];
    const ids = Object.keys(dateRanges);
    for (let i = 0; i < ids.length; i++) {
      const id = ids[i];
      const dateRange = dateRanges[id];
      if (dateRange.isInterstitial) {
        let interstitial = this.eventMap[id];
        if (interstitial) {
          interstitial.setDateRange(dateRange);
        } else {
          interstitial = new InterstitialEvent(dateRange, baseData);
          this.eventMap[id] = interstitial;
          if (enableAppendInPlace === false) {
            interstitial.appendInPlace = enableAppendInPlace;
          }
        }
        interstitialEvents.push(interstitial);
      }
    }
    return interstitialEvents;
  }
  parseSchedule(interstitialEvents, mediaSelection) {
    const schedule = [];
    const details = mediaSelection.main.details;
    const primaryDuration = details.live ? Infinity : details.edge;
    let playoutDuration = 0;
    interstitialEvents = interstitialEvents.filter((event) => !event.error && !(event.cue.once && event.hasPlayed));
    if (interstitialEvents.length) {
      this.resolveOffsets(interstitialEvents, mediaSelection);
      let primaryPosition = 0;
      let integratedTime = 0;
      interstitialEvents.forEach((interstitial, i) => {
        const preroll = interstitial.cue.pre;
        const postroll = interstitial.cue.post;
        const previousEvent = interstitialEvents[i - 1] || null;
        const appendInPlace = interstitial.appendInPlace;
        const eventStart = postroll ? primaryDuration : interstitial.startOffset;
        const interstitialDuration = interstitial.duration;
        const timelineDuration = interstitial.timelineOccupancy === TimelineOccupancy.Range ? interstitialDuration : 0;
        const resumptionOffset = interstitial.resumptionOffset;
        const inSameStartTimeSequence = (previousEvent == null ? void 0 : previousEvent.startTime) === eventStart;
        const start2 = eventStart + interstitial.cumulativeDuration;
        let end = appendInPlace ? start2 + interstitialDuration : eventStart + resumptionOffset;
        if (preroll || !postroll && eventStart <= 0) {
          const integratedStart = integratedTime;
          integratedTime += timelineDuration;
          interstitial.timelineStart = start2;
          const playoutStart = playoutDuration;
          playoutDuration += interstitialDuration;
          schedule.push({
            event: interstitial,
            start: start2,
            end,
            playout: {
              start: playoutStart,
              end: playoutDuration
            },
            integrated: {
              start: integratedStart,
              end: integratedTime
            }
          });
        } else if (eventStart <= primaryDuration) {
          if (!inSameStartTimeSequence) {
            const segmentDuration = eventStart - primaryPosition;
            if (segmentDuration > ABUTTING_THRESHOLD_SECONDS) {
              const timelineStart = primaryPosition;
              const _integratedStart = integratedTime;
              integratedTime += segmentDuration;
              const _playoutStart = playoutDuration;
              playoutDuration += segmentDuration;
              const primarySegment = {
                previousEvent: interstitialEvents[i - 1] || null,
                nextEvent: interstitial,
                start: timelineStart,
                end: timelineStart + segmentDuration,
                playout: {
                  start: _playoutStart,
                  end: playoutDuration
                },
                integrated: {
                  start: _integratedStart,
                  end: integratedTime
                }
              };
              schedule.push(primarySegment);
            } else if (segmentDuration > 0 && previousEvent) {
              previousEvent.cumulativeDuration += segmentDuration;
              schedule[schedule.length - 1].end = eventStart;
            }
          }
          if (postroll) {
            end = start2;
          }
          interstitial.timelineStart = start2;
          const integratedStart = integratedTime;
          integratedTime += timelineDuration;
          const playoutStart = playoutDuration;
          playoutDuration += interstitialDuration;
          schedule.push({
            event: interstitial,
            start: start2,
            end,
            playout: {
              start: playoutStart,
              end: playoutDuration
            },
            integrated: {
              start: integratedStart,
              end: integratedTime
            }
          });
        } else {
          return;
        }
        const resumeTime = interstitial.resumeTime;
        if (postroll || resumeTime > primaryDuration) {
          primaryPosition = primaryDuration;
        } else {
          primaryPosition = resumeTime;
        }
      });
      if (primaryPosition < primaryDuration) {
        var _schedule;
        const timelineStart = primaryPosition;
        const integratedStart = integratedTime;
        const segmentDuration = primaryDuration - primaryPosition;
        integratedTime += segmentDuration;
        const playoutStart = playoutDuration;
        playoutDuration += segmentDuration;
        schedule.push({
          previousEvent: ((_schedule = schedule[schedule.length - 1]) == null ? void 0 : _schedule.event) || null,
          nextEvent: null,
          start: primaryPosition,
          end: timelineStart + segmentDuration,
          playout: {
            start: playoutStart,
            end: playoutDuration
          },
          integrated: {
            start: integratedStart,
            end: integratedTime
          }
        });
      }
      this.setDurations(primaryDuration, playoutDuration, integratedTime);
    } else {
      const start2 = 0;
      schedule.push({
        previousEvent: null,
        nextEvent: null,
        start: start2,
        end: primaryDuration,
        playout: {
          start: start2,
          end: primaryDuration
        },
        integrated: {
          start: start2,
          end: primaryDuration
        }
      });
      this.setDurations(primaryDuration, primaryDuration, primaryDuration);
    }
    return schedule;
  }
  setDurations(primary, playout, integrated) {
    this.durations = {
      primary,
      playout,
      integrated
    };
  }
  resolveOffsets(interstitialEvents, mediaSelection) {
    const details = mediaSelection.main.details;
    const primaryDuration = details.live ? Infinity : details.edge;
    let cumulativeDuration = 0;
    let lastScheduledStart = -1;
    interstitialEvents.forEach((interstitial, i) => {
      const preroll = interstitial.cue.pre;
      const postroll = interstitial.cue.post;
      const eventStart = preroll ? 0 : postroll ? primaryDuration : interstitial.startTime;
      this.updateAssetDurations(interstitial);
      const inSameStartTimeSequence = lastScheduledStart === eventStart;
      if (inSameStartTimeSequence) {
        interstitial.cumulativeDuration = cumulativeDuration;
      } else {
        cumulativeDuration = 0;
        lastScheduledStart = eventStart;
      }
      if (!postroll && interstitial.snapOptions.in) {
        interstitial.resumeAnchor = findFragmentByPTS(null, details.fragments, interstitial.startOffset + interstitial.resumptionOffset, 0, 0) || void 0;
      }
      if (interstitial.appendInPlace && !interstitial.appendInPlaceStarted) {
        const alignedSegmentStart = this.primaryCanResumeInPlaceAt(interstitial, mediaSelection);
        if (!alignedSegmentStart) {
          interstitial.appendInPlace = false;
        }
      }
      if (!interstitial.appendInPlace && i + 1 < interstitialEvents.length) {
        const timeBetween = interstitialEvents[i + 1].startTime - interstitialEvents[i].resumeTime;
        if (timeBetween < ABUTTING_THRESHOLD_SECONDS) {
          interstitialEvents[i + 1].appendInPlace = false;
          if (interstitialEvents[i + 1].appendInPlace) {
            this.warn(`Could not change append strategy for abutting event ${interstitial}`);
          }
        }
      }
      const resumeOffset = isFiniteNumber(interstitial.resumeOffset) ? interstitial.resumeOffset : interstitial.duration;
      cumulativeDuration += resumeOffset;
    });
  }
  primaryCanResumeInPlaceAt(interstitial, mediaSelection) {
    const resumeTime = interstitial.resumeTime;
    const resumesInPlaceAt = interstitial.startTime + interstitial.resumptionOffset;
    if (Math.abs(resumeTime - resumesInPlaceAt) > ALIGNED_END_THRESHOLD_SECONDS) {
      this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with estimated timeline end ${resumesInPlaceAt}`);
      return false;
    }
    if (!mediaSelection) {
      this.log(`"${interstitial.identifier}" resumption ${resumeTime} can not be aligned with media (none selected)`);
      return false;
    }
    const playlists = Object.keys(mediaSelection);
    return !playlists.some((playlistType) => {
      const details = mediaSelection[playlistType].details;
      const playlistEnd3 = details.edge;
      if (resumeTime >= playlistEnd3) {
        this.log(`"${interstitial.identifier}" resumption ${resumeTime} past ${playlistType} playlist end ${playlistEnd3}`);
        return false;
      }
      const startFragment = findFragmentByPTS(null, details.fragments, resumeTime);
      if (!startFragment) {
        this.log(`"${interstitial.identifier}" resumption ${resumeTime} does not align with any fragments in ${playlistType} playlist (${details.fragStart}-${details.fragmentEnd})`);
        return true;
      }
      const allowance = playlistType === "audio" ? 0.175 : 0;
      const alignedWithSegment = Math.abs(startFragment.start - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance || Math.abs(startFragment.end - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance;
      if (!alignedWithSegment) {
        this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with ${playlistType} fragment bounds (${startFragment.start}-${startFragment.end} sn: ${startFragment.sn} cc: ${startFragment.cc})`);
        return true;
      }
      return false;
    });
  }
  updateAssetDurations(interstitial) {
    if (!interstitial.assetListLoaded) {
      return;
    }
    const eventStart = interstitial.timelineStart;
    let sumDuration = 0;
    let hasUnknownDuration = false;
    let hasErrors = false;
    interstitial.assetList.forEach((asset, i) => {
      const timelineStart = eventStart + sumDuration;
      asset.startOffset = sumDuration;
      asset.timelineStart = timelineStart;
      hasUnknownDuration || (hasUnknownDuration = asset.duration === null);
      hasErrors || (hasErrors = !!asset.error);
      const duration5 = asset.error ? 0 : asset.duration || 0;
      sumDuration += duration5;
    });
    if (hasUnknownDuration && !hasErrors) {
      interstitial.duration = Math.max(sumDuration, interstitial.duration);
    } else {
      interstitial.duration = sumDuration;
    }
  }
  removeEvent(interstitial) {
    interstitial.reset();
    delete this.eventMap[interstitial.identifier];
  }
};
function segmentToString(segment) {
  return `[${segment.event ? '"' + segment.event.identifier + '"' : "primary"}: ${segment.start.toFixed(2)}-${segment.end.toFixed(2)}]`;
}
var AssetListLoader = class {
  constructor(hls) {
    this.hls = void 0;
    this.hls = hls;
  }
  destroy() {
    this.hls = null;
  }
  loadAssetList(interstitial, hlsStartOffset) {
    const assetListUrl = interstitial.assetListUrl;
    let url;
    try {
      url = getInterstitialUrl(assetListUrl, this.hls.sessionId, interstitial.baseUrl);
    } catch (error) {
      const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, error, assetListUrl);
      this.hls.trigger(Events.ERROR, errorData);
      return;
    }
    if (hlsStartOffset && url.protocol !== "data:") {
      url.searchParams.set("_HLS_start_offset", "" + hlsStartOffset);
    }
    const config = this.hls.config;
    const Loader = config.loader;
    const loader = new Loader(config);
    const context = {
      responseType: "json",
      url: url.href
    };
    const loadPolicy = config.interstitialAssetListLoadPolicy.default;
    const loaderConfig = {
      loadPolicy,
      timeout: loadPolicy.maxLoadTimeMs,
      maxRetry: 0,
      retryDelay: 0,
      maxRetryDelay: 0
    };
    const callbacks = {
      onSuccess: (response, stats, context2, networkDetails) => {
        const assetListResponse = response.data;
        const assets = assetListResponse == null ? void 0 : assetListResponse.ASSETS;
        if (!Array.isArray(assets)) {
          const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_PARSING_ERROR, new Error(`Invalid interstitial asset list`), context2.url, stats, networkDetails);
          this.hls.trigger(Events.ERROR, errorData);
          return;
        }
        interstitial.assetListResponse = assetListResponse;
        this.hls.trigger(Events.ASSET_LIST_LOADED, {
          event: interstitial,
          assetListResponse,
          networkDetails
        });
      },
      onError: (error, context2, networkDetails, stats) => {
        const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, new Error(`Error loading X-ASSET-LIST: HTTP status ${error.code} ${error.text} (${context2.url})`), context2.url, stats, networkDetails);
        this.hls.trigger(Events.ERROR, errorData);
      },
      onTimeout: (stats, context2, networkDetails) => {
        const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_TIMEOUT, new Error(`Timeout loading X-ASSET-LIST (${context2.url})`), context2.url, stats, networkDetails);
        this.hls.trigger(Events.ERROR, errorData);
      }
    };
    loader.load(context, loaderConfig, callbacks);
    this.hls.trigger(Events.ASSET_LIST_LOADING, {
      event: interstitial
    });
    return loader;
  }
  assignAssetListError(interstitial, details, error, url, stats, networkDetails) {
    interstitial.error = error;
    return {
      type: ErrorTypes.NETWORK_ERROR,
      details,
      fatal: false,
      interstitial,
      url,
      error,
      networkDetails,
      stats
    };
  }
};
function addEventListener(el, type2, listener) {
  removeEventListener(el, type2, listener);
  el.addEventListener(type2, listener);
}
function removeEventListener(el, type2, listener) {
  el.removeEventListener(type2, listener);
}
function playWithCatch(media) {
  media == null ? void 0 : media.play().catch(() => {
  });
}
var InterstitialsController = class extends Logger {
  constructor(hls, HlsPlayerClass) {
    super("interstitials", hls.logger);
    this.HlsPlayerClass = void 0;
    this.hls = void 0;
    this.assetListLoader = void 0;
    this.mediaSelection = null;
    this.altSelection = null;
    this.media = null;
    this.detachedData = null;
    this.requiredTracks = null;
    this.manager = null;
    this.playerQueue = [];
    this.bufferedPos = -1;
    this.timelinePos = -1;
    this.schedule = void 0;
    this.playingItem = null;
    this.bufferingItem = null;
    this.waitingItem = null;
    this.endedItem = null;
    this.playingAsset = null;
    this.endedAsset = null;
    this.bufferingAsset = null;
    this.shouldPlay = false;
    this.onPlay = () => {
      this.shouldPlay = true;
    };
    this.onPause = () => {
      this.shouldPlay = false;
    };
    this.onSeeking = () => {
      const currentTime = this.currentTime;
      if (currentTime === void 0 || this.playbackDisabled) {
        return;
      }
      const diff = currentTime - this.timelinePos;
      const roundingError = Math.abs(diff) < 1 / 7056e5;
      if (roundingError) {
        return;
      }
      const backwardSeek = diff <= -0.01;
      this.timelinePos = currentTime;
      this.bufferedPos = currentTime;
      const playingItem = this.playingItem;
      if (!playingItem) {
        this.checkBuffer();
        return;
      }
      if (backwardSeek) {
        const resetCount = this.schedule.resetErrorsInRange(currentTime, currentTime - diff);
        if (resetCount) {
          this.updateSchedule();
        }
      }
      this.checkBuffer();
      if (backwardSeek && currentTime < playingItem.start || currentTime >= playingItem.end) {
        var _this$media;
        const scheduleIndex = this.schedule.findItemIndexAtTime(this.timelinePos);
        if (!this.isInterstitial(playingItem) && (_this$media = this.media) != null && _this$media.paused) {
          this.shouldPlay = false;
        }
        if (!backwardSeek) {
          const playingIndex = this.findItemIndex(playingItem);
          if (scheduleIndex > playingIndex) {
            const jumpIndex = this.schedule.findJumpRestrictedIndex(playingIndex + 1, scheduleIndex);
            if (jumpIndex > playingIndex) {
              this.setSchedulePosition(jumpIndex);
              return;
            }
          }
        }
        this.setSchedulePosition(scheduleIndex);
        return;
      }
      const playingAsset = this.playingAsset;
      if (!playingAsset) {
        if (this.playingLastItem && this.isInterstitial(playingItem)) {
          const restartAsset = playingItem.event.assetList[0];
          if (restartAsset) {
            this.endedItem = this.playingItem;
            this.playingItem = null;
            this.setScheduleToAssetAtTime(currentTime, restartAsset);
          }
        }
        return;
      }
      const start2 = playingAsset.timelineStart;
      const duration5 = playingAsset.duration || 0;
      if (backwardSeek && currentTime < start2 || currentTime >= start2 + duration5) {
        this.setScheduleToAssetAtTime(currentTime, playingAsset);
      }
    };
    this.onTimeupdate = () => {
      const currentTime = this.currentTime;
      if (currentTime === void 0 || this.playbackDisabled) {
        return;
      }
      if (currentTime > this.timelinePos) {
        this.timelinePos = currentTime;
        if (currentTime > this.bufferedPos) {
          this.checkBuffer();
        }
      } else {
        return;
      }
      const playingItem = this.playingItem;
      if (!playingItem || this.playingLastItem) {
        return;
      }
      if (currentTime >= playingItem.end) {
        this.timelinePos = playingItem.end;
        const playingIndex = this.findItemIndex(playingItem);
        this.setSchedulePosition(playingIndex + 1);
      }
      const playingAsset = this.playingAsset;
      if (!playingAsset) {
        return;
      }
      const end = playingAsset.timelineStart + (playingAsset.duration || 0);
      if (currentTime >= end) {
        this.setScheduleToAssetAtTime(currentTime, playingAsset);
      }
    };
    this.onScheduleUpdate = (removedInterstitials, previousItems) => {
      const schedule = this.schedule;
      const playingItem = this.playingItem;
      const interstitialEvents = schedule.events || [];
      const scheduleItems = schedule.items || [];
      const durations = schedule.durations;
      const removedIds = removedInterstitials.map((interstitial) => interstitial.identifier);
      const interstitialsUpdated = !!(interstitialEvents.length || removedIds.length);
      if (interstitialsUpdated) {
        this.log(`INTERSTITIALS_UPDATED (${interstitialEvents.length}): ${interstitialEvents}
Schedule: ${scheduleItems.map((seg) => segmentToString(seg))}`);
      }
      if (removedIds.length) {
        this.log(`Removed events ${removedIds}`);
      }
      this.playerQueue.forEach((player) => {
        if (player.interstitial.appendInPlace) {
          const timelineStart = player.assetItem.timelineStart;
          const diff = player.timelineOffset - timelineStart;
          if (diff) {
            try {
              player.timelineOffset = timelineStart;
            } catch (e) {
              if (Math.abs(diff) > ALIGNED_END_THRESHOLD_SECONDS) {
                this.warn(`${e} ("${player.assetId}" ${player.timelineOffset}->${timelineStart})`);
              }
            }
          }
        }
      });
      if (playingItem) {
        const updatedPlayingItem = this.updateItem(playingItem, this.timelinePos);
        if (this.itemsMatch(playingItem, updatedPlayingItem)) {
          this.playingItem = updatedPlayingItem;
          this.waitingItem = this.endedItem = null;
        }
      } else {
        this.waitingItem = this.updateItem(this.waitingItem);
        this.endedItem = this.updateItem(this.endedItem);
      }
      const bufferingItem = this.bufferingItem;
      if (bufferingItem) {
        const updatedBufferingItem = this.updateItem(bufferingItem, this.bufferedPos);
        if (this.itemsMatch(bufferingItem, updatedBufferingItem)) {
          this.bufferingItem = updatedBufferingItem;
        } else if (bufferingItem.event) {
          this.bufferingItem = this.playingItem;
          this.clearInterstitial(bufferingItem.event, null);
        }
      }
      removedInterstitials.forEach((interstitial) => {
        interstitial.assetList.forEach((asset) => {
          this.clearAssetPlayer(asset.identifier, null);
        });
      });
      if (interstitialsUpdated || previousItems) {
        this.hls.trigger(Events.INTERSTITIALS_UPDATED, {
          events: interstitialEvents.slice(0),
          schedule: scheduleItems.slice(0),
          durations,
          removedIds
        });
        if (this.isInterstitial(playingItem) && removedIds.includes(playingItem.event.identifier)) {
          this.warn(`Interstitial "${playingItem.event.identifier}" removed while playing`);
          this.primaryFallback(playingItem.event);
          return;
        }
        this.checkBuffer();
      }
    };
    this.hls = hls;
    this.HlsPlayerClass = HlsPlayerClass;
    this.assetListLoader = new AssetListLoader(hls);
    this.schedule = new InterstitialsSchedule(this.onScheduleUpdate, hls.logger);
    this.registerListeners();
  }
  registerListeners() {
    const hls = this.hls;
    hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
    hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
    hls.on(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
    hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
    hls.on(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
    hls.on(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
    hls.on(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
    hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
    hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
    hls.on(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
    hls.on(Events.MEDIA_ENDED, this.onMediaEnded, this);
    hls.on(Events.ERROR, this.onError, this);
    hls.on(Events.DESTROYING, this.onDestroying, this);
  }
  unregisterListeners() {
    const hls = this.hls;
    if (!hls) {
      return;
    }
    hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
    hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
    hls.off(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
    hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
    hls.off(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
    hls.off(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
    hls.off(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
    hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
    hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
    hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
    hls.off(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
    hls.off(Events.MEDIA_ENDED, this.onMediaEnded, this);
    hls.off(Events.ERROR, this.onError, this);
    hls.off(Events.DESTROYING, this.onDestroying, this);
  }
  startLoad() {
    this.resumeBuffering();
  }
  stopLoad() {
    this.pauseBuffering();
  }
  resumeBuffering() {
    var _this$getBufferingPla;
    (_this$getBufferingPla = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla.resumeBuffering();
  }
  pauseBuffering() {
    var _this$getBufferingPla2;
    (_this$getBufferingPla2 = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla2.pauseBuffering();
  }
  destroy() {
    this.unregisterListeners();
    this.stopLoad();
    if (this.assetListLoader) {
      this.assetListLoader.destroy();
    }
    this.emptyPlayerQueue();
    this.clearScheduleState();
    if (this.schedule) {
      this.schedule.destroy();
    }
    this.media = this.detachedData = this.mediaSelection = this.requiredTracks = this.altSelection = this.manager = null;
    this.hls = this.HlsPlayerClass = this.schedule = this.log = null;
    this.assetListLoader = null;
    this.onPlay = this.onPause = this.onSeeking = this.onTimeupdate = null;
    this.onScheduleUpdate = null;
  }
  onDestroying() {
    const media = this.primaryMedia || this.media;
    if (media) {
      this.removeMediaListeners(media);
    }
  }
  removeMediaListeners(media) {
    removeEventListener(media, "play", this.onPlay);
    removeEventListener(media, "pause", this.onPause);
    removeEventListener(media, "seeking", this.onSeeking);
    removeEventListener(media, "timeupdate", this.onTimeupdate);
  }
  onMediaAttaching(event, data) {
    const media = this.media = data.media;
    addEventListener(media, "seeking", this.onSeeking);
    addEventListener(media, "timeupdate", this.onTimeupdate);
    addEventListener(media, "play", this.onPlay);
    addEventListener(media, "pause", this.onPause);
  }
  onMediaAttached(event, data) {
    const playingItem = this.effectivePlayingItem;
    const detachedMedia = this.detachedData;
    this.detachedData = null;
    if (playingItem === null) {
      this.checkStart();
    } else if (!detachedMedia) {
      this.clearScheduleState();
      const playingIndex = this.findItemIndex(playingItem);
      this.setSchedulePosition(playingIndex);
    }
  }
  clearScheduleState() {
    this.playingItem = this.bufferingItem = this.waitingItem = this.endedItem = this.playingAsset = this.endedAsset = this.bufferingAsset = null;
  }
  onMediaDetaching(event, data) {
    const transferringMedia = !!data.transferMedia;
    const media = this.media;
    this.media = null;
    if (transferringMedia) {
      return;
    }
    if (media) {
      this.removeMediaListeners(media);
    }
    if (this.detachedData) {
      const player = this.getBufferingPlayer();
      if (player) {
        this.playingAsset = this.endedAsset = this.bufferingAsset = this.bufferingItem = this.waitingItem = this.detachedData = null;
        player.detachMedia();
      }
      this.shouldPlay = false;
    }
  }
  get interstitialsManager() {
    if (!this.manager) {
      if (!this.hls) {
        return null;
      }
      const c = this;
      const effectiveBufferingItem = () => c.bufferingItem || c.waitingItem;
      const getAssetPlayer = (asset) => asset ? c.getAssetPlayer(asset.identifier) : asset;
      const getMappedTime = (item, timelineType, asset, controllerField, assetPlayerField) => {
        if (item) {
          let time = item[timelineType].start;
          const interstitial = item.event;
          if (interstitial) {
            if (timelineType === "playout" || interstitial.timelineOccupancy !== TimelineOccupancy.Point) {
              const assetPlayer = getAssetPlayer(asset);
              if ((assetPlayer == null ? void 0 : assetPlayer.interstitial) === interstitial) {
                time += assetPlayer.assetItem.startOffset + assetPlayer[assetPlayerField];
              }
            }
          } else {
            const value = controllerField === "bufferedPos" ? getBufferedEnd() : c[controllerField];
            time += value - item.start;
          }
          return time;
        }
        return 0;
      };
      const findMappedTime = (primaryTime, timelineType) => {
        if (primaryTime !== 0 && timelineType !== "primary" && c.schedule.length) {
          var _c$schedule$items;
          const index = c.schedule.findItemIndexAtTime(primaryTime);
          const item = (_c$schedule$items = c.schedule.items) == null ? void 0 : _c$schedule$items[index];
          if (item) {
            const diff = item[timelineType].start - item.start;
            return primaryTime + diff;
          }
        }
        return primaryTime;
      };
      const getBufferedEnd = () => {
        const value = c.bufferedPos;
        if (value === Number.MAX_VALUE) {
          return getMappedDuration("primary");
        }
        return Math.max(value, 0);
      };
      const getMappedDuration = (timelineType) => {
        var _c$primaryDetails;
        if ((_c$primaryDetails = c.primaryDetails) != null && _c$primaryDetails.live) {
          return c.primaryDetails.edge;
        }
        return c.schedule.durations[timelineType];
      };
      const seekTo = (time, timelineType) => {
        var _item$event, _c$schedule$items2;
        const item = c.effectivePlayingItem;
        if (item != null && (_item$event = item.event) != null && _item$event.restrictions.skip) {
          return;
        }
        c.log(`seek to ${time} "${timelineType}"`);
        const playingItem = c.effectivePlayingItem;
        const targetIndex = c.schedule.findItemIndexAtTime(time, timelineType);
        const targetItem = (_c$schedule$items2 = c.schedule.items) == null ? void 0 : _c$schedule$items2[targetIndex];
        const bufferingPlayer = c.getBufferingPlayer();
        const bufferingInterstitial = bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial;
        const appendInPlace = bufferingInterstitial == null ? void 0 : bufferingInterstitial.appendInPlace;
        const seekInItem = playingItem && c.itemsMatch(playingItem, targetItem);
        if (playingItem && (appendInPlace || seekInItem)) {
          const assetPlayer = getAssetPlayer(c.playingAsset);
          const media = (assetPlayer == null ? void 0 : assetPlayer.media) || c.primaryMedia;
          if (media) {
            const currentTime = timelineType === "primary" ? media.currentTime : getMappedTime(playingItem, timelineType, c.playingAsset, "timelinePos", "currentTime");
            const diff = time - currentTime;
            const seekToTime = (appendInPlace ? currentTime : media.currentTime) + diff;
            if (seekToTime >= 0 && (!assetPlayer || appendInPlace || seekToTime <= assetPlayer.duration)) {
              media.currentTime = seekToTime;
              return;
            }
          }
        }
        if (targetItem) {
          let seekToTime = time;
          if (timelineType !== "primary") {
            const primarySegmentStart = targetItem[timelineType].start;
            const diff = time - primarySegmentStart;
            seekToTime = targetItem.start + diff;
          }
          const targetIsPrimary = !c.isInterstitial(targetItem);
          if ((!c.isInterstitial(playingItem) || playingItem.event.appendInPlace) && (targetIsPrimary || targetItem.event.appendInPlace)) {
            const media = c.media || (appendInPlace ? bufferingPlayer == null ? void 0 : bufferingPlayer.media : null);
            if (media) {
              media.currentTime = seekToTime;
            }
          } else if (playingItem) {
            const playingIndex = c.findItemIndex(playingItem);
            if (targetIndex > playingIndex) {
              const jumpIndex = c.schedule.findJumpRestrictedIndex(playingIndex + 1, targetIndex);
              if (jumpIndex > playingIndex) {
                c.setSchedulePosition(jumpIndex);
                return;
              }
            }
            let assetIndex = 0;
            if (targetIsPrimary) {
              c.timelinePos = seekToTime;
              c.checkBuffer();
            } else {
              var _targetItem$event;
              const assetList = targetItem == null ? void 0 : (_targetItem$event = targetItem.event) == null ? void 0 : _targetItem$event.assetList;
              if (assetList) {
                const eventTime = time - (targetItem[timelineType] || targetItem).start;
                for (let i = assetList.length; i--; ) {
                  const asset = assetList[i];
                  if (asset.duration && eventTime >= asset.startOffset && eventTime < asset.startOffset + asset.duration) {
                    assetIndex = i;
                    break;
                  }
                }
              }
            }
            c.setSchedulePosition(targetIndex, assetIndex);
          }
        }
      };
      const getActiveInterstitial = () => {
        const playingItem = c.effectivePlayingItem;
        if (c.isInterstitial(playingItem)) {
          return playingItem;
        }
        const bufferingItem = effectiveBufferingItem();
        if (c.isInterstitial(bufferingItem)) {
          return bufferingItem;
        }
        return null;
      };
      const interstitialPlayer = {
        get currentTime() {
          const interstitialItem = getActiveInterstitial();
          const playingItem = c.effectivePlayingItem;
          if (playingItem && playingItem === interstitialItem) {
            return getMappedTime(playingItem, "playout", c.effectivePlayingAsset, "timelinePos", "currentTime") - playingItem.playout.start;
          }
          return 0;
        },
        set currentTime(time) {
          const interstitialItem = getActiveInterstitial();
          const playingItem = c.effectivePlayingItem;
          if (playingItem && playingItem === interstitialItem) {
            seekTo(time + playingItem.playout.start, "playout");
          }
        },
        get duration() {
          const interstitialItem = getActiveInterstitial();
          if (interstitialItem) {
            return interstitialItem.playout.end - interstitialItem.playout.start;
          }
          return 0;
        },
        get assetPlayers() {
          var _getActiveInterstitia;
          const assetList = (_getActiveInterstitia = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia.event.assetList;
          if (assetList) {
            return assetList.map((asset) => c.getAssetPlayer(asset.identifier));
          }
          return [];
        },
        get playingIndex() {
          var _getActiveInterstitia2;
          const interstitial = (_getActiveInterstitia2 = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia2.event;
          if (interstitial && c.effectivePlayingAsset) {
            return interstitial.findAssetIndex(c.effectivePlayingAsset);
          }
          return -1;
        },
        get scheduleItem() {
          return getActiveInterstitial();
        }
      };
      this.manager = {
        get events() {
          var _c$schedule, _c$schedule$events;
          return ((_c$schedule = c.schedule) == null ? void 0 : (_c$schedule$events = _c$schedule.events) == null ? void 0 : _c$schedule$events.slice(0)) || [];
        },
        get schedule() {
          var _c$schedule2, _c$schedule2$items;
          return ((_c$schedule2 = c.schedule) == null ? void 0 : (_c$schedule2$items = _c$schedule2.items) == null ? void 0 : _c$schedule2$items.slice(0)) || [];
        },
        get interstitialPlayer() {
          if (getActiveInterstitial()) {
            return interstitialPlayer;
          }
          return null;
        },
        get playerQueue() {
          return c.playerQueue.slice(0);
        },
        get bufferingAsset() {
          return c.bufferingAsset;
        },
        get bufferingItem() {
          return effectiveBufferingItem();
        },
        get bufferingIndex() {
          const item = effectiveBufferingItem();
          return c.findItemIndex(item);
        },
        get playingAsset() {
          return c.effectivePlayingAsset;
        },
        get playingItem() {
          return c.effectivePlayingItem;
        },
        get playingIndex() {
          const item = c.effectivePlayingItem;
          return c.findItemIndex(item);
        },
        primary: {
          get bufferedEnd() {
            return getBufferedEnd();
          },
          get currentTime() {
            const timelinePos = c.timelinePos;
            return timelinePos > 0 ? timelinePos : 0;
          },
          set currentTime(time) {
            seekTo(time, "primary");
          },
          get duration() {
            return getMappedDuration("primary");
          },
          get seekableStart() {
            var _c$primaryDetails2;
            return ((_c$primaryDetails2 = c.primaryDetails) == null ? void 0 : _c$primaryDetails2.fragmentStart) || 0;
          }
        },
        integrated: {
          get bufferedEnd() {
            return getMappedTime(effectiveBufferingItem(), "integrated", c.bufferingAsset, "bufferedPos", "bufferedEnd");
          },
          get currentTime() {
            return getMappedTime(c.effectivePlayingItem, "integrated", c.effectivePlayingAsset, "timelinePos", "currentTime");
          },
          set currentTime(time) {
            seekTo(time, "integrated");
          },
          get duration() {
            return getMappedDuration("integrated");
          },
          get seekableStart() {
            var _c$primaryDetails3;
            return findMappedTime(((_c$primaryDetails3 = c.primaryDetails) == null ? void 0 : _c$primaryDetails3.fragmentStart) || 0, "integrated");
          }
        },
        skip: () => {
          const item = c.effectivePlayingItem;
          const event = item == null ? void 0 : item.event;
          if (event && !event.restrictions.skip) {
            const index = c.findItemIndex(item);
            if (event.appendInPlace) {
              const time = item.playout.start + item.event.duration;
              seekTo(time + 1e-3, "playout");
            } else {
              c.advanceAfterAssetEnded(event, index, Infinity);
            }
          }
        }
      };
    }
    return this.manager;
  }
  // Schedule getters
  get effectivePlayingItem() {
    return this.waitingItem || this.playingItem || this.endedItem;
  }
  get effectivePlayingAsset() {
    return this.playingAsset || this.endedAsset;
  }
  get playingLastItem() {
    var _this$schedule;
    const playingItem = this.playingItem;
    const items = (_this$schedule = this.schedule) == null ? void 0 : _this$schedule.items;
    if (!this.playbackStarted || !playingItem || !items) {
      return false;
    }
    return this.findItemIndex(playingItem) === items.length - 1;
  }
  get playbackStarted() {
    return this.effectivePlayingItem !== null;
  }
  // Media getters and event callbacks
  get currentTime() {
    var _this$bufferingItem, _this$bufferingItem$e, _media;
    if (this.mediaSelection === null) {
      return void 0;
    }
    const queuedForPlayback = this.waitingItem || this.playingItem;
    if (this.isInterstitial(queuedForPlayback) && !queuedForPlayback.event.appendInPlace) {
      return void 0;
    }
    let media = this.media;
    if (!media && (_this$bufferingItem = this.bufferingItem) != null && (_this$bufferingItem$e = _this$bufferingItem.event) != null && _this$bufferingItem$e.appendInPlace) {
      media = this.primaryMedia;
    }
    const currentTime = (_media = media) == null ? void 0 : _media.currentTime;
    if (currentTime === void 0 || !isFiniteNumber(currentTime)) {
      return void 0;
    }
    return currentTime;
  }
  get primaryMedia() {
    var _this$detachedData;
    return this.media || ((_this$detachedData = this.detachedData) == null ? void 0 : _this$detachedData.media) || null;
  }
  isInterstitial(item) {
    return !!(item != null && item.event);
  }
  retreiveMediaSource(assetId, toSegment) {
    const player = this.getAssetPlayer(assetId);
    if (player) {
      this.transferMediaFromPlayer(player, toSegment);
    }
  }
  transferMediaFromPlayer(player, toSegment) {
    const appendInPlace = player.interstitial.appendInPlace;
    const playerMedia = player.media;
    if (appendInPlace && playerMedia === this.primaryMedia) {
      this.bufferingAsset = null;
      if (!toSegment || this.isInterstitial(toSegment) && !toSegment.event.appendInPlace) {
        if (toSegment && playerMedia) {
          this.detachedData = {
            media: playerMedia
          };
          return;
        }
      }
      const attachMediaSourceData = player.transferMedia();
      this.log(`transfer MediaSource from ${player} ${stringify(attachMediaSourceData)}`);
      this.detachedData = attachMediaSourceData;
    } else if (toSegment && playerMedia) {
      this.shouldPlay || (this.shouldPlay = !playerMedia.paused);
    }
  }
  transferMediaTo(player, media) {
    var _this$detachedData2, _attachMediaSourceDat;
    if (player.media === media) {
      return;
    }
    let attachMediaSourceData = null;
    const primaryPlayer = this.hls;
    const isAssetPlayer = player !== primaryPlayer;
    const appendInPlace = isAssetPlayer && player.interstitial.appendInPlace;
    const detachedMediaSource = (_this$detachedData2 = this.detachedData) == null ? void 0 : _this$detachedData2.mediaSource;
    let logFromSource;
    if (primaryPlayer.media) {
      if (appendInPlace) {
        attachMediaSourceData = primaryPlayer.transferMedia();
        this.detachedData = attachMediaSourceData;
      }
      logFromSource = `Primary`;
    } else if (detachedMediaSource) {
      const bufferingPlayer = this.getBufferingPlayer();
      if (bufferingPlayer) {
        attachMediaSourceData = bufferingPlayer.transferMedia();
        logFromSource = `${bufferingPlayer}`;
      } else {
        logFromSource = `detached MediaSource`;
      }
    } else {
      logFromSource = `detached media`;
    }
    if (!attachMediaSourceData) {
      if (detachedMediaSource) {
        attachMediaSourceData = this.detachedData;
        this.log(`using detachedData: MediaSource ${stringify(attachMediaSourceData)}`);
      } else if (!this.detachedData || primaryPlayer.media === media) {
        const playerQueue = this.playerQueue;
        if (playerQueue.length > 1) {
          playerQueue.forEach((queuedPlayer) => {
            if (isAssetPlayer && queuedPlayer.interstitial.appendInPlace !== appendInPlace) {
              const interstitial = queuedPlayer.interstitial;
              this.clearInterstitial(queuedPlayer.interstitial, null);
              interstitial.appendInPlace = false;
              if (interstitial.appendInPlace) {
                this.warn(`Could not change append strategy for queued assets ${interstitial}`);
              }
            }
          });
        }
        this.hls.detachMedia();
        this.detachedData = {
          media
        };
      }
    }
    const transferring = attachMediaSourceData && "mediaSource" in attachMediaSourceData && ((_attachMediaSourceDat = attachMediaSourceData.mediaSource) == null ? void 0 : _attachMediaSourceDat.readyState) !== "closed";
    const dataToAttach = transferring && attachMediaSourceData ? attachMediaSourceData : media;
    this.log(`${transferring ? "transfering MediaSource" : "attaching media"} to ${isAssetPlayer ? player : "Primary"} from ${logFromSource}`);
    if (dataToAttach === attachMediaSourceData) {
      const isAssetAtEndOfSchedule = isAssetPlayer && player.assetId === this.schedule.assetIdAtEnd;
      dataToAttach.overrides = {
        duration: this.schedule.duration,
        endOfStream: !isAssetPlayer || isAssetAtEndOfSchedule,
        cueRemoval: !isAssetPlayer
      };
    }
    player.attachMedia(dataToAttach);
  }
  onInterstitialCueEnter() {
    this.onTimeupdate();
  }
  // Scheduling methods
  checkStart() {
    const schedule = this.schedule;
    const interstitialEvents = schedule.events;
    if (!interstitialEvents || this.playbackDisabled || !this.media) {
      return;
    }
    if (this.bufferedPos === -1) {
      this.bufferedPos = 0;
    }
    const timelinePos = this.timelinePos;
    const effectivePlayingItem = this.effectivePlayingItem;
    if (timelinePos === -1) {
      const startPosition = this.hls.startPosition;
      this.timelinePos = startPosition;
      if (interstitialEvents.length && interstitialEvents[0].cue.pre) {
        const index = schedule.findEventIndex(interstitialEvents[0].identifier);
        this.setSchedulePosition(index);
      } else if (startPosition >= 0 || !this.primaryLive) {
        const start2 = this.timelinePos = startPosition > 0 ? startPosition : 0;
        const index = schedule.findItemIndexAtTime(start2);
        this.setSchedulePosition(index);
      }
    } else if (effectivePlayingItem && !this.playingItem) {
      const index = schedule.findItemIndex(effectivePlayingItem);
      this.setSchedulePosition(index);
    }
  }
  advanceAfterAssetEnded(interstitial, index, assetListIndex) {
    const nextAssetIndex = assetListIndex + 1;
    if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex) && !interstitial.assetList[nextAssetIndex].error) {
      this.setSchedulePosition(index, nextAssetIndex);
    } else {
      const scheduleItems = this.schedule.items;
      if (scheduleItems) {
        const nextIndex = index + 1;
        const scheduleLength = scheduleItems.length;
        if (nextIndex >= scheduleLength) {
          this.setSchedulePosition(-1);
          return;
        }
        const resumptionTime = interstitial.resumeTime;
        if (this.timelinePos < resumptionTime) {
          this.timelinePos = resumptionTime;
          this.checkBuffer();
        }
        this.setSchedulePosition(nextIndex);
      }
    }
  }
  setScheduleToAssetAtTime(time, playingAsset) {
    const schedule = this.schedule;
    const parentIdentifier = playingAsset.parentIdentifier;
    const interstitial = schedule.getEvent(parentIdentifier);
    if (interstitial) {
      const itemIndex = schedule.findEventIndex(parentIdentifier);
      const assetListIndex = schedule.findAssetIndex(interstitial, time);
      this.setSchedulePosition(itemIndex, assetListIndex);
    }
  }
  setSchedulePosition(index, assetListIndex) {
    const scheduleItems = this.schedule.items;
    if (!scheduleItems || this.playbackDisabled) {
      return;
    }
    this.log(`setSchedulePosition ${index}, ${assetListIndex}`);
    const scheduledItem = index >= 0 ? scheduleItems[index] : null;
    const currentItem = this.playingItem;
    const playingLastItem = this.playingLastItem;
    if (this.isInterstitial(currentItem)) {
      var _interstitial$assetLi;
      const interstitial = currentItem.event;
      const playingAsset = this.playingAsset;
      const assetId = playingAsset == null ? void 0 : playingAsset.identifier;
      const player = assetId ? this.getAssetPlayer(assetId) : null;
      if (player && assetId && (!this.eventItemsMatch(currentItem, scheduledItem) || assetListIndex !== void 0 && assetId !== ((_interstitial$assetLi = interstitial.assetList) == null ? void 0 : _interstitial$assetLi[assetListIndex].identifier))) {
        var _this$detachedData3;
        const _assetListIndex = interstitial.findAssetIndex(playingAsset);
        this.log(`INTERSTITIAL_ASSET_ENDED ${_assetListIndex + 1}/${interstitial.assetList.length} ${eventAssetToString(playingAsset)}`);
        this.endedAsset = playingAsset;
        this.playingAsset = null;
        this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED, {
          asset: playingAsset,
          assetListIndex: _assetListIndex,
          event: interstitial,
          schedule: scheduleItems.slice(0),
          scheduleIndex: index,
          player
        });
        this.retreiveMediaSource(assetId, scheduledItem);
        if (player.media && !((_this$detachedData3 = this.detachedData) != null && _this$detachedData3.mediaSource)) {
          player.detachMedia();
        }
      }
      if (!this.eventItemsMatch(currentItem, scheduledItem)) {
        this.endedItem = currentItem;
        this.playingItem = null;
        this.log(`INTERSTITIAL_ENDED ${interstitial} ${segmentToString(currentItem)}`);
        interstitial.hasPlayed = true;
        this.hls.trigger(Events.INTERSTITIAL_ENDED, {
          event: interstitial,
          schedule: scheduleItems.slice(0),
          scheduleIndex: index
        });
        if (interstitial.cue.once) {
          this.updateSchedule();
          const items = this.schedule.items;
          if (scheduledItem && items) {
            const updatedIndex = this.schedule.findItemIndex(scheduledItem);
            this.advanceSchedule(updatedIndex, items, assetListIndex, currentItem, playingLastItem);
          }
          return;
        }
      }
    }
    this.advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playingLastItem);
  }
  advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playedLastItem) {
    const scheduledItem = index >= 0 ? scheduleItems[index] : null;
    const media = this.primaryMedia;
    const playerQueue = this.playerQueue;
    if (playerQueue.length) {
      playerQueue.forEach((player) => {
        const interstitial = player.interstitial;
        const queuedIndex = this.schedule.findEventIndex(interstitial.identifier);
        if (queuedIndex < index || queuedIndex > index + 1) {
          this.clearInterstitial(interstitial, scheduledItem);
        }
      });
    }
    if (this.isInterstitial(scheduledItem)) {
      this.timelinePos = Math.min(Math.max(this.timelinePos, scheduledItem.start), scheduledItem.end);
      const interstitial = scheduledItem.event;
      if (assetListIndex === void 0) {
        assetListIndex = this.schedule.findAssetIndex(interstitial, this.timelinePos);
      }
      const waitingItem = this.waitingItem;
      if (!this.assetsBuffered(scheduledItem, media)) {
        this.setBufferingItem(scheduledItem);
      }
      let player = this.preloadAssets(interstitial, assetListIndex);
      if (!this.eventItemsMatch(scheduledItem, waitingItem || currentItem)) {
        this.waitingItem = scheduledItem;
        this.log(`INTERSTITIAL_STARTED ${segmentToString(scheduledItem)} ${interstitial.appendInPlace ? "append in place" : ""}`);
        this.hls.trigger(Events.INTERSTITIAL_STARTED, {
          event: interstitial,
          schedule: scheduleItems.slice(0),
          scheduleIndex: index
        });
      }
      if (!interstitial.assetListLoaded) {
        this.log(`Waiting for ASSET-LIST to complete loading ${interstitial}`);
        return;
      }
      if (interstitial.assetListLoader) {
        interstitial.assetListLoader.destroy();
        interstitial.assetListLoader = void 0;
      }
      if (!media) {
        this.log(`Waiting for attachMedia to start Interstitial ${interstitial}`);
        return;
      }
      this.waitingItem = this.endedItem = null;
      this.playingItem = scheduledItem;
      const assetItem = interstitial.assetList[assetListIndex];
      if (!assetItem) {
        const nextItem = scheduleItems[index + 1];
        const _media2 = this.media;
        if (nextItem && _media2 && !this.isInterstitial(nextItem) && _media2.currentTime < nextItem.start) {
          _media2.currentTime = this.timelinePos = nextItem.start;
        }
        this.advanceAfterAssetEnded(interstitial, index, assetListIndex || 0);
        return;
      }
      if (!player) {
        player = this.getAssetPlayer(assetItem.identifier);
      }
      if (player === null || player.destroyed) {
        const assetListLength = interstitial.assetList.length;
        this.warn(`asset ${assetListIndex + 1}/${assetListLength} player destroyed ${interstitial}`);
        player = this.createAssetPlayer(interstitial, assetItem, assetListIndex);
      }
      if (!this.eventItemsMatch(scheduledItem, this.bufferingItem)) {
        if (interstitial.appendInPlace && this.isAssetBuffered(assetItem)) {
          return;
        }
      }
      this.startAssetPlayer(player, assetListIndex, scheduleItems, index, media);
      if (this.shouldPlay) {
        playWithCatch(player.media);
      }
    } else if (scheduledItem !== null) {
      this.resumePrimary(scheduledItem, index, currentItem);
      if (this.shouldPlay) {
        playWithCatch(this.hls.media);
      }
    } else if (playedLastItem && this.isInterstitial(currentItem)) {
      this.endedItem = null;
      this.playingItem = currentItem;
      if (!currentItem.event.appendInPlace) {
        this.attachPrimary(this.schedule.durations.primary, null);
      }
    }
  }
  get playbackDisabled() {
    return this.hls.config.enableInterstitialPlayback === false;
  }
  get primaryDetails() {
    var _this$mediaSelection, _this$mediaSelection$;
    return (_this$mediaSelection = this.mediaSelection) == null ? void 0 : (_this$mediaSelection$ = _this$mediaSelection.main) == null ? void 0 : _this$mediaSelection$.details;
  }
  get primaryLive() {
    var _this$primaryDetails;
    return !!((_this$primaryDetails = this.primaryDetails) != null && _this$primaryDetails.live);
  }
  resumePrimary(scheduledItem, index, fromItem) {
    var _this$detachedData4;
    this.playingItem = scheduledItem;
    this.playingAsset = this.endedAsset = null;
    this.waitingItem = this.endedItem = null;
    this.bufferedToItem(scheduledItem);
    this.log(`resuming ${segmentToString(scheduledItem)}`);
    if (!((_this$detachedData4 = this.detachedData) != null && _this$detachedData4.mediaSource)) {
      let timelinePos = this.timelinePos;
      if (timelinePos < scheduledItem.start || timelinePos >= scheduledItem.end) {
        timelinePos = this.getPrimaryResumption(scheduledItem, index);
        this.timelinePos = timelinePos;
      }
      this.attachPrimary(timelinePos, scheduledItem);
    }
    if (!fromItem) {
      return;
    }
    const scheduleItems = this.schedule.items;
    if (!scheduleItems) {
      return;
    }
    this.log(`resumed ${segmentToString(scheduledItem)}`);
    this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED, {
      schedule: scheduleItems.slice(0),
      scheduleIndex: index
    });
    this.checkBuffer();
  }
  getPrimaryResumption(scheduledItem, index) {
    const itemStart = scheduledItem.start;
    if (this.primaryLive) {
      const details = this.primaryDetails;
      if (index === 0) {
        return this.hls.startPosition;
      } else if (details && (itemStart < details.fragmentStart || itemStart > details.edge)) {
        return this.hls.liveSyncPosition || -1;
      }
    }
    return itemStart;
  }
  isAssetBuffered(asset) {
    const player = this.getAssetPlayer(asset.identifier);
    if (player != null && player.hls) {
      return player.hls.bufferedToEnd;
    }
    const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
    return bufferInfo.end + 1 >= asset.timelineStart + (asset.duration || 0);
  }
  attachPrimary(timelinePos, item, skipSeekToStartPosition) {
    if (item) {
      this.setBufferingItem(item);
    } else {
      this.bufferingItem = this.playingItem;
    }
    this.bufferingAsset = null;
    const media = this.primaryMedia;
    if (!media) {
      return;
    }
    const hls = this.hls;
    if (hls.media) {
      this.checkBuffer();
    } else {
      this.transferMediaTo(hls, media);
      if (skipSeekToStartPosition) {
        this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
      }
    }
    if (!skipSeekToStartPosition) {
      this.timelinePos = timelinePos;
      this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
    }
  }
  startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition) {
    var _hls$mainForwardBuffe;
    const hls = this.hls;
    if (!hls.loadingEnabled || !hls.media || Math.abs((((_hls$mainForwardBuffe = hls.mainForwardBufferInfo) == null ? void 0 : _hls$mainForwardBuffe.start) || hls.media.currentTime) - timelinePos) > 0.5) {
      hls.startLoad(timelinePos, skipSeekToStartPosition);
    } else if (!hls.bufferingEnabled) {
      hls.resumeBuffering();
    }
  }
  // HLS.js event callbacks
  onManifestLoading() {
    this.stopLoad();
    this.schedule.reset();
    this.emptyPlayerQueue();
    this.clearScheduleState();
    this.shouldPlay = false;
    this.bufferedPos = this.timelinePos = -1;
    this.mediaSelection = this.altSelection = this.manager = this.requiredTracks = null;
    this.hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
    this.hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  }
  onLevelUpdated(event, data) {
    if (data.level === -1) {
      return;
    }
    const main = this.hls.levels[data.level];
    const currentSelection = _objectSpread2(_objectSpread2({}, this.mediaSelection || this.altSelection), {}, {
      main
    });
    this.mediaSelection = currentSelection;
    this.schedule.parseInterstitialDateRanges(currentSelection, this.hls.config.interstitialAppendInPlace);
    if (!this.effectivePlayingItem && this.schedule.items) {
      this.checkStart();
    }
  }
  onAudioTrackUpdated(event, data) {
    const audio = this.hls.audioTracks[data.id];
    const previousSelection = this.mediaSelection;
    if (!previousSelection) {
      this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
        audio
      });
      return;
    }
    const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
      audio
    });
    this.mediaSelection = currentSelection;
  }
  onSubtitleTrackUpdated(event, data) {
    const subtitles = this.hls.subtitleTracks[data.id];
    const previousSelection = this.mediaSelection;
    if (!previousSelection) {
      this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
        subtitles
      });
      return;
    }
    const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
      subtitles
    });
    this.mediaSelection = currentSelection;
  }
  onAudioTrackSwitching(event, data) {
    const audioOption = getBasicSelectionOption(data);
    this.playerQueue.forEach((player) => player.hls.setAudioOption(data) || player.hls.setAudioOption(audioOption));
  }
  onSubtitleTrackSwitch(event, data) {
    const subtitleOption = getBasicSelectionOption(data);
    this.playerQueue.forEach((player) => player.hls.setSubtitleOption(data) || data.id !== -1 && player.hls.setSubtitleOption(subtitleOption));
  }
  onBufferCodecs(event, data) {
    const requiredTracks = data.tracks;
    if (requiredTracks) {
      this.requiredTracks = requiredTracks;
    }
  }
  onBufferAppended(event, data) {
    this.checkBuffer();
  }
  onBufferFlushed(event, data) {
    const playingItem = this.playingItem;
    if (playingItem && !this.itemsMatch(playingItem, this.bufferingItem) && !this.isInterstitial(playingItem)) {
      const timelinePos = this.timelinePos;
      this.bufferedPos = timelinePos;
      this.checkBuffer();
    }
  }
  onBufferedToEnd(event) {
    const interstitialEvents = this.schedule.events;
    if (this.bufferedPos < Number.MAX_VALUE && interstitialEvents) {
      for (let i = 0; i < interstitialEvents.length; i++) {
        const interstitial = interstitialEvents[i];
        if (interstitial.cue.post) {
          var _this$schedule$items;
          const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
          const item = (_this$schedule$items = this.schedule.items) == null ? void 0 : _this$schedule$items[scheduleIndex];
          if (this.isInterstitial(item) && this.eventItemsMatch(item, this.bufferingItem)) {
            this.bufferedToItem(item, 0);
          }
          break;
        }
      }
      this.bufferedPos = Number.MAX_VALUE;
    }
  }
  onMediaEnded(event) {
    const playingItem = this.playingItem;
    if (!this.playingLastItem && playingItem) {
      const playingIndex = this.findItemIndex(playingItem);
      this.setSchedulePosition(playingIndex + 1);
    } else {
      this.shouldPlay = false;
    }
  }
  updateItem(previousItem, time) {
    const items = this.schedule.items;
    if (previousItem && items) {
      const index = this.findItemIndex(previousItem, time);
      return items[index] || null;
    }
    return null;
  }
  itemsMatch(a, b) {
    return !!b && (a === b || a.event && b.event && this.eventItemsMatch(a, b) || !a.event && !b.event && this.findItemIndex(a) === this.findItemIndex(b));
  }
  eventItemsMatch(a, b) {
    var _b$event;
    return !!b && (a === b || a.event.identifier === ((_b$event = b.event) == null ? void 0 : _b$event.identifier));
  }
  findItemIndex(item, time) {
    return item ? this.schedule.findItemIndex(item, time) : -1;
  }
  updateSchedule() {
    const mediaSelection = this.mediaSelection;
    if (!mediaSelection) {
      return;
    }
    this.schedule.updateSchedule(mediaSelection, []);
  }
  // Schedule buffer control
  checkBuffer(starved) {
    const items = this.schedule.items;
    if (!items) {
      return;
    }
    const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
    if (starved) {
      this.bufferedPos = this.timelinePos;
    }
    starved || (starved = bufferInfo.len < 1);
    this.updateBufferedPos(bufferInfo.end, items, starved);
  }
  updateBufferedPos(bufferEnd, items, bufferIsEmpty) {
    const schedule = this.schedule;
    const bufferingItem = this.bufferingItem;
    if (this.bufferedPos > bufferEnd) {
      return;
    }
    if (items.length === 1 && this.itemsMatch(items[0], bufferingItem)) {
      this.bufferedPos = bufferEnd;
      return;
    }
    const playingItem = this.playingItem;
    const playingIndex = this.findItemIndex(playingItem);
    let bufferEndIndex = schedule.findItemIndexAtTime(bufferEnd);
    if (this.bufferedPos < bufferEnd) {
      var _nextItemToBuffer$eve, _bufferingItem$event;
      const bufferingIndex = this.findItemIndex(bufferingItem);
      const nextToBufferIndex = Math.min(bufferingIndex + 1, items.length - 1);
      const nextItemToBuffer = items[nextToBufferIndex];
      if (bufferEndIndex === -1 && bufferingItem && bufferEnd >= bufferingItem.end || (_nextItemToBuffer$eve = nextItemToBuffer.event) != null && _nextItemToBuffer$eve.appendInPlace && bufferEnd + 0.01 >= nextItemToBuffer.start) {
        bufferEndIndex = nextToBufferIndex;
      }
      if (nextToBufferIndex - playingIndex > 1 && (bufferingItem == null ? void 0 : (_bufferingItem$event = bufferingItem.event) == null ? void 0 : _bufferingItem$event.appendInPlace) === false) {
        return;
      }
      this.bufferedPos = bufferEnd;
      if (bufferEndIndex > bufferingIndex && bufferEndIndex > playingIndex) {
        this.bufferedToItem(nextItemToBuffer);
      } else {
        const details = this.primaryDetails;
        if (this.primaryLive && details && bufferEnd > details.edge - details.targetduration && nextItemToBuffer.start < details.edge + this.hls.config.interstitialLiveLookAhead && this.isInterstitial(nextItemToBuffer)) {
          this.preloadAssets(nextItemToBuffer.event, 0);
        }
      }
    } else if (bufferIsEmpty && playingItem && !this.itemsMatch(playingItem, bufferingItem)) {
      if (bufferEndIndex === playingIndex) {
        this.bufferedToItem(playingItem);
      } else if (bufferEndIndex === playingIndex + 1) {
        this.bufferedToItem(items[bufferEndIndex]);
      }
    }
  }
  assetsBuffered(item, media) {
    const assetList = item.event.assetList;
    if (assetList.length === 0) {
      return false;
    }
    return !item.event.assetList.some((asset) => {
      const player = this.getAssetPlayer(asset.identifier);
      return !(player != null && player.bufferedInPlaceToEnd(media));
    });
  }
  setBufferingItem(item) {
    const bufferingLast = this.bufferingItem;
    const schedule = this.schedule;
    if (!this.itemsMatch(item, bufferingLast)) {
      const {
        items,
        events
      } = schedule;
      if (!items || !events) {
        return bufferingLast;
      }
      const isInterstitial = this.isInterstitial(item);
      const bufferingPlayer = this.getBufferingPlayer();
      this.bufferingItem = item;
      this.bufferedPos = Math.max(item.start, Math.min(item.end, this.timelinePos));
      if (!this.playbackDisabled) {
        const timeRemaining = bufferingPlayer ? bufferingPlayer.remaining : bufferingLast ? bufferingLast.end - this.timelinePos : 0;
        this.log(`buffered to boundary ${segmentToString(item)}` + (bufferingLast ? ` (${timeRemaining.toFixed(2)} remaining)` : ""));
        if (isInterstitial) {
          item.event.assetList.forEach((asset) => {
            const player = this.getAssetPlayer(asset.identifier);
            if (player) {
              player.resumeBuffering();
            }
          });
        } else {
          this.hls.resumeBuffering();
          this.playerQueue.forEach((player) => player.pauseBuffering());
        }
      }
      this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY, {
        events: events.slice(0),
        schedule: items.slice(0),
        bufferingIndex: this.findItemIndex(item),
        playingIndex: this.findItemIndex(this.playingItem)
      });
    } else if (this.bufferingItem !== item) {
      this.bufferingItem = item;
    }
    return bufferingLast;
  }
  bufferedToItem(item, assetListIndex = 0) {
    const bufferingLast = this.setBufferingItem(item);
    if (this.playbackDisabled) {
      return;
    }
    if (this.isInterstitial(item)) {
      this.bufferedToEvent(item, assetListIndex);
    } else if (bufferingLast !== null) {
      this.bufferingAsset = null;
      const detachedData = this.detachedData;
      if (detachedData) {
        if (detachedData.mediaSource) {
          const skipSeekToStartPosition = true;
          this.attachPrimary(item.start, item, skipSeekToStartPosition);
        } else {
          this.preloadPrimary(item);
        }
      } else {
        this.preloadPrimary(item);
      }
    }
  }
  preloadPrimary(item) {
    const index = this.findItemIndex(item);
    const timelinePos = this.getPrimaryResumption(item, index);
    this.startLoadingPrimaryAt(timelinePos);
  }
  bufferedToEvent(item, assetListIndex) {
    const interstitial = item.event;
    const neverLoaded = interstitial.assetList.length === 0 && !interstitial.assetListLoader;
    const playOnce = interstitial.cue.once;
    if (neverLoaded || !playOnce) {
      const player = this.preloadAssets(interstitial, assetListIndex);
      if (player != null && player.interstitial.appendInPlace) {
        const assetItem = interstitial.assetList[assetListIndex];
        const media = this.primaryMedia;
        if (assetItem && media) {
          this.bufferAssetPlayer(player, media);
        }
      }
    }
  }
  preloadAssets(interstitial, assetListIndex) {
    const uri = interstitial.assetUrl;
    const assetListLength = interstitial.assetList.length;
    const neverLoaded = assetListLength === 0 && !interstitial.assetListLoader;
    const playOnce = interstitial.cue.once;
    if (neverLoaded) {
      const timelineStart = interstitial.timelineStart;
      if (interstitial.appendInPlace) {
        var _playingItem$nextEven;
        const playingItem = this.playingItem;
        if (!this.isInterstitial(playingItem) && (playingItem == null ? void 0 : (_playingItem$nextEven = playingItem.nextEvent) == null ? void 0 : _playingItem$nextEven.identifier) === interstitial.identifier) {
          this.flushFrontBuffer(timelineStart + 0.25);
        }
      }
      let hlsStartOffset;
      let liveStartPosition = 0;
      if (!this.playingItem && this.primaryLive) {
        liveStartPosition = this.hls.startPosition;
        if (liveStartPosition === -1) {
          liveStartPosition = this.hls.liveSyncPosition || 0;
        }
      }
      if (liveStartPosition && !(interstitial.cue.pre || interstitial.cue.post)) {
        const startOffset = liveStartPosition - timelineStart;
        if (startOffset > 0) {
          hlsStartOffset = Math.round(startOffset * 1e3) / 1e3;
        }
      }
      this.log(`Load interstitial asset ${assetListIndex + 1}/${uri ? 1 : assetListLength} ${interstitial}${hlsStartOffset ? ` live-start: ${liveStartPosition} start-offset: ${hlsStartOffset}` : ""}`);
      if (uri) {
        return this.createAsset(interstitial, 0, 0, timelineStart, interstitial.duration, uri);
      }
      const assetListLoader = this.assetListLoader.loadAssetList(interstitial, hlsStartOffset);
      if (assetListLoader) {
        interstitial.assetListLoader = assetListLoader;
      }
    } else if (!playOnce && assetListLength) {
      for (let i = assetListIndex; i < assetListLength; i++) {
        const asset = interstitial.assetList[i];
        const playerIndex = this.getAssetPlayerQueueIndex(asset.identifier);
        if ((playerIndex === -1 || this.playerQueue[playerIndex].destroyed) && !asset.error) {
          this.createAssetPlayer(interstitial, asset, i);
        }
      }
      return this.getAssetPlayer(interstitial.assetList[assetListIndex].identifier);
    }
    return null;
  }
  flushFrontBuffer(startOffset) {
    const requiredTracks = this.requiredTracks;
    if (!requiredTracks) {
      return;
    }
    this.log(`Removing front buffer starting at ${startOffset}`);
    const sourceBufferNames = Object.keys(requiredTracks);
    sourceBufferNames.forEach((type2) => {
      this.hls.trigger(Events.BUFFER_FLUSHING, {
        startOffset,
        endOffset: Infinity,
        type: type2
      });
    });
  }
  // Interstitial Asset Player control
  getAssetPlayerQueueIndex(assetId) {
    const playerQueue = this.playerQueue;
    for (let i = 0; i < playerQueue.length; i++) {
      if (assetId === playerQueue[i].assetId) {
        return i;
      }
    }
    return -1;
  }
  getAssetPlayer(assetId) {
    const index = this.getAssetPlayerQueueIndex(assetId);
    return this.playerQueue[index] || null;
  }
  getBufferingPlayer() {
    const {
      playerQueue,
      primaryMedia
    } = this;
    if (primaryMedia) {
      for (let i = 0; i < playerQueue.length; i++) {
        if (playerQueue[i].media === primaryMedia) {
          return playerQueue[i];
        }
      }
    }
    return null;
  }
  createAsset(interstitial, assetListIndex, startOffset, timelineStart, duration5, uri) {
    const assetItem = {
      parentIdentifier: interstitial.identifier,
      identifier: generateAssetIdentifier(interstitial, uri, assetListIndex),
      duration: duration5,
      startOffset,
      timelineStart,
      uri
    };
    return this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  }
  createAssetPlayer(interstitial, assetItem, assetListIndex) {
    this.log(`create HLSAssetPlayer for ${eventAssetToString(assetItem)}`);
    const primary = this.hls;
    const userConfig = primary.userConfig;
    let videoPreference = userConfig.videoPreference;
    const currentLevel = primary.loadLevelObj || primary.levels[primary.currentLevel];
    if (videoPreference || currentLevel) {
      videoPreference = _extends({}, videoPreference);
      if (currentLevel.videoCodec) {
        videoPreference.videoCodec = currentLevel.videoCodec;
      }
      if (currentLevel.videoRange) {
        videoPreference.allowedVideoRanges = [currentLevel.videoRange];
      }
    }
    const selectedAudio = primary.audioTracks[primary.audioTrack];
    const selectedSubtitle = primary.subtitleTracks[primary.subtitleTrack];
    let startPosition = 0;
    if (this.primaryLive || interstitial.appendInPlace) {
      const timePastStart = this.timelinePos - assetItem.timelineStart;
      if (timePastStart > 1) {
        const duration5 = assetItem.duration;
        if (duration5 && timePastStart < duration5) {
          startPosition = timePastStart;
        }
      }
    }
    const assetId = assetItem.identifier;
    const playerConfig = _objectSpread2(_objectSpread2({}, userConfig), {}, {
      autoStartLoad: true,
      startFragPrefetch: true,
      primarySessionId: primary.sessionId,
      assetPlayerId: assetId,
      abrEwmaDefaultEstimate: primary.bandwidthEstimate,
      interstitialsController: void 0,
      startPosition,
      liveDurationInfinity: false,
      testBandwidth: false,
      videoPreference,
      audioPreference: selectedAudio || userConfig.audioPreference,
      subtitlePreference: selectedSubtitle || userConfig.subtitlePreference
    });
    if (interstitial.appendInPlace) {
      interstitial.appendInPlaceStarted = true;
      if (assetItem.timelineStart) {
        playerConfig.timelineOffset = assetItem.timelineStart;
      }
    }
    const cmcd = playerConfig.cmcd;
    if (cmcd != null && cmcd.sessionId && cmcd.contentId) {
      playerConfig.cmcd = _extends({}, cmcd, {
        contentId: hash(assetItem.uri)
      });
    }
    if (this.getAssetPlayer(assetId)) {
      this.warn(`Duplicate date range identifier ${interstitial} and asset ${assetId}`);
    }
    const player = new HlsAssetPlayer(this.HlsPlayerClass, playerConfig, interstitial, assetItem);
    this.playerQueue.push(player);
    interstitial.assetList[assetListIndex] = assetItem;
    const updateAssetPlayerDetails = (details) => {
      if (details.live) {
        const error = new Error(`Interstitials MUST be VOD assets ${interstitial}`);
        const errorData = {
          fatal: true,
          type: ErrorTypes.OTHER_ERROR,
          details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
          error
        };
        this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
        return;
      }
      const duration5 = details.edge - details.fragmentStart;
      const currentAssetDuration = assetItem.duration;
      if (currentAssetDuration === null || duration5 > currentAssetDuration) {
        this.log(`Interstitial asset "${assetId}" duration change ${currentAssetDuration} > ${duration5}`);
        assetItem.duration = duration5;
        this.updateSchedule();
      }
    };
    player.on(Events.LEVEL_UPDATED, (event, {
      details
    }) => updateAssetPlayerDetails(details));
    player.on(Events.LEVEL_PTS_UPDATED, (event, {
      details
    }) => updateAssetPlayerDetails(details));
    const onBufferCodecs = (event, data) => {
      const inQueuPlayer = this.getAssetPlayer(assetId);
      if (inQueuPlayer && data.tracks) {
        inQueuPlayer.off(Events.BUFFER_CODECS, onBufferCodecs);
        inQueuPlayer.tracks = data.tracks;
        const media = this.primaryMedia;
        if (this.bufferingAsset === inQueuPlayer.assetItem && media && !inQueuPlayer.media) {
          this.bufferAssetPlayer(inQueuPlayer, media);
        }
      }
    };
    player.on(Events.BUFFER_CODECS, onBufferCodecs);
    const bufferedToEnd = () => {
      var _this$schedule$items2;
      const inQueuPlayer = this.getAssetPlayer(assetId);
      this.log(`buffered to end of asset ${inQueuPlayer}`);
      if (!inQueuPlayer) {
        return;
      }
      const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
      const assetListIndex2 = interstitial.findAssetIndex(assetItem);
      const nextAssetIndex = assetListIndex2 + 1;
      const item = (_this$schedule$items2 = this.schedule.items) == null ? void 0 : _this$schedule$items2[scheduleIndex];
      if (this.isInterstitial(item)) {
        if (assetListIndex2 !== -1 && !interstitial.isAssetPastPlayoutLimit(nextAssetIndex) && !interstitial.assetList[nextAssetIndex].error) {
          this.bufferedToItem(item, nextAssetIndex);
        } else {
          var _this$schedule$items3;
          const nextItem = (_this$schedule$items3 = this.schedule.items) == null ? void 0 : _this$schedule$items3[scheduleIndex + 1];
          if (nextItem) {
            this.bufferedToItem(nextItem);
          }
        }
      }
    };
    player.on(Events.BUFFERED_TO_END, bufferedToEnd);
    const endedWithAssetIndex = (assetIndex) => {
      return () => {
        const inQueuPlayer = this.getAssetPlayer(assetId);
        if (!inQueuPlayer) {
          return;
        }
        this.shouldPlay = true;
        const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
        this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetIndex);
      };
    };
    player.once(Events.MEDIA_ENDED, endedWithAssetIndex(assetListIndex));
    player.once(Events.PLAYOUT_LIMIT_REACHED, endedWithAssetIndex(Infinity));
    player.on(Events.ERROR, (event, data) => {
      const inQueuPlayer = this.getAssetPlayer(assetId);
      if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
        if (inQueuPlayer != null && inQueuPlayer.media) {
          const assetCurrentTime = inQueuPlayer.currentTime;
          const distanceFromEnd = inQueuPlayer.duration - assetCurrentTime;
          if (assetCurrentTime && interstitial.appendInPlace && distanceFromEnd / inQueuPlayer.media.playbackRate < 0.5) {
            this.log(`Advancing buffer past end of asset ${assetId} ${interstitial} at ${inQueuPlayer.media.currentTime}`);
            bufferedToEnd();
          } else {
            this.warn(`Stalled at ${assetCurrentTime} of ${assetCurrentTime + distanceFromEnd} in asset ${assetId} ${interstitial}`);
            this.onTimeupdate();
            this.checkBuffer(true);
          }
        }
        return;
      }
      this.handleAssetItemError(data, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, `Asset player error ${data.error} ${interstitial}`);
    });
    player.on(Events.DESTROYING, () => {
      const inQueuPlayer = this.getAssetPlayer(assetId);
      if (!inQueuPlayer) {
        return;
      }
      const error = new Error(`Asset player destroyed unexpectedly ${assetId}`);
      const errorData = {
        fatal: true,
        type: ErrorTypes.OTHER_ERROR,
        details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
        error
      };
      this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
    });
    this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED, {
      asset: assetItem,
      assetListIndex,
      event: interstitial,
      player
    });
    return player;
  }
  clearInterstitial(interstitial, toSegment) {
    interstitial.assetList.forEach((asset) => {
      this.clearAssetPlayer(asset.identifier, toSegment);
    });
    interstitial.reset();
  }
  clearAssetPlayer(assetId, toSegment) {
    const playerIndex = this.getAssetPlayerQueueIndex(assetId);
    if (playerIndex !== -1) {
      this.log(`clearAssetPlayer "${assetId}" toSegment: ${toSegment ? segmentToString(toSegment) : toSegment}`);
      const player = this.playerQueue[playerIndex];
      this.transferMediaFromPlayer(player, toSegment);
      this.playerQueue.splice(playerIndex, 1);
      player.destroy();
    }
  }
  emptyPlayerQueue() {
    let player;
    while (player = this.playerQueue.pop()) {
      player.destroy();
    }
    this.playerQueue = [];
  }
  startAssetPlayer(player, assetListIndex, scheduleItems, scheduleIndex, media) {
    const {
      interstitial,
      assetItem,
      assetId
    } = player;
    const assetListLength = interstitial.assetList.length;
    const playingAsset = this.playingAsset;
    this.endedAsset = null;
    this.playingAsset = assetItem;
    if (!playingAsset || playingAsset.identifier !== assetId) {
      if (playingAsset) {
        this.clearAssetPlayer(playingAsset.identifier, scheduleItems[scheduleIndex]);
        delete playingAsset.error;
      }
      this.log(`INTERSTITIAL_ASSET_STARTED ${assetListIndex + 1}/${assetListLength} ${player}`);
      this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED, {
        asset: assetItem,
        assetListIndex,
        event: interstitial,
        schedule: scheduleItems.slice(0),
        scheduleIndex,
        player
      });
    }
    this.bufferAssetPlayer(player, media);
  }
  bufferAssetPlayer(player, media) {
    var _this$schedule$items4, _this$detachedData5;
    const {
      interstitial,
      assetItem,
      assetId
    } = player;
    const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
    const item = (_this$schedule$items4 = this.schedule.items) == null ? void 0 : _this$schedule$items4[scheduleIndex];
    if (!item) {
      return;
    }
    this.setBufferingItem(item);
    this.bufferingAsset = assetItem;
    const bufferingPlayer = this.getBufferingPlayer();
    if (bufferingPlayer === player) {
      return;
    }
    const appendInPlaceNext = interstitial.appendInPlace;
    if (appendInPlaceNext && (bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial.appendInPlace) === false) {
      return;
    }
    const activeTracks = (bufferingPlayer == null ? void 0 : bufferingPlayer.tracks) || ((_this$detachedData5 = this.detachedData) == null ? void 0 : _this$detachedData5.tracks) || this.requiredTracks;
    if (appendInPlaceNext && assetItem !== this.playingAsset) {
      if (!player.tracks) {
        return;
      }
      if (activeTracks && !isCompatibleTrackChange(activeTracks, player.tracks)) {
        const error = new Error(`Asset "${assetId}" SourceBuffer tracks ('${Object.keys(player.tracks)}') are not compatible with primary content tracks ('${Object.keys(activeTracks)}')`);
        const errorData = {
          fatal: true,
          type: ErrorTypes.OTHER_ERROR,
          details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
          error
        };
        const assetListIndex = interstitial.findAssetIndex(assetItem);
        this.handleAssetItemError(errorData, interstitial, scheduleIndex, assetListIndex, error.message);
        return;
      }
    }
    this.transferMediaTo(player, media);
  }
  handleAssetItemError(data, interstitial, scheduleIndex, assetListIndex, errorMessage) {
    if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
      return;
    }
    const assetItem = interstitial.assetList[assetListIndex] || null;
    let player = null;
    if (assetItem) {
      const playerIndex = this.getAssetPlayerQueueIndex(assetItem.identifier);
      player = this.playerQueue[playerIndex] || null;
    }
    const items = this.schedule.items;
    const interstitialAssetError = _extends({}, data, {
      fatal: false,
      errorAction: createDoNothingErrorAction(true),
      asset: assetItem,
      assetListIndex,
      event: interstitial,
      schedule: items,
      scheduleIndex,
      player
    });
    this.warn(`Asset item error: ${data.error}`);
    this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR, interstitialAssetError);
    if (!data.fatal) {
      return;
    }
    const error = new Error(errorMessage);
    if (assetItem) {
      if (this.playingAsset !== assetItem) {
        this.clearAssetPlayer(assetItem.identifier, null);
      }
      assetItem.error = error;
    }
    if (!interstitial.assetList.some((asset) => !asset.error)) {
      interstitial.error = error;
    } else if (interstitial.appendInPlace) {
      interstitial.error = error;
    }
    this.primaryFallback(interstitial);
  }
  primaryFallback(interstitial) {
    const flushStart = interstitial.timelineStart;
    const playingItem = this.effectivePlayingItem;
    this.updateSchedule();
    if (playingItem) {
      this.log(`Fallback to primary from event "${interstitial.identifier}" start: ${flushStart} pos: ${this.timelinePos} playing: ${playingItem ? segmentToString(playingItem) : "<none>"} error: ${interstitial.error}`);
      if (interstitial.appendInPlace) {
        this.attachPrimary(flushStart, null);
        this.flushFrontBuffer(flushStart);
      }
      let timelinePos = this.timelinePos;
      if (timelinePos === -1) {
        timelinePos = this.hls.startPosition;
      }
      const newPlayingItem = this.updateItem(playingItem, timelinePos);
      if (!this.itemsMatch(playingItem, newPlayingItem)) {
        const scheduleIndex = this.schedule.findItemIndexAtTime(timelinePos);
        this.setSchedulePosition(scheduleIndex);
      } else {
        this.clearInterstitial(interstitial, null);
      }
    } else {
      this.checkStart();
    }
  }
  // Asset List loading
  onAssetListLoaded(event, data) {
    var _this$bufferingItem2;
    const interstitial = data.event;
    const interstitialId = interstitial.identifier;
    const assets = data.assetListResponse.ASSETS;
    if (!this.schedule.hasEvent(interstitialId)) {
      return;
    }
    const eventStart = interstitial.timelineStart;
    const previousDuration = interstitial.duration;
    let sumDuration = 0;
    assets.forEach((asset, assetListIndex) => {
      const duration5 = parseFloat(asset.DURATION);
      this.createAsset(interstitial, assetListIndex, sumDuration, eventStart + sumDuration, duration5, asset.URI);
      sumDuration += duration5;
    });
    interstitial.duration = sumDuration;
    this.log(`Loaded asset-list with duration: ${sumDuration} (was: ${previousDuration}) ${interstitial}`);
    const waitingItem = this.waitingItem;
    const waitingForItem = (waitingItem == null ? void 0 : waitingItem.event.identifier) === interstitialId;
    this.updateSchedule();
    const bufferingEvent = (_this$bufferingItem2 = this.bufferingItem) == null ? void 0 : _this$bufferingItem2.event;
    if (waitingForItem) {
      var _this$schedule$items5;
      const scheduleIndex = this.schedule.findEventIndex(interstitialId);
      const item = (_this$schedule$items5 = this.schedule.items) == null ? void 0 : _this$schedule$items5[scheduleIndex];
      if (item) {
        if (!this.playingItem && this.timelinePos > item.end) {
          const index = this.schedule.findItemIndexAtTime(this.timelinePos);
          if (index !== scheduleIndex) {
            interstitial.error = new Error(`Interstitial no longer within playback range ${this.timelinePos} ${interstitial}`);
            this.primaryFallback(interstitial);
            return;
          }
        }
        this.setBufferingItem(item);
      }
      this.setSchedulePosition(scheduleIndex);
    } else if ((bufferingEvent == null ? void 0 : bufferingEvent.identifier) === interstitialId && bufferingEvent.appendInPlace) {
      const assetItem = interstitial.assetList[0];
      const player = this.getAssetPlayer(assetItem.identifier);
      const media = this.primaryMedia;
      if (assetItem && player && media) {
        this.bufferAssetPlayer(player, media);
      }
    }
  }
  onError(event, data) {
    switch (data.details) {
      case ErrorDetails.ASSET_LIST_PARSING_ERROR:
      case ErrorDetails.ASSET_LIST_LOAD_ERROR:
      case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT: {
        const interstitial = data.interstitial;
        if (interstitial) {
          this.primaryFallback(interstitial);
        }
        break;
      }
      case ErrorDetails.BUFFER_STALLED_ERROR: {
        this.onTimeupdate();
        this.checkBuffer(true);
        break;
      }
    }
  }
};
var TICK_INTERVAL$2 = 500;
var SubtitleStreamController = class extends BaseStreamController {
  constructor(hls, fragmentTracker, keyLoader) {
    super(hls, fragmentTracker, keyLoader, "subtitle-stream-controller", PlaylistLevelType.SUBTITLE);
    this.currentTrackId = -1;
    this.tracksBuffered = [];
    this.mainDetails = null;
    this.registerListeners();
  }
  onHandlerDestroying() {
    this.unregisterListeners();
    super.onHandlerDestroying();
    this.mainDetails = null;
  }
  registerListeners() {
    super.registerListeners();
    const {
      hls
    } = this;
    hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
    hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
    hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
    hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
    hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
    hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  }
  unregisterListeners() {
    super.unregisterListeners();
    const {
      hls
    } = this;
    hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
    hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
    hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
    hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
    hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
    hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  }
  startLoad(startPosition, skipSeekToStartPosition) {
    this.stopLoad();
    this.state = State.IDLE;
    this.setInterval(TICK_INTERVAL$2);
    this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
    this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
    this.tick();
  }
  onManifestLoading() {
    super.onManifestLoading();
    this.mainDetails = null;
  }
  onMediaDetaching(event, data) {
    this.tracksBuffered = [];
    super.onMediaDetaching(event, data);
  }
  onLevelLoaded(event, data) {
    this.mainDetails = data.details;
  }
  onSubtitleFragProcessed(event, data) {
    const {
      frag,
      success
    } = data;
    if (isMediaFragment(frag)) {
      this.fragPrevious = frag;
    }
    this.state = State.IDLE;
    if (!success) {
      return;
    }
    const buffered = this.tracksBuffered[this.currentTrackId];
    if (!buffered) {
      return;
    }
    let timeRange;
    const fragStart = frag.start;
    for (let i = 0; i < buffered.length; i++) {
      if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
        timeRange = buffered[i];
        break;
      }
    }
    const fragEnd = frag.start + frag.duration;
    if (timeRange) {
      timeRange.end = fragEnd;
    } else {
      timeRange = {
        start: fragStart,
        end: fragEnd
      };
      buffered.push(timeRange);
    }
    this.fragmentTracker.fragBuffered(frag);
    this.fragBufferedComplete(frag, null);
    if (this.media) {
      this.tick();
    }
  }
  onBufferFlushing(event, data) {
    const {
      startOffset,
      endOffset
    } = data;
    if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
      const endOffsetSubtitles = endOffset - 1;
      if (endOffsetSubtitles <= 0) {
        return;
      }
      data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
      this.tracksBuffered.forEach((buffered) => {
        for (let i = 0; i < buffered.length; ) {
          if (buffered[i].end <= endOffsetSubtitles) {
            buffered.shift();
            continue;
          } else if (buffered[i].start < endOffsetSubtitles) {
            buffered[i].start = endOffsetSubtitles;
          } else {
            break;
          }
          i++;
        }
      });
      this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE);
    }
  }
  // If something goes wrong, proceed to next frag, if we were processing one.
  onError(event, data) {
    const frag = data.frag;
    if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) {
      if (data.details === ErrorDetails.FRAG_GAP) {
        this.fragmentTracker.fragBuffered(frag, true);
      }
      if (this.fragCurrent) {
        this.fragCurrent.abortRequests();
      }
      if (this.state !== State.STOPPED) {
        this.state = State.IDLE;
      }
    }
  }
  // Got all new subtitle levels.
  onSubtitleTracksUpdated(event, {
    subtitleTracks
  }) {
    if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) {
      this.levels = subtitleTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
      return;
    }
    this.tracksBuffered = [];
    this.levels = subtitleTracks.map((mediaPlaylist) => {
      const level = new Level(mediaPlaylist);
      this.tracksBuffered[level.id] = [];
      return level;
    });
    this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE);
    this.fragPrevious = null;
    this.mediaBuffer = null;
  }
  onSubtitleTrackSwitch(event, data) {
    var _this$levels;
    this.currentTrackId = data.id;
    if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) {
      this.clearInterval();
      return;
    }
    const currentTrack = this.levels[this.currentTrackId];
    if (currentTrack != null && currentTrack.details) {
      this.mediaBuffer = this.mediaBufferTimeRanges;
    } else {
      this.mediaBuffer = null;
    }
    if (currentTrack && this.state !== State.STOPPED) {
      this.setInterval(TICK_INTERVAL$2);
    }
  }
  // Got a new set of subtitle fragments.
  onSubtitleTrackLoaded(event, data) {
    var _track$details;
    const {
      currentTrackId,
      levels
    } = this;
    const {
      details: newDetails,
      id: trackId
    } = data;
    if (!levels) {
      this.warn(`Subtitle tracks were reset while loading level ${trackId}`);
      return;
    }
    const track = levels[trackId];
    if (trackId >= levels.length || !track) {
      return;
    }
    this.log(`Subtitle track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
    this.mediaBuffer = this.mediaBufferTimeRanges;
    let sliding = 0;
    if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {
      const mainDetails = this.mainDetails;
      if (newDetails.deltaUpdateFailed || !mainDetails) {
        return;
      }
      const mainSlidingStartFragment = mainDetails.fragments[0];
      if (!track.details) {
        if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
          alignMediaPlaylistByPDT(newDetails, mainDetails);
          sliding = newDetails.fragmentStart;
        } else if (mainSlidingStartFragment) {
          sliding = mainSlidingStartFragment.start;
          addSliding(newDetails, sliding);
        }
      } else {
        var _this$levelLastLoaded;
        sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
        if (sliding === 0 && mainSlidingStartFragment) {
          sliding = mainSlidingStartFragment.start;
          addSliding(newDetails, sliding);
        }
      }
    }
    track.details = newDetails;
    this.levelLastLoaded = track;
    if (trackId !== currentTrackId) {
      return;
    }
    this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED, {
      details: newDetails,
      id: trackId,
      groupId: data.groupId
    });
    this.tick();
    if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) {
      const foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0);
      if (!foundFrag) {
        this.warn("Subtitle playlist not aligned with playback");
        track.details = void 0;
      }
    }
  }
  _handleFragmentLoadComplete(fragLoadedData) {
    const {
      frag,
      payload
    } = fragLoadedData;
    const decryptData = frag.decryptdata;
    const hls = this.hls;
    if (this.fragContextChanged(frag)) {
      return;
    }
    if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
      const startTime = performance.now();
      this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
        hls.trigger(Events.ERROR, {
          type: ErrorTypes.MEDIA_ERROR,
          details: ErrorDetails.FRAG_DECRYPT_ERROR,
          fatal: false,
          error: err,
          reason: err.message,
          frag
        });
        throw err;
      }).then((decryptedData) => {
        const endTime = performance.now();
        hls.trigger(Events.FRAG_DECRYPTED, {
          frag,
          payload: decryptedData,
          stats: {
            tstart: startTime,
            tdecrypt: endTime
          }
        });
      }).catch((err) => {
        this.warn(`${err.name}: ${err.message}`);
        this.state = State.IDLE;
      });
    }
  }
  doTick() {
    if (!this.media) {
      this.state = State.IDLE;
      return;
    }
    if (this.state === State.IDLE) {
      const {
        currentTrackId,
        levels
      } = this;
      const track = levels == null ? void 0 : levels[currentTrackId];
      if (!track || !levels.length || !track.details) {
        return;
      }
      if (this.waitForLive(track)) {
        return;
      }
      const {
        config
      } = this;
      const currentTime = this.getLoadPosition();
      const bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config.maxBufferHole);
      const {
        end: targetBufferTime,
        len: bufferLen
      } = bufferedInfo;
      const trackDetails = track.details;
      const maxBufLen = this.hls.maxBufferLength + trackDetails.levelTargetDuration;
      if (bufferLen > maxBufLen) {
        return;
      }
      const fragments = trackDetails.fragments;
      const fragLen = fragments.length;
      const end = trackDetails.edge;
      let foundFrag = null;
      const fragPrevious = this.fragPrevious;
      if (targetBufferTime < end) {
        const tolerance = config.maxFragLookUpTolerance;
        const lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance;
        foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance);
        if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
          foundFrag = fragments[0];
        }
      } else {
        foundFrag = fragments[fragLen - 1];
      }
      foundFrag = this.filterReplacedPrimary(foundFrag, track.details);
      if (!foundFrag) {
        return;
      }
      const curSNIdx = foundFrag.sn - trackDetails.startSN;
      const prevFrag = fragments[curSNIdx - 1];
      if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) {
        foundFrag = prevFrag;
      }
      if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
        const fragToLoad = this.mapToInitFragWhenRequired(foundFrag);
        if (fragToLoad) {
          this.loadFragment(fragToLoad, track, targetBufferTime);
        }
      }
    }
  }
  loadFragment(frag, level, targetBufferTime) {
    if (!isMediaFragment(frag)) {
      this._loadInitSegment(frag, level);
    } else {
      super.loadFragment(frag, level, targetBufferTime);
    }
  }
  get mediaBufferTimeRanges() {
    return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []);
  }
};
var BufferableInstance = class {
  constructor(timeranges) {
    this.buffered = void 0;
    const getRange2 = (name, index, length) => {
      index = index >>> 0;
      if (index > length - 1) {
        throw new DOMException(`Failed to execute '${name}' on 'TimeRanges': The index provided (${index}) is greater than the maximum bound (${length})`);
      }
      return timeranges[index][name];
    };
    this.buffered = {
      get length() {
        return timeranges.length;
      },
      end(index) {
        return getRange2("end", index, timeranges.length);
      },
      start(index) {
        return getRange2("start", index, timeranges.length);
      }
    };
  }
};
var specialCea608CharsCodes = {
  42: 225,
  // lowercase a, acute accent
  92: 233,
  // lowercase e, acute accent
  94: 237,
  // lowercase i, acute accent
  95: 243,
  // lowercase o, acute accent
  96: 250,
  // lowercase u, acute accent
  123: 231,
  // lowercase c with cedilla
  124: 247,
  // division symbol
  125: 209,
  // uppercase N tilde
  126: 241,
  // lowercase n tilde
  127: 9608,
  // Full block
  // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  128: 174,
  // Registered symbol (R)
  129: 176,
  // degree sign
  130: 189,
  // 1/2 symbol
  131: 191,
  // Inverted (open) question mark
  132: 8482,
  // Trademark symbol (TM)
  133: 162,
  // Cents symbol
  134: 163,
  // Pounds sterling
  135: 9834,
  // Music 8'th note
  136: 224,
  // lowercase a, grave accent
  137: 32,
  // transparent space (regular)
  138: 232,
  // lowercase e, grave accent
  139: 226,
  // lowercase a, circumflex accent
  140: 234,
  // lowercase e, circumflex accent
  141: 238,
  // lowercase i, circumflex accent
  142: 244,
  // lowercase o, circumflex accent
  143: 251,
  // lowercase u, circumflex accent
  // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  144: 193,
  // capital letter A with acute
  145: 201,
  // capital letter E with acute
  146: 211,
  // capital letter O with acute
  147: 218,
  // capital letter U with acute
  148: 220,
  // capital letter U with diaresis
  149: 252,
  // lowercase letter U with diaeresis
  150: 8216,
  // opening single quote
  151: 161,
  // inverted exclamation mark
  152: 42,
  // asterisk
  153: 8217,
  // closing single quote
  154: 9473,
  // box drawings heavy horizontal
  155: 169,
  // copyright sign
  156: 8480,
  // Service mark
  157: 8226,
  // (round) bullet
  158: 8220,
  // Left double quotation mark
  159: 8221,
  // Right double quotation mark
  160: 192,
  // uppercase A, grave accent
  161: 194,
  // uppercase A, circumflex
  162: 199,
  // uppercase C with cedilla
  163: 200,
  // uppercase E, grave accent
  164: 202,
  // uppercase E, circumflex
  165: 203,
  // capital letter E with diaresis
  166: 235,
  // lowercase letter e with diaresis
  167: 206,
  // uppercase I, circumflex
  168: 207,
  // uppercase I, with diaresis
  169: 239,
  // lowercase i, with diaresis
  170: 212,
  // uppercase O, circumflex
  171: 217,
  // uppercase U, grave accent
  172: 249,
  // lowercase u, grave accent
  173: 219,
  // uppercase U, circumflex
  174: 171,
  // left-pointing double angle quotation mark
  175: 187,
  // right-pointing double angle quotation mark
  // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  176: 195,
  // Uppercase A, tilde
  177: 227,
  // Lowercase a, tilde
  178: 205,
  // Uppercase I, acute accent
  179: 204,
  // Uppercase I, grave accent
  180: 236,
  // Lowercase i, grave accent
  181: 210,
  // Uppercase O, grave accent
  182: 242,
  // Lowercase o, grave accent
  183: 213,
  // Uppercase O, tilde
  184: 245,
  // Lowercase o, tilde
  185: 123,
  // Open curly brace
  186: 125,
  // Closing curly brace
  187: 92,
  // Backslash
  188: 94,
  // Caret
  189: 95,
  // Underscore
  190: 124,
  // Pipe (vertical line)
  191: 8764,
  // Tilde operator
  192: 196,
  // Uppercase A, umlaut
  193: 228,
  // Lowercase A, umlaut
  194: 214,
  // Uppercase O, umlaut
  195: 246,
  // Lowercase o, umlaut
  196: 223,
  // Esszett (sharp S)
  197: 165,
  // Yen symbol
  198: 164,
  // Generic currency sign
  199: 9475,
  // Box drawings heavy vertical
  200: 197,
  // Uppercase A, ring
  201: 229,
  // Lowercase A, ring
  202: 216,
  // Uppercase O, stroke
  203: 248,
  // Lowercase o, strok
  204: 9487,
  // Box drawings heavy down and right
  205: 9491,
  // Box drawings heavy down and left
  206: 9495,
  // Box drawings heavy up and right
  207: 9499
  // Box drawings heavy up and left
};
var getCharForByte = (byte) => String.fromCharCode(specialCea608CharsCodes[byte] || byte);
var NR_ROWS = 15;
var NR_COLS = 100;
var rowsLowCh1 = {
  17: 1,
  18: 3,
  21: 5,
  22: 7,
  23: 9,
  16: 11,
  19: 12,
  20: 14
};
var rowsHighCh1 = {
  17: 2,
  18: 4,
  21: 6,
  22: 8,
  23: 10,
  19: 13,
  20: 15
};
var rowsLowCh2 = {
  25: 1,
  26: 3,
  29: 5,
  30: 7,
  31: 9,
  24: 11,
  27: 12,
  28: 14
};
var rowsHighCh2 = {
  25: 2,
  26: 4,
  29: 6,
  30: 8,
  31: 10,
  27: 13,
  28: 15
};
var backgroundColors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "black", "transparent"];
var CaptionsLogger = class {
  constructor() {
    this.time = null;
    this.verboseLevel = 0;
  }
  log(severity, msg) {
    if (this.verboseLevel >= severity) {
      const m = typeof msg === "function" ? msg() : msg;
      logger.log(`${this.time} [${severity}] ${m}`);
    }
  }
};
var numArrayToHexArray = function numArrayToHexArray2(numArray) {
  const hexArray = [];
  for (let j = 0; j < numArray.length; j++) {
    hexArray.push(numArray[j].toString(16));
  }
  return hexArray;
};
var PenState = class {
  constructor() {
    this.foreground = "white";
    this.underline = false;
    this.italics = false;
    this.background = "black";
    this.flash = false;
  }
  reset() {
    this.foreground = "white";
    this.underline = false;
    this.italics = false;
    this.background = "black";
    this.flash = false;
  }
  setStyles(styles) {
    const attribs = ["foreground", "underline", "italics", "background", "flash"];
    for (let i = 0; i < attribs.length; i++) {
      const style = attribs[i];
      if (styles.hasOwnProperty(style)) {
        this[style] = styles[style];
      }
    }
  }
  isDefault() {
    return this.foreground === "white" && !this.underline && !this.italics && this.background === "black" && !this.flash;
  }
  equals(other) {
    return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  }
  copy(newPenState) {
    this.foreground = newPenState.foreground;
    this.underline = newPenState.underline;
    this.italics = newPenState.italics;
    this.background = newPenState.background;
    this.flash = newPenState.flash;
  }
  toString() {
    return "color=" + this.foreground + ", underline=" + this.underline + ", italics=" + this.italics + ", background=" + this.background + ", flash=" + this.flash;
  }
};
var StyledUnicodeChar = class {
  constructor() {
    this.uchar = " ";
    this.penState = new PenState();
  }
  reset() {
    this.uchar = " ";
    this.penState.reset();
  }
  setChar(uchar, newPenState) {
    this.uchar = uchar;
    this.penState.copy(newPenState);
  }
  setPenState(newPenState) {
    this.penState.copy(newPenState);
  }
  equals(other) {
    return this.uchar === other.uchar && this.penState.equals(other.penState);
  }
  copy(newChar) {
    this.uchar = newChar.uchar;
    this.penState.copy(newChar.penState);
  }
  isEmpty() {
    return this.uchar === " " && this.penState.isDefault();
  }
};
var Row = class {
  constructor(logger4) {
    this.chars = [];
    this.pos = 0;
    this.currPenState = new PenState();
    this.cueStartTime = null;
    this.logger = void 0;
    for (let i = 0; i < NR_COLS; i++) {
      this.chars.push(new StyledUnicodeChar());
    }
    this.logger = logger4;
  }
  equals(other) {
    for (let i = 0; i < NR_COLS; i++) {
      if (!this.chars[i].equals(other.chars[i])) {
        return false;
      }
    }
    return true;
  }
  copy(other) {
    for (let i = 0; i < NR_COLS; i++) {
      this.chars[i].copy(other.chars[i]);
    }
  }
  isEmpty() {
    let empty = true;
    for (let i = 0; i < NR_COLS; i++) {
      if (!this.chars[i].isEmpty()) {
        empty = false;
        break;
      }
    }
    return empty;
  }
  /**
   *  Set the cursor to a valid column.
   */
  setCursor(absPos) {
    if (this.pos !== absPos) {
      this.pos = absPos;
    }
    if (this.pos < 0) {
      this.logger.log(3, "Negative cursor position " + this.pos);
      this.pos = 0;
    } else if (this.pos > NR_COLS) {
      this.logger.log(3, "Too large cursor position " + this.pos);
      this.pos = NR_COLS;
    }
  }
  /**
   * Move the cursor relative to current position.
   */
  moveCursor(relPos) {
    const newPos = this.pos + relPos;
    if (relPos > 1) {
      for (let i = this.pos + 1; i < newPos + 1; i++) {
        this.chars[i].setPenState(this.currPenState);
      }
    }
    this.setCursor(newPos);
  }
  /**
   * Backspace, move one step back and clear character.
   */
  backSpace() {
    this.moveCursor(-1);
    this.chars[this.pos].setChar(" ", this.currPenState);
  }
  insertChar(byte) {
    if (byte >= 144) {
      this.backSpace();
    }
    const char = getCharForByte(byte);
    if (this.pos >= NR_COLS) {
      this.logger.log(0, () => "Cannot insert " + byte.toString(16) + " (" + char + ") at position " + this.pos + ". Skipping it!");
      return;
    }
    this.chars[this.pos].setChar(char, this.currPenState);
    this.moveCursor(1);
  }
  clearFromPos(startPos) {
    let i;
    for (i = startPos; i < NR_COLS; i++) {
      this.chars[i].reset();
    }
  }
  clear() {
    this.clearFromPos(0);
    this.pos = 0;
    this.currPenState.reset();
  }
  clearToEndOfRow() {
    this.clearFromPos(this.pos);
  }
  getTextString() {
    const chars = [];
    let empty = true;
    for (let i = 0; i < NR_COLS; i++) {
      const char = this.chars[i].uchar;
      if (char !== " ") {
        empty = false;
      }
      chars.push(char);
    }
    if (empty) {
      return "";
    } else {
      return chars.join("");
    }
  }
  setPenStyles(styles) {
    this.currPenState.setStyles(styles);
    const currChar = this.chars[this.pos];
    currChar.setPenState(this.currPenState);
  }
};
var CaptionScreen = class {
  constructor(logger4) {
    this.rows = [];
    this.currRow = NR_ROWS - 1;
    this.nrRollUpRows = null;
    this.lastOutputScreen = null;
    this.logger = void 0;
    for (let i = 0; i < NR_ROWS; i++) {
      this.rows.push(new Row(logger4));
    }
    this.logger = logger4;
  }
  reset() {
    for (let i = 0; i < NR_ROWS; i++) {
      this.rows[i].clear();
    }
    this.currRow = NR_ROWS - 1;
  }
  equals(other) {
    let equal = true;
    for (let i = 0; i < NR_ROWS; i++) {
      if (!this.rows[i].equals(other.rows[i])) {
        equal = false;
        break;
      }
    }
    return equal;
  }
  copy(other) {
    for (let i = 0; i < NR_ROWS; i++) {
      this.rows[i].copy(other.rows[i]);
    }
  }
  isEmpty() {
    let empty = true;
    for (let i = 0; i < NR_ROWS; i++) {
      if (!this.rows[i].isEmpty()) {
        empty = false;
        break;
      }
    }
    return empty;
  }
  backSpace() {
    const row = this.rows[this.currRow];
    row.backSpace();
  }
  clearToEndOfRow() {
    const row = this.rows[this.currRow];
    row.clearToEndOfRow();
  }
  /**
   * Insert a character (without styling) in the current row.
   */
  insertChar(char) {
    const row = this.rows[this.currRow];
    row.insertChar(char);
  }
  setPen(styles) {
    const row = this.rows[this.currRow];
    row.setPenStyles(styles);
  }
  moveCursor(relPos) {
    const row = this.rows[this.currRow];
    row.moveCursor(relPos);
  }
  setCursor(absPos) {
    this.logger.log(2, "setCursor: " + absPos);
    const row = this.rows[this.currRow];
    row.setCursor(absPos);
  }
  setPAC(pacData) {
    this.logger.log(2, () => "pacData = " + stringify(pacData));
    let newRow = pacData.row - 1;
    if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
      newRow = this.nrRollUpRows - 1;
    }
    if (this.nrRollUpRows && this.currRow !== newRow) {
      for (let i = 0; i < NR_ROWS; i++) {
        this.rows[i].clear();
      }
      const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
      const lastOutputScreen = this.lastOutputScreen;
      if (lastOutputScreen) {
        const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
        const time = this.logger.time;
        if (prevLineTime !== null && time !== null && prevLineTime < time) {
          for (let i = 0; i < this.nrRollUpRows; i++) {
            this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);
          }
        }
      }
    }
    this.currRow = newRow;
    const row = this.rows[this.currRow];
    if (pacData.indent !== null) {
      const indent = pacData.indent;
      const prevPos = Math.max(indent - 1, 0);
      row.setCursor(pacData.indent);
      pacData.color = row.chars[prevPos].penState.foreground;
    }
    const styles = {
      foreground: pacData.color,
      underline: pacData.underline,
      italics: pacData.italics,
      background: "black",
      flash: false
    };
    this.setPen(styles);
  }
  /**
   * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
   */
  setBkgData(bkgData) {
    this.logger.log(2, () => "bkgData = " + stringify(bkgData));
    this.backSpace();
    this.setPen(bkgData);
    this.insertChar(32);
  }
  setRollUpRows(nrRows) {
    this.nrRollUpRows = nrRows;
  }
  rollUp() {
    if (this.nrRollUpRows === null) {
      this.logger.log(3, "roll_up but nrRollUpRows not set yet");
      return;
    }
    this.logger.log(1, () => this.getDisplayText());
    const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
    const topRow = this.rows.splice(topRowIndex, 1)[0];
    topRow.clear();
    this.rows.splice(this.currRow, 0, topRow);
    this.logger.log(2, "Rolling up");
  }
  /**
   * Get all non-empty rows with as unicode text.
   */
  getDisplayText(asOneRow) {
    asOneRow = asOneRow || false;
    const displayText = [];
    let text = "";
    let rowNr = -1;
    for (let i = 0; i < NR_ROWS; i++) {
      const rowText = this.rows[i].getTextString();
      if (rowText) {
        rowNr = i + 1;
        if (asOneRow) {
          displayText.push("Row " + rowNr + ": '" + rowText + "'");
        } else {
          displayText.push(rowText.trim());
        }
      }
    }
    if (displayText.length > 0) {
      if (asOneRow) {
        text = "[" + displayText.join(" | ") + "]";
      } else {
        text = displayText.join("\n");
      }
    }
    return text;
  }
  getTextAndFormat() {
    return this.rows;
  }
};
var Cea608Channel = class {
  constructor(channelNumber, outputFilter, logger4) {
    this.chNr = void 0;
    this.outputFilter = void 0;
    this.mode = void 0;
    this.verbose = void 0;
    this.displayedMemory = void 0;
    this.nonDisplayedMemory = void 0;
    this.lastOutputScreen = void 0;
    this.currRollUpRow = void 0;
    this.writeScreen = void 0;
    this.cueStartTime = void 0;
    this.logger = void 0;
    this.chNr = channelNumber;
    this.outputFilter = outputFilter;
    this.mode = null;
    this.verbose = 0;
    this.displayedMemory = new CaptionScreen(logger4);
    this.nonDisplayedMemory = new CaptionScreen(logger4);
    this.lastOutputScreen = new CaptionScreen(logger4);
    this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
    this.writeScreen = this.displayedMemory;
    this.mode = null;
    this.cueStartTime = null;
    this.logger = logger4;
  }
  reset() {
    this.mode = null;
    this.displayedMemory.reset();
    this.nonDisplayedMemory.reset();
    this.lastOutputScreen.reset();
    this.outputFilter.reset();
    this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
    this.writeScreen = this.displayedMemory;
    this.mode = null;
    this.cueStartTime = null;
  }
  getHandler() {
    return this.outputFilter;
  }
  setHandler(newHandler) {
    this.outputFilter = newHandler;
  }
  setPAC(pacData) {
    this.writeScreen.setPAC(pacData);
  }
  setBkgData(bkgData) {
    this.writeScreen.setBkgData(bkgData);
  }
  setMode(newMode) {
    if (newMode === this.mode) {
      return;
    }
    this.mode = newMode;
    this.logger.log(2, () => "MODE=" + newMode);
    if (this.mode === "MODE_POP-ON") {
      this.writeScreen = this.nonDisplayedMemory;
    } else {
      this.writeScreen = this.displayedMemory;
      this.writeScreen.reset();
    }
    if (this.mode !== "MODE_ROLL-UP") {
      this.displayedMemory.nrRollUpRows = null;
      this.nonDisplayedMemory.nrRollUpRows = null;
    }
    this.mode = newMode;
  }
  insertChars(chars) {
    for (let i = 0; i < chars.length; i++) {
      this.writeScreen.insertChar(chars[i]);
    }
    const screen2 = this.writeScreen === this.displayedMemory ? "DISP" : "NON_DISP";
    this.logger.log(2, () => screen2 + ": " + this.writeScreen.getDisplayText(true));
    if (this.mode === "MODE_PAINT-ON" || this.mode === "MODE_ROLL-UP") {
      this.logger.log(1, () => "DISPLAYED: " + this.displayedMemory.getDisplayText(true));
      this.outputDataUpdate();
    }
  }
  ccRCL() {
    this.logger.log(2, "RCL - Resume Caption Loading");
    this.setMode("MODE_POP-ON");
  }
  ccBS() {
    this.logger.log(2, "BS - BackSpace");
    if (this.mode === "MODE_TEXT") {
      return;
    }
    this.writeScreen.backSpace();
    if (this.writeScreen === this.displayedMemory) {
      this.outputDataUpdate();
    }
  }
  ccAOF() {
  }
  ccAON() {
  }
  ccDER() {
    this.logger.log(2, "DER- Delete to End of Row");
    this.writeScreen.clearToEndOfRow();
    this.outputDataUpdate();
  }
  ccRU(nrRows) {
    this.logger.log(2, "RU(" + nrRows + ") - Roll Up");
    this.writeScreen = this.displayedMemory;
    this.setMode("MODE_ROLL-UP");
    this.writeScreen.setRollUpRows(nrRows);
  }
  ccFON() {
    this.logger.log(2, "FON - Flash On");
    this.writeScreen.setPen({
      flash: true
    });
  }
  ccRDC() {
    this.logger.log(2, "RDC - Resume Direct Captioning");
    this.setMode("MODE_PAINT-ON");
  }
  ccTR() {
    this.logger.log(2, "TR");
    this.setMode("MODE_TEXT");
  }
  ccRTD() {
    this.logger.log(2, "RTD");
    this.setMode("MODE_TEXT");
  }
  ccEDM() {
    this.logger.log(2, "EDM - Erase Displayed Memory");
    this.displayedMemory.reset();
    this.outputDataUpdate(true);
  }
  ccCR() {
    this.logger.log(2, "CR - Carriage Return");
    this.writeScreen.rollUp();
    this.outputDataUpdate(true);
  }
  ccENM() {
    this.logger.log(2, "ENM - Erase Non-displayed Memory");
    this.nonDisplayedMemory.reset();
  }
  ccEOC() {
    this.logger.log(2, "EOC - End Of Caption");
    if (this.mode === "MODE_POP-ON") {
      const tmp = this.displayedMemory;
      this.displayedMemory = this.nonDisplayedMemory;
      this.nonDisplayedMemory = tmp;
      this.writeScreen = this.nonDisplayedMemory;
      this.logger.log(1, () => "DISP: " + this.displayedMemory.getDisplayText());
    }
    this.outputDataUpdate(true);
  }
  ccTO(nrCols) {
    this.logger.log(2, "TO(" + nrCols + ") - Tab Offset");
    this.writeScreen.moveCursor(nrCols);
  }
  ccMIDROW(secondByte) {
    const styles = {
      flash: false
    };
    styles.underline = secondByte % 2 === 1;
    styles.italics = secondByte >= 46;
    if (!styles.italics) {
      const colorIndex = Math.floor(secondByte / 2) - 16;
      const colors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta"];
      styles.foreground = colors[colorIndex];
    } else {
      styles.foreground = "white";
    }
    this.logger.log(2, "MIDROW: " + stringify(styles));
    this.writeScreen.setPen(styles);
  }
  outputDataUpdate(dispatch = false) {
    const time = this.logger.time;
    if (time === null) {
      return;
    }
    if (this.outputFilter) {
      if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
        this.cueStartTime = time;
      } else {
        if (!this.displayedMemory.equals(this.lastOutputScreen)) {
          this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
          if (dispatch && this.outputFilter.dispatchCue) {
            this.outputFilter.dispatchCue();
          }
          this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
        }
      }
      this.lastOutputScreen.copy(this.displayedMemory);
    }
  }
  cueSplitAtTime(t2) {
    if (this.outputFilter) {
      if (!this.displayedMemory.isEmpty()) {
        if (this.outputFilter.newCue) {
          this.outputFilter.newCue(this.cueStartTime, t2, this.displayedMemory);
        }
        this.cueStartTime = t2;
      }
    }
  }
};
var Cea608Parser = class {
  constructor(field, out1, out2) {
    this.channels = void 0;
    this.currentChannel = 0;
    this.cmdHistory = createCmdHistory();
    this.logger = void 0;
    const logger4 = this.logger = new CaptionsLogger();
    this.channels = [null, new Cea608Channel(field, out1, logger4), new Cea608Channel(field + 1, out2, logger4)];
  }
  getHandler(channel) {
    return this.channels[channel].getHandler();
  }
  setHandler(channel, newHandler) {
    this.channels[channel].setHandler(newHandler);
  }
  /**
   * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
   */
  addData(time, byteList) {
    this.logger.time = time;
    for (let i = 0; i < byteList.length; i += 2) {
      const a = byteList[i] & 127;
      const b = byteList[i + 1] & 127;
      let cmdFound = false;
      let charsFound = null;
      if (a === 0 && b === 0) {
        continue;
      } else {
        this.logger.log(3, () => "[" + numArrayToHexArray([byteList[i], byteList[i + 1]]) + "] -> (" + numArrayToHexArray([a, b]) + ")");
      }
      const cmdHistory = this.cmdHistory;
      const isControlCode = a >= 16 && a <= 31;
      if (isControlCode) {
        if (hasCmdRepeated(a, b, cmdHistory)) {
          setLastCmd(null, null, cmdHistory);
          this.logger.log(3, () => "Repeated command (" + numArrayToHexArray([a, b]) + ") is dropped");
          continue;
        }
        setLastCmd(a, b, this.cmdHistory);
        cmdFound = this.parseCmd(a, b);
        if (!cmdFound) {
          cmdFound = this.parseMidrow(a, b);
        }
        if (!cmdFound) {
          cmdFound = this.parsePAC(a, b);
        }
        if (!cmdFound) {
          cmdFound = this.parseBackgroundAttributes(a, b);
        }
      } else {
        setLastCmd(null, null, cmdHistory);
      }
      if (!cmdFound) {
        charsFound = this.parseChars(a, b);
        if (charsFound) {
          const currChNr = this.currentChannel;
          if (currChNr && currChNr > 0) {
            const channel = this.channels[currChNr];
            channel.insertChars(charsFound);
          } else {
            this.logger.log(2, "No channel found yet. TEXT-MODE?");
          }
        }
      }
      if (!cmdFound && !charsFound) {
        this.logger.log(2, () => "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + " orig: " + numArrayToHexArray([byteList[i], byteList[i + 1]]));
      }
    }
  }
  /**
   * Parse Command.
   * @returns True if a command was found
   */
  parseCmd(a, b) {
    const cond1 = (a === 20 || a === 28 || a === 21 || a === 29) && b >= 32 && b <= 47;
    const cond2 = (a === 23 || a === 31) && b >= 33 && b <= 35;
    if (!(cond1 || cond2)) {
      return false;
    }
    const chNr = a === 20 || a === 21 || a === 23 ? 1 : 2;
    const channel = this.channels[chNr];
    if (a === 20 || a === 21 || a === 28 || a === 29) {
      if (b === 32) {
        channel.ccRCL();
      } else if (b === 33) {
        channel.ccBS();
      } else if (b === 34) {
        channel.ccAOF();
      } else if (b === 35) {
        channel.ccAON();
      } else if (b === 36) {
        channel.ccDER();
      } else if (b === 37) {
        channel.ccRU(2);
      } else if (b === 38) {
        channel.ccRU(3);
      } else if (b === 39) {
        channel.ccRU(4);
      } else if (b === 40) {
        channel.ccFON();
      } else if (b === 41) {
        channel.ccRDC();
      } else if (b === 42) {
        channel.ccTR();
      } else if (b === 43) {
        channel.ccRTD();
      } else if (b === 44) {
        channel.ccEDM();
      } else if (b === 45) {
        channel.ccCR();
      } else if (b === 46) {
        channel.ccENM();
      } else if (b === 47) {
        channel.ccEOC();
      }
    } else {
      channel.ccTO(b - 32);
    }
    this.currentChannel = chNr;
    return true;
  }
  /**
   * Parse midrow styling command
   */
  parseMidrow(a, b) {
    let chNr = 0;
    if ((a === 17 || a === 25) && b >= 32 && b <= 47) {
      if (a === 17) {
        chNr = 1;
      } else {
        chNr = 2;
      }
      if (chNr !== this.currentChannel) {
        this.logger.log(0, "Mismatch channel in midrow parsing");
        return false;
      }
      const channel = this.channels[chNr];
      if (!channel) {
        return false;
      }
      channel.ccMIDROW(b);
      this.logger.log(3, () => "MIDROW (" + numArrayToHexArray([a, b]) + ")");
      return true;
    }
    return false;
  }
  /**
   * Parse Preable Access Codes (Table 53).
   * @returns {Boolean} Tells if PAC found
   */
  parsePAC(a, b) {
    let row;
    const case1 = (a >= 17 && a <= 23 || a >= 25 && a <= 31) && b >= 64 && b <= 127;
    const case2 = (a === 16 || a === 24) && b >= 64 && b <= 95;
    if (!(case1 || case2)) {
      return false;
    }
    const chNr = a <= 23 ? 1 : 2;
    if (b >= 64 && b <= 95) {
      row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
    } else {
      row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
    }
    const channel = this.channels[chNr];
    if (!channel) {
      return false;
    }
    channel.setPAC(this.interpretPAC(row, b));
    this.currentChannel = chNr;
    return true;
  }
  /**
   * Interpret the second byte of the pac, and return the information.
   * @returns pacData with style parameters
   */
  interpretPAC(row, byte) {
    let pacIndex;
    const pacData = {
      color: null,
      italics: false,
      indent: null,
      underline: false,
      row
    };
    if (byte > 95) {
      pacIndex = byte - 96;
    } else {
      pacIndex = byte - 64;
    }
    pacData.underline = (pacIndex & 1) === 1;
    if (pacIndex <= 13) {
      pacData.color = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "white"][Math.floor(pacIndex / 2)];
    } else if (pacIndex <= 15) {
      pacData.italics = true;
      pacData.color = "white";
    } else {
      pacData.indent = Math.floor((pacIndex - 16) / 2) * 4;
    }
    return pacData;
  }
  /**
   * Parse characters.
   * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
   */
  parseChars(a, b) {
    let channelNr;
    let charCodes = null;
    let charCode1 = null;
    if (a >= 25) {
      channelNr = 2;
      charCode1 = a - 8;
    } else {
      channelNr = 1;
      charCode1 = a;
    }
    if (charCode1 >= 17 && charCode1 <= 19) {
      let oneCode;
      if (charCode1 === 17) {
        oneCode = b + 80;
      } else if (charCode1 === 18) {
        oneCode = b + 112;
      } else {
        oneCode = b + 144;
      }
      this.logger.log(2, () => "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
      charCodes = [oneCode];
    } else if (a >= 32 && a <= 127) {
      charCodes = b === 0 ? [a] : [a, b];
    }
    if (charCodes) {
      this.logger.log(3, () => "Char codes =  " + numArrayToHexArray(charCodes).join(","));
    }
    return charCodes;
  }
  /**
   * Parse extended background attributes as well as new foreground color black.
   * @returns True if background attributes are found
   */
  parseBackgroundAttributes(a, b) {
    const case1 = (a === 16 || a === 24) && b >= 32 && b <= 47;
    const case2 = (a === 23 || a === 31) && b >= 45 && b <= 47;
    if (!(case1 || case2)) {
      return false;
    }
    let index;
    const bkgData = {};
    if (a === 16 || a === 24) {
      index = Math.floor((b - 32) / 2);
      bkgData.background = backgroundColors[index];
      if (b % 2 === 1) {
        bkgData.background = bkgData.background + "_semi";
      }
    } else if (b === 45) {
      bkgData.background = "transparent";
    } else {
      bkgData.foreground = "black";
      if (b === 47) {
        bkgData.underline = true;
      }
    }
    const chNr = a <= 23 ? 1 : 2;
    const channel = this.channels[chNr];
    channel.setBkgData(bkgData);
    return true;
  }
  /**
   * Reset state of parser and its channels.
   */
  reset() {
    for (let i = 0; i < Object.keys(this.channels).length; i++) {
      const channel = this.channels[i];
      if (channel) {
        channel.reset();
      }
    }
    setLastCmd(null, null, this.cmdHistory);
  }
  /**
   * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
   */
  cueSplitAtTime(t2) {
    for (let i = 0; i < this.channels.length; i++) {
      const channel = this.channels[i];
      if (channel) {
        channel.cueSplitAtTime(t2);
      }
    }
  }
};
function setLastCmd(a, b, cmdHistory) {
  cmdHistory.a = a;
  cmdHistory.b = b;
}
function hasCmdRepeated(a, b, cmdHistory) {
  return cmdHistory.a === a && cmdHistory.b === b;
}
function createCmdHistory() {
  return {
    a: null,
    b: null
  };
}
var VTTCue2 = function() {
  if (optionalSelf != null && optionalSelf.VTTCue) {
    return self.VTTCue;
  }
  const AllowedDirections = ["", "lr", "rl"];
  const AllowedAlignments = ["start", "middle", "end", "left", "right"];
  function isAllowedValue(allowed, value) {
    if (typeof value !== "string") {
      return false;
    }
    if (!Array.isArray(allowed)) {
      return false;
    }
    const lcValue = value.toLowerCase();
    if (~allowed.indexOf(lcValue)) {
      return lcValue;
    }
    return false;
  }
  function findDirectionSetting(value) {
    return isAllowedValue(AllowedDirections, value);
  }
  function findAlignSetting(value) {
    return isAllowedValue(AllowedAlignments, value);
  }
  function extend3(obj, ...rest) {
    let i = 1;
    for (; i < arguments.length; i++) {
      const cobj = arguments[i];
      for (const p in cobj) {
        obj[p] = cobj[p];
      }
    }
    return obj;
  }
  function VTTCue3(startTime, endTime, text) {
    const cue = this;
    const baseObj = {
      enumerable: true
    };
    cue.hasBeenReset = false;
    let _id = "";
    let _pauseOnExit = false;
    let _startTime = startTime;
    let _endTime = endTime;
    let _text = text;
    let _region = null;
    let _vertical = "";
    let _snapToLines = true;
    let _line = "auto";
    let _lineAlign = "start";
    let _position = 50;
    let _positionAlign = "middle";
    let _size = 50;
    let _align = "middle";
    Object.defineProperty(cue, "id", extend3({}, baseObj, {
      get: function() {
        return _id;
      },
      set: function(value) {
        _id = "" + value;
      }
    }));
    Object.defineProperty(cue, "pauseOnExit", extend3({}, baseObj, {
      get: function() {
        return _pauseOnExit;
      },
      set: function(value) {
        _pauseOnExit = !!value;
      }
    }));
    Object.defineProperty(cue, "startTime", extend3({}, baseObj, {
      get: function() {
        return _startTime;
      },
      set: function(value) {
        if (typeof value !== "number") {
          throw new TypeError("Start time must be set to a number.");
        }
        _startTime = value;
        this.hasBeenReset = true;
      }
    }));
    Object.defineProperty(cue, "endTime", extend3({}, baseObj, {
      get: function() {
        return _endTime;
      },
      set: function(value) {
        if (typeof value !== "number") {
          throw new TypeError("End time must be set to a number.");
        }
        _endTime = value;
        this.hasBeenReset = true;
      }
    }));
    Object.defineProperty(cue, "text", extend3({}, baseObj, {
      get: function() {
        return _text;
      },
      set: function(value) {
        _text = "" + value;
        this.hasBeenReset = true;
      }
    }));
    Object.defineProperty(cue, "region", extend3({}, baseObj, {
      get: function() {
        return _region;
      },
      set: function(value) {
        _region = value;
        this.hasBeenReset = true;
      }
    }));
    Object.defineProperty(cue, "vertical", extend3({}, baseObj, {
      get: function() {
        return _vertical;
      },
      set: function(value) {
        const setting = findDirectionSetting(value);
        if (setting === false) {
          throw new SyntaxError("An invalid or illegal string was specified.");
        }
        _vertical = setting;
        this.hasBeenReset = true;
      }
    }));
    Object.defineProperty(cue, "snapToLines", extend3({}, baseObj, {
      get: function() {
        return _snapToLines;
      },
      set: function(value) {
        _snapToLines = !!value;
        this.hasBeenReset = true;
      }
    }));
    Object.defineProperty(cue, "line", extend3({}, baseObj, {
      get: function() {
        return _line;
      },
      set: function(value) {
        if (typeof value !== "number" && value !== "auto") {
          throw new SyntaxError("An invalid number or illegal string was specified.");
        }
        _line = value;
        this.hasBeenReset = true;
      }
    }));
    Object.defineProperty(cue, "lineAlign", extend3({}, baseObj, {
      get: function() {
        return _lineAlign;
      },
      set: function(value) {
        const setting = findAlignSetting(value);
        if (!setting) {
          throw new SyntaxError("An invalid or illegal string was specified.");
        }
        _lineAlign = setting;
        this.hasBeenReset = true;
      }
    }));
    Object.defineProperty(cue, "position", extend3({}, baseObj, {
      get: function() {
        return _position;
      },
      set: function(value) {
        if (value < 0 || value > 100) {
          throw new Error("Position must be between 0 and 100.");
        }
        _position = value;
        this.hasBeenReset = true;
      }
    }));
    Object.defineProperty(cue, "positionAlign", extend3({}, baseObj, {
      get: function() {
        return _positionAlign;
      },
      set: function(value) {
        const setting = findAlignSetting(value);
        if (!setting) {
          throw new SyntaxError("An invalid or illegal string was specified.");
        }
        _positionAlign = setting;
        this.hasBeenReset = true;
      }
    }));
    Object.defineProperty(cue, "size", extend3({}, baseObj, {
      get: function() {
        return _size;
      },
      set: function(value) {
        if (value < 0 || value > 100) {
          throw new Error("Size must be between 0 and 100.");
        }
        _size = value;
        this.hasBeenReset = true;
      }
    }));
    Object.defineProperty(cue, "align", extend3({}, baseObj, {
      get: function() {
        return _align;
      },
      set: function(value) {
        const setting = findAlignSetting(value);
        if (!setting) {
          throw new SyntaxError("An invalid or illegal string was specified.");
        }
        _align = setting;
        this.hasBeenReset = true;
      }
    }));
    cue.displayState = void 0;
  }
  VTTCue3.prototype.getCueAsHTML = function() {
    const WebVTT2 = self.WebVTT;
    return WebVTT2.convertCueToDOMTree(self, this.text);
  };
  return VTTCue3;
}();
var StringDecoder = class {
  decode(data, options) {
    if (!data) {
      return "";
    }
    if (typeof data !== "string") {
      throw new Error("Error - expected string data.");
    }
    return decodeURIComponent(encodeURIComponent(data));
  }
};
function parseTimeStamp(input) {
  function computeSeconds(h, m2, s, f) {
    return (h | 0) * 3600 + (m2 | 0) * 60 + (s | 0) + parseFloat(f || 0);
  }
  const m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
  if (!m) {
    return null;
  }
  if (parseFloat(m[2]) > 59) {
    return computeSeconds(m[2], m[3], 0, m[4]);
  }
  return computeSeconds(m[1], m[2], m[3], m[4]);
}
var Settings = class {
  constructor() {
    this.values = /* @__PURE__ */ Object.create(null);
  }
  // Only accept the first assignment to any key.
  set(k, v) {
    if (!this.get(k) && v !== "") {
      this.values[k] = v;
    }
  }
  // Return the value for a key, or a default value.
  // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  // a number of possible default values as properties where 'defaultKey' is
  // the key of the property that will be chosen; otherwise it's assumed to be
  // a single value.
  get(k, dflt, defaultKey) {
    if (defaultKey) {
      return this.has(k) ? this.values[k] : dflt[defaultKey];
    }
    return this.has(k) ? this.values[k] : dflt;
  }
  // Check whether we have a value for a key.
  has(k) {
    return k in this.values;
  }
  // Accept a setting if its one of the given alternatives.
  alt(k, v, a) {
    for (let n = 0; n < a.length; ++n) {
      if (v === a[n]) {
        this.set(k, v);
        break;
      }
    }
  }
  // Accept a setting if its a valid (signed) integer.
  integer(k, v) {
    if (/^-?\d+$/.test(v)) {
      this.set(k, parseInt(v, 10));
    }
  }
  // Accept a setting if its a valid percentage.
  percent(k, v) {
    if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
      const percent = parseFloat(v);
      if (percent >= 0 && percent <= 100) {
        this.set(k, percent);
        return true;
      }
    }
    return false;
  }
};
function parseOptions(input, callback2, keyValueDelim, groupDelim) {
  const groups = groupDelim ? input.split(groupDelim) : [input];
  for (const i in groups) {
    if (typeof groups[i] !== "string") {
      continue;
    }
    const kv = groups[i].split(keyValueDelim);
    if (kv.length !== 2) {
      continue;
    }
    const k = kv[0];
    const v = kv[1];
    callback2(k, v);
  }
}
var defaults = new VTTCue2(0, 0, "");
var center = defaults.align === "middle" ? "middle" : "center";
function parseCue(input, cue, regionList) {
  const oInput = input;
  function consumeTimeStamp() {
    const ts2 = parseTimeStamp(input);
    if (ts2 === null) {
      throw new Error("Malformed timestamp: " + oInput);
    }
    input = input.replace(/^[^\sa-zA-Z-]+/, "");
    return ts2;
  }
  function consumeCueSettings(input2, cue2) {
    const settings = new Settings();
    parseOptions(input2, function(k, v) {
      let vals;
      switch (k) {
        case "region":
          for (let i = regionList.length - 1; i >= 0; i--) {
            if (regionList[i].id === v) {
              settings.set(k, regionList[i].region);
              break;
            }
          }
          break;
        case "vertical":
          settings.alt(k, v, ["rl", "lr"]);
          break;
        case "line":
          vals = v.split(",");
          settings.integer(k, vals[0]);
          if (settings.percent(k, vals[0])) {
            settings.set("snapToLines", false);
          }
          settings.alt(k, vals[0], ["auto"]);
          if (vals.length === 2) {
            settings.alt("lineAlign", vals[1], ["start", center, "end"]);
          }
          break;
        case "position":
          vals = v.split(",");
          settings.percent(k, vals[0]);
          if (vals.length === 2) {
            settings.alt("positionAlign", vals[1], ["start", center, "end", "line-left", "line-right", "auto"]);
          }
          break;
        case "size":
          settings.percent(k, v);
          break;
        case "align":
          settings.alt(k, v, ["start", center, "end", "left", "right"]);
          break;
      }
    }, /:/, /\s/);
    cue2.region = settings.get("region", null);
    cue2.vertical = settings.get("vertical", "");
    let line = settings.get("line", "auto");
    if (line === "auto" && defaults.line === -1) {
      line = -1;
    }
    cue2.line = line;
    cue2.lineAlign = settings.get("lineAlign", "start");
    cue2.snapToLines = settings.get("snapToLines", true);
    cue2.size = settings.get("size", 100);
    cue2.align = settings.get("align", center);
    let position = settings.get("position", "auto");
    if (position === "auto" && defaults.position === 50) {
      position = cue2.align === "start" || cue2.align === "left" ? 0 : cue2.align === "end" || cue2.align === "right" ? 100 : 50;
    }
    cue2.position = position;
  }
  function skipWhitespace() {
    input = input.replace(/^\s+/, "");
  }
  skipWhitespace();
  cue.startTime = consumeTimeStamp();
  skipWhitespace();
  if (input.slice(0, 3) !== "-->") {
    throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  }
  input = input.slice(3);
  skipWhitespace();
  cue.endTime = consumeTimeStamp();
  skipWhitespace();
  consumeCueSettings(input, cue);
}
function fixLineBreaks(input) {
  return input.replace(/<br(?: \/)?>/gi, "\n");
}
var VTTParser = class {
  constructor() {
    this.state = "INITIAL";
    this.buffer = "";
    this.decoder = new StringDecoder();
    this.regionList = [];
    this.cue = null;
    this.oncue = void 0;
    this.onparsingerror = void 0;
    this.onflush = void 0;
  }
  parse(data) {
    const _this = this;
    if (data) {
      _this.buffer += _this.decoder.decode(data, {
        stream: true
      });
    }
    function collectNextLine() {
      let buffer = _this.buffer;
      let pos = 0;
      buffer = fixLineBreaks(buffer);
      while (pos < buffer.length && buffer[pos] !== "\r" && buffer[pos] !== "\n") {
        ++pos;
      }
      const line = buffer.slice(0, pos);
      if (buffer[pos] === "\r") {
        ++pos;
      }
      if (buffer[pos] === "\n") {
        ++pos;
      }
      _this.buffer = buffer.slice(pos);
      return line;
    }
    function parseHeader2(input) {
      parseOptions(input, function(k, v) {
      }, /:/);
    }
    try {
      let line = "";
      if (_this.state === "INITIAL") {
        if (!/\r\n|\n/.test(_this.buffer)) {
          return this;
        }
        line = collectNextLine();
        const m = line.match(/^(ï»¿)?WEBVTT([ \t].*)?$/);
        if (!(m != null && m[0])) {
          throw new Error("Malformed WebVTT signature.");
        }
        _this.state = "HEADER";
      }
      let alreadyCollectedLine = false;
      while (_this.buffer) {
        if (!/\r\n|\n/.test(_this.buffer)) {
          return this;
        }
        if (!alreadyCollectedLine) {
          line = collectNextLine();
        } else {
          alreadyCollectedLine = false;
        }
        switch (_this.state) {
          case "HEADER":
            if (/:/.test(line)) {
              parseHeader2(line);
            } else if (!line) {
              _this.state = "ID";
            }
            continue;
          case "NOTE":
            if (!line) {
              _this.state = "ID";
            }
            continue;
          case "ID":
            if (/^NOTE($|[ \t])/.test(line)) {
              _this.state = "NOTE";
              break;
            }
            if (!line) {
              continue;
            }
            _this.cue = new VTTCue2(0, 0, "");
            _this.state = "CUE";
            if (line.indexOf("-->") === -1) {
              _this.cue.id = line;
              continue;
            }
          // Process line as start of a cue.
          /* falls through */
          case "CUE":
            if (!_this.cue) {
              _this.state = "BADCUE";
              continue;
            }
            try {
              parseCue(line, _this.cue, _this.regionList);
            } catch (e) {
              _this.cue = null;
              _this.state = "BADCUE";
              continue;
            }
            _this.state = "CUETEXT";
            continue;
          case "CUETEXT":
            {
              const hasSubstring = line.indexOf("-->") !== -1;
              if (!line || hasSubstring && (alreadyCollectedLine = true)) {
                if (_this.oncue && _this.cue) {
                  _this.oncue(_this.cue);
                }
                _this.cue = null;
                _this.state = "ID";
                continue;
              }
              if (_this.cue === null) {
                continue;
              }
              if (_this.cue.text) {
                _this.cue.text += "\n";
              }
              _this.cue.text += line;
            }
            continue;
          case "BADCUE":
            if (!line) {
              _this.state = "ID";
            }
        }
      }
    } catch (e) {
      if (_this.state === "CUETEXT" && _this.cue && _this.oncue) {
        _this.oncue(_this.cue);
      }
      _this.cue = null;
      _this.state = _this.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
    }
    return this;
  }
  flush() {
    const _this = this;
    try {
      if (_this.cue || _this.state === "HEADER") {
        _this.buffer += "\n\n";
        _this.parse();
      }
      if (_this.state === "INITIAL" || _this.state === "BADWEBVTT") {
        throw new Error("Malformed WebVTT signature.");
      }
    } catch (e) {
      if (_this.onparsingerror) {
        _this.onparsingerror(e);
      }
    }
    if (_this.onflush) {
      _this.onflush();
    }
    return this;
  }
};
var LINEBREAKS = /\r\n|\n\r|\n|\r/g;
var startsWith = function startsWith2(inputString, searchString, position = 0) {
  return inputString.slice(position, position + searchString.length) === searchString;
};
var cueString2millis = function cueString2millis2(timeString) {
  let ts2 = parseInt(timeString.slice(-3));
  const secs = parseInt(timeString.slice(-6, -4));
  const mins = parseInt(timeString.slice(-9, -7));
  const hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(":"))) : 0;
  if (!isFiniteNumber(ts2) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {
    throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);
  }
  ts2 += 1e3 * secs;
  ts2 += 60 * 1e3 * mins;
  ts2 += 60 * 60 * 1e3 * hours;
  return ts2;
};
function generateCueId(startTime, endTime, text) {
  return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
}
var calculateOffset = function calculateOffset2(vttCCs, cc, presentationTime) {
  let currCC = vttCCs[cc];
  let prevCC = vttCCs[currCC.prevCC];
  if (!prevCC || !prevCC.new && currCC.new) {
    vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
    currCC.new = false;
    return;
  }
  while ((_prevCC = prevCC) != null && _prevCC.new) {
    var _prevCC;
    vttCCs.ccOffset += currCC.start - prevCC.start;
    currCC.new = false;
    currCC = prevCC;
    prevCC = vttCCs[currCC.prevCC];
  }
  vttCCs.presentationOffset = presentationTime;
};
function parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) {
  const parser6 = new VTTParser();
  const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, "\n").split("\n");
  const cues = [];
  const init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0;
  let cueTime = "00:00.000";
  let timestampMapMPEGTS = 0;
  let timestampMapLOCAL = 0;
  let parsingError;
  let inHeader = true;
  parser6.oncue = function(cue) {
    const currCC = vttCCs[cc];
    let cueOffset = vttCCs.ccOffset;
    const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 9e4;
    if (currCC != null && currCC.new) {
      if (timestampMapLOCAL !== void 0) {
        cueOffset = vttCCs.ccOffset = currCC.start;
      } else {
        calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
      }
    }
    if (webVttMpegTsMapOffset) {
      if (!initPTS) {
        parsingError = new Error("Missing initPTS for VTT MPEGTS");
        return;
      }
      cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
    }
    const duration5 = cue.endTime - cue.startTime;
    const startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 9e4, timeOffset * 9e4) / 9e4;
    cue.startTime = Math.max(startTime, 0);
    cue.endTime = Math.max(startTime + duration5, 0);
    const text = cue.text.trim();
    cue.text = decodeURIComponent(encodeURIComponent(text));
    if (!cue.id) {
      cue.id = generateCueId(cue.startTime, cue.endTime, text);
    }
    if (cue.endTime > 0) {
      cues.push(cue);
    }
  };
  parser6.onparsingerror = function(error) {
    parsingError = error;
  };
  parser6.onflush = function() {
    if (parsingError) {
      errorCallBack(parsingError);
      return;
    }
    callBack(cues);
  };
  vttLines.forEach((line) => {
    if (inHeader) {
      if (startsWith(line, "X-TIMESTAMP-MAP=")) {
        inHeader = false;
        line.slice(16).split(",").forEach((timestamp) => {
          if (startsWith(timestamp, "LOCAL:")) {
            cueTime = timestamp.slice(6);
          } else if (startsWith(timestamp, "MPEGTS:")) {
            timestampMapMPEGTS = parseInt(timestamp.slice(7));
          }
        });
        try {
          timestampMapLOCAL = cueString2millis(cueTime) / 1e3;
        } catch (error) {
          parsingError = error;
        }
        return;
      } else if (line === "") {
        inHeader = false;
      }
    }
    parser6.parse(line + "\n");
  });
  parser6.flush();
}
var IMSC1_CODEC = "stpp.ttml.im1t";
var HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;
var TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
var textAlignToLineAlign = {
  left: "start",
  center: "center",
  right: "end",
  start: "start",
  end: "end"
};
function parseIMSC1(payload, initPTS, callBack, errorCallBack) {
  const results = findBox(new Uint8Array(payload), ["mdat"]);
  if (results.length === 0) {
    errorCallBack(new Error("Could not parse IMSC1 mdat"));
    return;
  }
  const ttmlList = results.map((mdat) => utf8ArrayToStr(mdat));
  const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);
  try {
    ttmlList.forEach((ttml) => callBack(parseTTML(ttml, syncTime)));
  } catch (error) {
    errorCallBack(error);
  }
}
function parseTTML(ttml, syncTime) {
  const parser6 = new DOMParser();
  const xmlDoc = parser6.parseFromString(ttml, "text/xml");
  const tt = xmlDoc.getElementsByTagName("tt")[0];
  if (!tt) {
    throw new Error("Invalid ttml");
  }
  const defaultRateInfo = {
    frameRate: 30,
    subFrameRate: 1,
    frameRateMultiplier: 0,
    tickRate: 0
  };
  const rateInfo = Object.keys(defaultRateInfo).reduce((result, key) => {
    result[key] = tt.getAttribute(`ttp:${key}`) || defaultRateInfo[key];
    return result;
  }, {});
  const trim = tt.getAttribute("xml:space") !== "preserve";
  const styleElements = collectionToDictionary(getElementCollection(tt, "styling", "style"));
  const regionElements = collectionToDictionary(getElementCollection(tt, "layout", "region"));
  const cueElements = getElementCollection(tt, "body", "[begin]");
  return [].map.call(cueElements, (cueElement) => {
    const cueText = getTextContent(cueElement, trim);
    if (!cueText || !cueElement.hasAttribute("begin")) {
      return null;
    }
    const startTime = parseTtmlTime(cueElement.getAttribute("begin"), rateInfo);
    const duration5 = parseTtmlTime(cueElement.getAttribute("dur"), rateInfo);
    let endTime = parseTtmlTime(cueElement.getAttribute("end"), rateInfo);
    if (startTime === null) {
      throw timestampParsingError(cueElement);
    }
    if (endTime === null) {
      if (duration5 === null) {
        throw timestampParsingError(cueElement);
      }
      endTime = startTime + duration5;
    }
    const cue = new VTTCue2(startTime - syncTime, endTime - syncTime, cueText);
    cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);
    const region = regionElements[cueElement.getAttribute("region")];
    const style = styleElements[cueElement.getAttribute("style")];
    const styles = getTtmlStyles(region, style, styleElements);
    const {
      textAlign
    } = styles;
    if (textAlign) {
      const lineAlign = textAlignToLineAlign[textAlign];
      if (lineAlign) {
        cue.lineAlign = lineAlign;
      }
      cue.align = textAlign;
    }
    _extends(cue, styles);
    return cue;
  }).filter((cue) => cue !== null);
}
function getElementCollection(fromElement, parentName, childName) {
  const parent = fromElement.getElementsByTagName(parentName)[0];
  if (parent) {
    return [].slice.call(parent.querySelectorAll(childName));
  }
  return [];
}
function collectionToDictionary(elementsWithId) {
  return elementsWithId.reduce((dict, element) => {
    const id = element.getAttribute("xml:id");
    if (id) {
      dict[id] = element;
    }
    return dict;
  }, {});
}
function getTextContent(element, trim) {
  return [].slice.call(element.childNodes).reduce((str, node, i) => {
    var _node$childNodes;
    if (node.nodeName === "br" && i) {
      return str + "\n";
    }
    if ((_node$childNodes = node.childNodes) != null && _node$childNodes.length) {
      return getTextContent(node, trim);
    } else if (trim) {
      return str + node.textContent.trim().replace(/\s+/g, " ");
    }
    return str + node.textContent;
  }, "");
}
function getTtmlStyles(region, style, styleElements) {
  const ttsNs = "http://www.w3.org/ns/ttml#styling";
  let regionStyle = null;
  const styleAttributes = [
    "displayAlign",
    "textAlign",
    "color",
    "backgroundColor",
    "fontSize",
    "fontFamily"
    // 'fontWeight',
    // 'lineHeight',
    // 'wrapOption',
    // 'fontStyle',
    // 'direction',
    // 'writingMode'
  ];
  const regionStyleName = region != null && region.hasAttribute("style") ? region.getAttribute("style") : null;
  if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {
    regionStyle = styleElements[regionStyleName];
  }
  return styleAttributes.reduce((styles, name) => {
    const value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name);
    if (value) {
      styles[name] = value;
    }
    return styles;
  }, {});
}
function getAttributeNS(element, ns, name) {
  if (!element) {
    return null;
  }
  return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
}
function timestampParsingError(node) {
  return new Error(`Could not parse ttml timestamp ${node}`);
}
function parseTtmlTime(timeAttributeValue, rateInfo) {
  if (!timeAttributeValue) {
    return null;
  }
  let seconds = parseTimeStamp(timeAttributeValue);
  if (seconds === null) {
    if (HMSF_REGEX.test(timeAttributeValue)) {
      seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
    } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
      seconds = parseTimeUnits(timeAttributeValue, rateInfo);
    }
  }
  return seconds;
}
function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
  const m = HMSF_REGEX.exec(timeAttributeValue);
  const frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
  return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
}
function parseTimeUnits(timeAttributeValue, rateInfo) {
  const m = TIME_UNIT_REGEX.exec(timeAttributeValue);
  const value = Number(m[1]);
  const unit = m[2];
  switch (unit) {
    case "h":
      return value * 3600;
    case "m":
      return value * 60;
    case "ms":
      return value * 1e3;
    case "f":
      return value / rateInfo.frameRate;
    case "t":
      return value / rateInfo.tickRate;
  }
  return value;
}
var OutputFilter = class {
  constructor(timelineController, trackName) {
    this.timelineController = void 0;
    this.cueRanges = [];
    this.trackName = void 0;
    this.startTime = null;
    this.endTime = null;
    this.screen = null;
    this.timelineController = timelineController;
    this.trackName = trackName;
  }
  dispatchCue() {
    if (this.startTime === null) {
      return;
    }
    this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
    this.startTime = null;
  }
  newCue(startTime, endTime, screen2) {
    if (this.startTime === null || this.startTime > startTime) {
      this.startTime = startTime;
    }
    this.endTime = endTime;
    this.screen = screen2;
    this.timelineController.createCaptionsTrack(this.trackName);
  }
  reset() {
    this.cueRanges = [];
    this.startTime = null;
  }
};
var TimelineController = class {
  constructor(hls) {
    this.hls = void 0;
    this.media = null;
    this.config = void 0;
    this.enabled = true;
    this.Cues = void 0;
    this.textTracks = [];
    this.tracks = [];
    this.initPTS = [];
    this.unparsedVttFrags = [];
    this.captionsTracks = {};
    this.nonNativeCaptionsTracks = {};
    this.cea608Parser1 = void 0;
    this.cea608Parser2 = void 0;
    this.lastCc = -1;
    this.lastSn = -1;
    this.lastPartIndex = -1;
    this.prevCC = -1;
    this.vttCCs = newVTTCCs();
    this.captionsProperties = void 0;
    this.hls = hls;
    this.config = hls.config;
    this.Cues = hls.config.cueHandler;
    this.captionsProperties = {
      textTrack1: {
        label: this.config.captionsTextTrack1Label,
        languageCode: this.config.captionsTextTrack1LanguageCode
      },
      textTrack2: {
        label: this.config.captionsTextTrack2Label,
        languageCode: this.config.captionsTextTrack2LanguageCode
      },
      textTrack3: {
        label: this.config.captionsTextTrack3Label,
        languageCode: this.config.captionsTextTrack3LanguageCode
      },
      textTrack4: {
        label: this.config.captionsTextTrack4Label,
        languageCode: this.config.captionsTextTrack4LanguageCode
      }
    };
    hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
    hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
    hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
    hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
    hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
    hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
    hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
    hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
    hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  }
  destroy() {
    const {
      hls
    } = this;
    hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
    hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
    hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
    hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
    hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
    hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
    hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
    hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
    hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
    this.hls = this.config = this.media = null;
    this.cea608Parser1 = this.cea608Parser2 = void 0;
  }
  initCea608Parsers() {
    const channel1 = new OutputFilter(this, "textTrack1");
    const channel2 = new OutputFilter(this, "textTrack2");
    const channel3 = new OutputFilter(this, "textTrack3");
    const channel4 = new OutputFilter(this, "textTrack4");
    this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);
    this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);
  }
  addCues(trackName, startTime, endTime, screen2, cueRanges) {
    let merged = false;
    for (let i = cueRanges.length; i--; ) {
      const cueRange = cueRanges[i];
      const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
      if (overlap >= 0) {
        cueRange[0] = Math.min(cueRange[0], startTime);
        cueRange[1] = Math.max(cueRange[1], endTime);
        merged = true;
        if (overlap / (endTime - startTime) > 0.5) {
          return;
        }
      }
    }
    if (!merged) {
      cueRanges.push([startTime, endTime]);
    }
    if (this.config.renderTextTracksNatively) {
      const track = this.captionsTracks[trackName];
      this.Cues.newCue(track, startTime, endTime, screen2);
    } else {
      const cues = this.Cues.newCue(null, startTime, endTime, screen2);
      this.hls.trigger(Events.CUES_PARSED, {
        type: "captions",
        cues,
        track: trackName
      });
    }
  }
  // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  onInitPtsFound(event, {
    frag,
    id,
    initPTS,
    timescale: timescale2
  }) {
    const {
      unparsedVttFrags
    } = this;
    if (id === PlaylistLevelType.MAIN) {
      this.initPTS[frag.cc] = {
        baseTime: initPTS,
        timescale: timescale2
      };
    }
    if (unparsedVttFrags.length) {
      this.unparsedVttFrags = [];
      unparsedVttFrags.forEach((frag2) => {
        this.onFragLoaded(Events.FRAG_LOADED, frag2);
      });
    }
  }
  getExistingTrack(label, language) {
    const {
      media
    } = this;
    if (media) {
      for (let i = 0; i < media.textTracks.length; i++) {
        const textTrack = media.textTracks[i];
        if (canReuseVttTextTrack(textTrack, {
          name: label,
          lang: language,
          characteristics: "transcribes-spoken-dialog,describes-music-and-sound"
        })) {
          return textTrack;
        }
      }
    }
    return null;
  }
  createCaptionsTrack(trackName) {
    if (this.config.renderTextTracksNatively) {
      this.createNativeTrack(trackName);
    } else {
      this.createNonNativeTrack(trackName);
    }
  }
  createNativeTrack(trackName) {
    if (this.captionsTracks[trackName]) {
      return;
    }
    const {
      captionsProperties,
      captionsTracks,
      media
    } = this;
    const {
      label,
      languageCode
    } = captionsProperties[trackName];
    const existingTrack = this.getExistingTrack(label, languageCode);
    if (!existingTrack) {
      const textTrack = this.createTextTrack("captions", label, languageCode);
      if (textTrack) {
        textTrack[trackName] = true;
        captionsTracks[trackName] = textTrack;
      }
    } else {
      captionsTracks[trackName] = existingTrack;
      clearCurrentCues(captionsTracks[trackName]);
      sendAddTrackEvent(captionsTracks[trackName], media);
    }
  }
  createNonNativeTrack(trackName) {
    if (this.nonNativeCaptionsTracks[trackName]) {
      return;
    }
    const trackProperties = this.captionsProperties[trackName];
    if (!trackProperties) {
      return;
    }
    const label = trackProperties.label;
    const track = {
      _id: trackName,
      label,
      kind: "captions",
      default: trackProperties.media ? !!trackProperties.media.default : false,
      closedCaptions: trackProperties.media
    };
    this.nonNativeCaptionsTracks[trackName] = track;
    this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
      tracks: [track]
    });
  }
  createTextTrack(kind, label, lang) {
    const media = this.media;
    if (!media) {
      return;
    }
    return media.addTextTrack(kind, label, lang);
  }
  onMediaAttaching(event, data) {
    this.media = data.media;
    if (!data.mediaSource) {
      this._cleanTracks();
    }
  }
  onMediaDetaching(event, data) {
    const transferringMedia = !!data.transferMedia;
    this.media = null;
    if (transferringMedia) {
      return;
    }
    const {
      captionsTracks
    } = this;
    Object.keys(captionsTracks).forEach((trackName) => {
      clearCurrentCues(captionsTracks[trackName]);
      delete captionsTracks[trackName];
    });
    this.nonNativeCaptionsTracks = {};
  }
  onManifestLoading() {
    this.lastCc = -1;
    this.lastSn = -1;
    this.lastPartIndex = -1;
    this.prevCC = -1;
    this.vttCCs = newVTTCCs();
    this._cleanTracks();
    this.tracks = [];
    this.captionsTracks = {};
    this.nonNativeCaptionsTracks = {};
    this.textTracks = [];
    this.unparsedVttFrags = [];
    this.initPTS = [];
    if (this.cea608Parser1 && this.cea608Parser2) {
      this.cea608Parser1.reset();
      this.cea608Parser2.reset();
    }
  }
  _cleanTracks() {
    const {
      media
    } = this;
    if (!media) {
      return;
    }
    const textTracks = media.textTracks;
    if (textTracks) {
      for (let i = 0; i < textTracks.length; i++) {
        clearCurrentCues(textTracks[i]);
      }
    }
  }
  onSubtitleTracksUpdated(event, data) {
    const tracks = data.subtitleTracks || [];
    const hasIMSC1 = tracks.some((track) => track.textCodec === IMSC1_CODEC);
    if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
      const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);
      if (listIsIdentical) {
        this.tracks = tracks;
        return;
      }
      this.textTracks = [];
      this.tracks = tracks;
      if (this.config.renderTextTracksNatively) {
        const media = this.media;
        const inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null;
        this.tracks.forEach((track, index) => {
          let textTrack;
          if (inUseTracks) {
            let inUseTrack = null;
            for (let i = 0; i < inUseTracks.length; i++) {
              if (inUseTracks[i] && canReuseVttTextTrack(inUseTracks[i], track)) {
                inUseTrack = inUseTracks[i];
                inUseTracks[i] = null;
                break;
              }
            }
            if (inUseTrack) {
              textTrack = inUseTrack;
            }
          }
          if (textTrack) {
            clearCurrentCues(textTrack);
          } else {
            const textTrackKind = captionsOrSubtitlesFromCharacteristics(track);
            textTrack = this.createTextTrack(textTrackKind, track.name, track.lang);
            if (textTrack) {
              textTrack.mode = "disabled";
            }
          }
          if (textTrack) {
            this.textTracks.push(textTrack);
          }
        });
        if (inUseTracks != null && inUseTracks.length) {
          const unusedTextTracks = inUseTracks.filter((t2) => t2 !== null).map((t2) => t2.label);
          if (unusedTextTracks.length) {
            this.hls.logger.warn(`Media element contains unused subtitle tracks: ${unusedTextTracks.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);
          }
        }
      } else if (this.tracks.length) {
        const tracksList = this.tracks.map((track) => {
          return {
            label: track.name,
            kind: track.type.toLowerCase(),
            default: track.default,
            subtitleTrack: track
          };
        });
        this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
          tracks: tracksList
        });
      }
    }
  }
  onManifestLoaded(event, data) {
    if (this.config.enableCEA708Captions && data.captions) {
      data.captions.forEach((captionsTrack) => {
        const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
        if (!instreamIdMatch) {
          return;
        }
        const trackName = `textTrack${instreamIdMatch[1]}`;
        const trackProperties = this.captionsProperties[trackName];
        if (!trackProperties) {
          return;
        }
        trackProperties.label = captionsTrack.name;
        if (captionsTrack.lang) {
          trackProperties.languageCode = captionsTrack.lang;
        }
        trackProperties.media = captionsTrack;
      });
    }
  }
  closedCaptionsForLevel(frag) {
    const level = this.hls.levels[frag.level];
    return level == null ? void 0 : level.attrs["CLOSED-CAPTIONS"];
  }
  onFragLoading(event, data) {
    if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {
      var _data$part$index, _data$part;
      const {
        cea608Parser1,
        cea608Parser2,
        lastSn
      } = this;
      const {
        cc,
        sn
      } = data.frag;
      const partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1;
      if (cea608Parser1 && cea608Parser2) {
        if (sn !== lastSn + 1 || sn === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) {
          cea608Parser1.reset();
          cea608Parser2.reset();
        }
      }
      this.lastCc = cc;
      this.lastSn = sn;
      this.lastPartIndex = partIndex;
    }
  }
  onFragLoaded(event, data) {
    const {
      frag,
      payload
    } = data;
    if (frag.type === PlaylistLevelType.SUBTITLE) {
      if (payload.byteLength) {
        const decryptData = frag.decryptdata;
        const decrypted = "stats" in data;
        if (decryptData == null || !decryptData.encrypted || decrypted) {
          const trackPlaylistMedia = this.tracks[frag.level];
          const vttCCs = this.vttCCs;
          if (!vttCCs[frag.cc]) {
            vttCCs[frag.cc] = {
              start: frag.start,
              prevCC: this.prevCC,
              new: true
            };
            this.prevCC = frag.cc;
          }
          if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) {
            this._parseIMSC1(frag, payload);
          } else {
            this._parseVTTs(data);
          }
        }
      } else {
        this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
          success: false,
          frag,
          error: new Error("Empty subtitle payload")
        });
      }
    }
  }
  _parseIMSC1(frag, payload) {
    const hls = this.hls;
    parseIMSC1(payload, this.initPTS[frag.cc], (cues) => {
      this._appendCues(cues, frag.level);
      hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
        success: true,
        frag
      });
    }, (error) => {
      hls.logger.log(`Failed to parse IMSC1: ${error}`);
      hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
        success: false,
        frag,
        error
      });
    });
  }
  _parseVTTs(data) {
    var _frag$initSegment;
    const {
      frag,
      payload
    } = data;
    const {
      initPTS,
      unparsedVttFrags
    } = this;
    const maxAvCC = initPTS.length - 1;
    if (!initPTS[frag.cc] && maxAvCC === -1) {
      unparsedVttFrags.push(data);
      return;
    }
    const hls = this.hls;
    const payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)).buffer : payload;
    parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, (cues) => {
      this._appendCues(cues, frag.level);
      hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
        success: true,
        frag
      });
    }, (error) => {
      const missingInitPTS = error.message === "Missing initPTS for VTT MPEGTS";
      if (missingInitPTS) {
        unparsedVttFrags.push(data);
      } else {
        this._fallbackToIMSC1(frag, payload);
      }
      hls.logger.log(`Failed to parse VTT cue: ${error}`);
      if (missingInitPTS && maxAvCC > frag.cc) {
        return;
      }
      hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
        success: false,
        frag,
        error
      });
    });
  }
  _fallbackToIMSC1(frag, payload) {
    const trackPlaylistMedia = this.tracks[frag.level];
    if (!trackPlaylistMedia.textCodec) {
      parseIMSC1(payload, this.initPTS[frag.cc], () => {
        trackPlaylistMedia.textCodec = IMSC1_CODEC;
        this._parseIMSC1(frag, payload);
      }, () => {
        trackPlaylistMedia.textCodec = "wvtt";
      });
    }
  }
  _appendCues(cues, fragLevel) {
    const hls = this.hls;
    if (this.config.renderTextTracksNatively) {
      const textTrack = this.textTracks[fragLevel];
      if (!textTrack || textTrack.mode === "disabled") {
        return;
      }
      cues.forEach((cue) => addCueToTrack(textTrack, cue));
    } else {
      const currentTrack = this.tracks[fragLevel];
      if (!currentTrack) {
        return;
      }
      const track = currentTrack.default ? "default" : "subtitles" + fragLevel;
      hls.trigger(Events.CUES_PARSED, {
        type: "subtitles",
        cues,
        track
      });
    }
  }
  onFragDecrypted(event, data) {
    const {
      frag
    } = data;
    if (frag.type === PlaylistLevelType.SUBTITLE) {
      this.onFragLoaded(Events.FRAG_LOADED, data);
    }
  }
  onSubtitleTracksCleared() {
    this.tracks = [];
    this.captionsTracks = {};
  }
  onFragParsingUserdata(event, data) {
    if (!this.enabled || !this.config.enableCEA708Captions) {
      return;
    }
    const {
      frag,
      samples
    } = data;
    if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === "NONE") {
      return;
    }
    for (let i = 0; i < samples.length; i++) {
      const ccBytes = samples[i].bytes;
      if (ccBytes) {
        if (!this.cea608Parser1) {
          this.initCea608Parsers();
        }
        const ccdatas = this.extractCea608Data(ccBytes);
        this.cea608Parser1.addData(samples[i].pts, ccdatas[0]);
        this.cea608Parser2.addData(samples[i].pts, ccdatas[1]);
      }
    }
  }
  onBufferFlushing(event, {
    startOffset,
    endOffset,
    endOffsetSubtitles,
    type: type2
  }) {
    const {
      media
    } = this;
    if (!media || media.currentTime < endOffset) {
      return;
    }
    if (!type2 || type2 === "video") {
      const {
        captionsTracks
      } = this;
      Object.keys(captionsTracks).forEach((trackName) => removeCuesInRange(captionsTracks[trackName], startOffset, endOffset));
    }
    if (this.config.renderTextTracksNatively) {
      if (startOffset === 0 && endOffsetSubtitles !== void 0) {
        const {
          textTracks
        } = this;
        Object.keys(textTracks).forEach((trackName) => removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles));
      }
    }
  }
  extractCea608Data(byteArray) {
    const actualCCBytes = [[], []];
    const count = byteArray[0] & 31;
    let position = 2;
    for (let j = 0; j < count; j++) {
      const tmpByte = byteArray[position++];
      const ccbyte1 = 127 & byteArray[position++];
      const ccbyte2 = 127 & byteArray[position++];
      if (ccbyte1 === 0 && ccbyte2 === 0) {
        continue;
      }
      const ccValid = (4 & tmpByte) !== 0;
      if (ccValid) {
        const ccType = 3 & tmpByte;
        if (0 === ccType || 1 === ccType) {
          actualCCBytes[ccType].push(ccbyte1);
          actualCCBytes[ccType].push(ccbyte2);
        }
      }
    }
    return actualCCBytes;
  }
};
function captionsOrSubtitlesFromCharacteristics(track) {
  if (track.characteristics) {
    if (/transcribes-spoken-dialog/gi.test(track.characteristics) && /describes-music-and-sound/gi.test(track.characteristics)) {
      return "captions";
    }
  }
  return "subtitles";
}
function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack);
}
function intersection(x1, x2, y1, y2) {
  return Math.min(x2, y2) - Math.max(x1, y1);
}
function newVTTCCs() {
  return {
    ccOffset: 0,
    presentationOffset: 0,
    0: {
      start: 0,
      prevCC: -1,
      new: true
    }
  };
}
var WHITESPACE_CHAR = /\s/;
var Cues = {
  newCue(track, startTime, endTime, captionScreen) {
    const result = [];
    let row;
    let cue;
    let indenting;
    let indent;
    let text;
    const Cue = self.VTTCue || self.TextTrackCue;
    for (let r2 = 0; r2 < captionScreen.rows.length; r2++) {
      row = captionScreen.rows[r2];
      indenting = true;
      indent = 0;
      text = "";
      if (!row.isEmpty()) {
        var _track$cues;
        for (let c = 0; c < row.chars.length; c++) {
          if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
            indent++;
          } else {
            text += row.chars[c].uchar;
            indenting = false;
          }
        }
        row.cueStartTime = startTime;
        if (startTime === endTime) {
          endTime += 1e-4;
        }
        if (indent >= 16) {
          indent--;
        } else {
          indent++;
        }
        const cueText = fixLineBreaks(text.trim());
        const id = generateCueId(startTime, endTime, cueText);
        if (!(track != null && (_track$cues = track.cues) != null && _track$cues.getCueById(id))) {
          cue = new Cue(startTime, endTime, cueText);
          cue.id = id;
          cue.line = r2 + 1;
          cue.align = "left";
          cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
          result.push(cue);
        }
      }
    }
    if (track && result.length) {
      result.sort((cueA, cueB) => {
        if (cueA.line === "auto" || cueB.line === "auto") {
          return 0;
        }
        if (cueA.line > 8 && cueB.line > 8) {
          return cueB.line - cueA.line;
        }
        return cueA.line - cueB.line;
      });
      result.forEach((cue2) => addCueToTrack(track, cue2));
    }
    return result;
  }
};
function fetchSupported() {
  if (
    // @ts-ignore
    self.fetch && self.AbortController && self.ReadableStream && self.Request
  ) {
    try {
      new self.ReadableStream({});
      return true;
    } catch (e) {
    }
  }
  return false;
}
var BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
var FetchLoader = class {
  constructor(config) {
    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 = config.fetchSetup || getRequest;
    this.controller = new self.AbortController();
    this.stats = new LoadStats();
  }
  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() {
    if (this.controller && !this.stats.loading.end) {
      this.stats.aborted = true;
      this.controller.abort();
    }
  }
  abort() {
    var _this$callbacks;
    this.abortInternal();
    if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
      this.callbacks.onAbort(this.stats, this.context, this.response);
    }
  }
  load(context, config, callbacks) {
    const stats = this.stats;
    if (stats.loading.start) {
      throw new Error("Loader can only be used once.");
    }
    stats.loading.start = self.performance.now();
    const initParams = getRequestParameters(context, this.controller.signal);
    const isArrayBuffer = context.responseType === "arraybuffer";
    const LENGTH = isArrayBuffer ? "byteLength" : "length";
    const {
      maxTimeToFirstByteMs,
      maxLoadTimeMs
    } = config.loadPolicy;
    this.context = context;
    this.config = config;
    this.callbacks = callbacks;
    this.request = this.fetchSetup(context, initParams);
    self.clearTimeout(this.requestTimeout);
    config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
    this.requestTimeout = self.setTimeout(() => {
      if (this.callbacks) {
        this.abortInternal();
        this.callbacks.onTimeout(stats, context, this.response);
      }
    }, config.timeout);
    const fetchPromise = isPromise(this.request) ? this.request.then(self.fetch) : self.fetch(this.request);
    fetchPromise.then((response) => {
      var _this$callbacks2;
      this.response = this.loader = response;
      const first = Math.max(self.performance.now(), stats.loading.start);
      self.clearTimeout(this.requestTimeout);
      config.timeout = maxLoadTimeMs;
      this.requestTimeout = self.setTimeout(() => {
        if (this.callbacks) {
          this.abortInternal();
          this.callbacks.onTimeout(stats, context, this.response);
        }
      }, maxLoadTimeMs - (first - stats.loading.start));
      if (!response.ok) {
        const {
          status: status2,
          statusText
        } = response;
        throw new FetchError(statusText || "fetch, bad network response", status2, response);
      }
      stats.loading.first = first;
      stats.total = getContentLength(response.headers) || stats.total;
      const onProgress = (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onProgress;
      if (onProgress && isFiniteNumber(config.highWaterMark)) {
        return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
      }
      if (isArrayBuffer) {
        return response.arrayBuffer();
      }
      if (context.responseType === "json") {
        return response.json();
      }
      return response.text();
    }).then((responseData) => {
      var _this$callbacks3, _this$callbacks4;
      const response = this.response;
      if (!response) {
        throw new Error("loader destroyed");
      }
      self.clearTimeout(this.requestTimeout);
      stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
      const total = responseData[LENGTH];
      if (total) {
        stats.loaded = stats.total = total;
      }
      const loaderResponse = {
        url: response.url,
        data: responseData,
        code: response.status
      };
      const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
      if (onProgress && !isFiniteNumber(config.highWaterMark)) {
        onProgress(stats, context, responseData, response);
      }
      (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(loaderResponse, stats, context, response);
    }).catch((error) => {
      var _this$callbacks5;
      self.clearTimeout(this.requestTimeout);
      if (stats.aborted) {
        return;
      }
      const code = !error ? 0 : error.code || 0;
      const text = !error ? null : error.message;
      (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
        code,
        text
      }, context, error ? error.details : null, stats);
    });
  }
  getCacheAge() {
    let result = null;
    if (this.response) {
      const ageHeader = this.response.headers.get("age");
      result = ageHeader ? parseFloat(ageHeader) : null;
    }
    return result;
  }
  getResponseHeader(name) {
    return this.response ? this.response.headers.get(name) : null;
  }
  loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {
    const chunkCache = new ChunkCache();
    const reader = response.body.getReader();
    const pump = () => {
      return reader.read().then((data) => {
        if (data.done) {
          if (chunkCache.dataLength) {
            onProgress(stats, context, chunkCache.flush().buffer, response);
          }
          return Promise.resolve(new ArrayBuffer(0));
        }
        const chunk = data.value;
        const len = chunk.length;
        stats.loaded += len;
        if (len < highWaterMark || chunkCache.dataLength) {
          chunkCache.push(chunk);
          if (chunkCache.dataLength >= highWaterMark) {
            onProgress(stats, context, chunkCache.flush().buffer, response);
          }
        } else {
          onProgress(stats, context, chunk.buffer, response);
        }
        return pump();
      }).catch(() => {
        return Promise.reject();
      });
    };
    return pump();
  }
};
function getRequestParameters(context, signal) {
  const initParams = {
    method: "GET",
    mode: "cors",
    credentials: "same-origin",
    signal,
    headers: new self.Headers(_extends({}, context.headers))
  };
  if (context.rangeEnd) {
    initParams.headers.set("Range", "bytes=" + context.rangeStart + "-" + String(context.rangeEnd - 1));
  }
  return initParams;
}
function getByteRangeLength(byteRangeHeader) {
  const result = BYTERANGE.exec(byteRangeHeader);
  if (result) {
    return parseInt(result[2]) - parseInt(result[1]) + 1;
  }
}
function getContentLength(headers) {
  const contentRange = headers.get("Content-Range");
  if (contentRange) {
    const byteRangeLength = getByteRangeLength(contentRange);
    if (isFiniteNumber(byteRangeLength)) {
      return byteRangeLength;
    }
  }
  const contentLength = headers.get("Content-Length");
  if (contentLength) {
    return parseInt(contentLength);
  }
}
function getRequest(context, initParams) {
  return new self.Request(context.url, initParams);
}
var FetchError = class extends Error {
  constructor(message, code, details) {
    super(message);
    this.code = void 0;
    this.details = void 0;
    this.code = code;
    this.details = details;
  }
};
var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
var XhrLoader = class {
  constructor(config) {
    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 = config ? config.xhrSetup || null : null;
    this.stats = new LoadStats();
    this.retryDelay = 0;
  }
  destroy() {
    this.callbacks = null;
    this.abortInternal();
    this.loader = null;
    this.config = null;
    this.context = null;
    this.xhrSetup = null;
  }
  abortInternal() {
    const loader = this.loader;
    self.clearTimeout(this.requestTimeout);
    self.clearTimeout(this.retryTimeout);
    if (loader) {
      loader.onreadystatechange = null;
      loader.onprogress = null;
      if (loader.readyState !== 4) {
        this.stats.aborted = true;
        loader.abort();
      }
    }
  }
  abort() {
    var _this$callbacks;
    this.abortInternal();
    if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
      this.callbacks.onAbort(this.stats, this.context, this.loader);
    }
  }
  load(context, config, callbacks) {
    if (this.stats.loading.start) {
      throw new Error("Loader can only be used once.");
    }
    this.stats.loading.start = self.performance.now();
    this.context = context;
    this.config = config;
    this.callbacks = callbacks;
    this.loadInternal();
  }
  loadInternal() {
    const {
      config,
      context
    } = this;
    if (!config || !context) {
      return;
    }
    const xhr = this.loader = new self.XMLHttpRequest();
    const stats = this.stats;
    stats.loading.first = 0;
    stats.loaded = 0;
    stats.aborted = false;
    const xhrSetup = this.xhrSetup;
    if (xhrSetup) {
      Promise.resolve().then(() => {
        if (this.loader !== xhr || this.stats.aborted) return;
        return xhrSetup(xhr, context.url);
      }).catch((error) => {
        if (this.loader !== xhr || this.stats.aborted) return;
        xhr.open("GET", context.url, true);
        return xhrSetup(xhr, context.url);
      }).then(() => {
        if (this.loader !== xhr || this.stats.aborted) return;
        this.openAndSendXhr(xhr, context, config);
      }).catch((error) => {
        var _this$callbacks2;
        (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onError({
          code: xhr.status,
          text: error.message
        }, context, xhr, stats);
        return;
      });
    } else {
      this.openAndSendXhr(xhr, context, config);
    }
  }
  openAndSendXhr(xhr, context, config) {
    if (!xhr.readyState) {
      xhr.open("GET", context.url, true);
    }
    const headers = context.headers;
    const {
      maxTimeToFirstByteMs,
      maxLoadTimeMs
    } = config.loadPolicy;
    if (headers) {
      for (const header in headers) {
        xhr.setRequestHeader(header, headers[header]);
      }
    }
    if (context.rangeEnd) {
      xhr.setRequestHeader("Range", "bytes=" + context.rangeStart + "-" + (context.rangeEnd - 1));
    }
    xhr.onreadystatechange = this.readystatechange.bind(this);
    xhr.onprogress = this.loadprogress.bind(this);
    xhr.responseType = context.responseType;
    self.clearTimeout(this.requestTimeout);
    config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
    this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
    xhr.send();
  }
  readystatechange() {
    const {
      context,
      loader: xhr,
      stats
    } = this;
    if (!context || !xhr) {
      return;
    }
    const readyState = xhr.readyState;
    const config = this.config;
    if (stats.aborted) {
      return;
    }
    if (readyState >= 2) {
      if (stats.loading.first === 0) {
        stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
        if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
          self.clearTimeout(this.requestTimeout);
          config.timeout = config.loadPolicy.maxLoadTimeMs;
          this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
        }
      }
      if (readyState === 4) {
        self.clearTimeout(this.requestTimeout);
        xhr.onreadystatechange = null;
        xhr.onprogress = null;
        const status2 = xhr.status;
        const useResponseText = xhr.responseType === "text" ? xhr.responseText : null;
        if (status2 >= 200 && status2 < 300) {
          const data = useResponseText != null ? useResponseText : xhr.response;
          if (data != null) {
            var _this$callbacks3, _this$callbacks4;
            stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
            const len = xhr.responseType === "arraybuffer" ? data.byteLength : data.length;
            stats.loaded = stats.total = len;
            stats.bwEstimate = stats.total * 8e3 / (stats.loading.end - stats.loading.first);
            const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
            if (onProgress) {
              onProgress(stats, context, data, xhr);
            }
            const _response = {
              url: xhr.responseURL,
              data,
              code: status2
            };
            (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(_response, stats, context, xhr);
            return;
          }
        }
        const retryConfig = config.loadPolicy.errorRetry;
        const retryCount = stats.retry;
        const response = {
          url: context.url,
          data: void 0,
          code: status2
        };
        if (shouldRetry(retryConfig, retryCount, false, response)) {
          this.retry(retryConfig);
        } else {
          var _this$callbacks5;
          logger.error(`${status2} while loading ${context.url}`);
          (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
            code: status2,
            text: xhr.statusText
          }, context, xhr, stats);
        }
      }
    }
  }
  loadtimeout() {
    if (!this.config) return;
    const retryConfig = this.config.loadPolicy.timeoutRetry;
    const retryCount = this.stats.retry;
    if (shouldRetry(retryConfig, retryCount, true)) {
      this.retry(retryConfig);
    } else {
      var _this$context;
      logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);
      const callbacks = this.callbacks;
      if (callbacks) {
        this.abortInternal();
        callbacks.onTimeout(this.stats, this.context, this.loader);
      }
    }
  }
  retry(retryConfig) {
    const {
      context,
      stats
    } = this;
    this.retryDelay = getRetryDelay(retryConfig, stats.retry);
    stats.retry++;
    logger.warn(`${status ? "HTTP Status " + status : "Timeout"} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.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(event) {
    const stats = this.stats;
    stats.loaded = event.loaded;
    if (event.lengthComputable) {
      stats.total = event.total;
    }
  }
  getCacheAge() {
    let result = null;
    if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
      const ageHeader = this.loader.getResponseHeader("age");
      result = ageHeader ? parseFloat(ageHeader) : null;
    }
    return result;
  }
  getResponseHeader(name) {
    if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, "im").test(this.loader.getAllResponseHeaders())) {
      return this.loader.getResponseHeader(name);
    }
    return null;
  }
};
var defaultLoadPolicy = {
  maxTimeToFirstByteMs: 8e3,
  maxLoadTimeMs: 2e4,
  timeoutRetry: null,
  errorRetry: null
};
var hlsDefaultConfig = _objectSpread2(_objectSpread2({
  autoStartLoad: true,
  // used by stream-controller
  startPosition: -1,
  // used by stream-controller
  defaultAudioCodec: void 0,
  // used by stream-controller
  debug: false,
  // used by logger
  capLevelOnFPSDrop: false,
  // used by fps-controller
  capLevelToPlayerSize: false,
  // used by cap-level-controller
  ignoreDevicePixelRatio: false,
  // used by cap-level-controller
  maxDevicePixelRatio: Number.POSITIVE_INFINITY,
  // used by cap-level-controller
  preferManagedMediaSource: true,
  initialLiveManifestSize: 1,
  // used by stream-controller
  maxBufferLength: 30,
  // used by stream-controller
  backBufferLength: Infinity,
  // used by buffer-controller
  frontBufferFlushThreshold: Infinity,
  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: true,
  // used by gap-controller
  liveSyncDurationCount: 3,
  // used by latency-controller
  liveSyncOnStallIncrease: 1,
  // used by latency-controller
  liveMaxLatencyDurationCount: Infinity,
  // 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: false,
  // used by buffer-controller
  /**
   * @deprecated use backBufferLength
   */
  liveBackBufferLength: null,
  // used by buffer-controller
  maxMaxBufferLength: 600,
  // used by stream-controller
  enableWorker: true,
  // used by transmuxer
  workerPath: null,
  // used by transmuxer
  enableSoftwareAES: true,
  // used by decrypter
  startLevel: void 0,
  // used by level-controller
  startFragPrefetch: false,
  // used by stream-controller
  fpsDroppedMonitoringPeriod: 5e3,
  // used by fps-controller
  fpsDroppedMonitoringThreshold: 0.2,
  // used by fps-controller
  appendErrorMaxRetry: 3,
  // used by buffer-controller
  ignorePlaylistParsingErrors: false,
  loader: XhrLoader,
  // 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: AbrController,
  bufferController: BufferController,
  capLevelController: CapLevelController,
  errorController: ErrorController,
  fpsController: FPSController,
  stretchShortVideoTrack: false,
  // used by mp4-remuxer
  maxAudioFramesDrift: 1,
  // used by mp4-remuxer
  forceKeyFrameOnDiscontinuity: true,
  // 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: false,
  // used by abr-controller
  maxStarvationDelay: 4,
  // used by abr-controller
  maxLoadingDelay: 4,
  // used by abr-controller
  minAutoBitrate: 0,
  // used by hls
  emeEnabled: false,
  // used by eme-controller
  widevineLicenseUrl: void 0,
  // used by eme-controller
  drmSystems: {},
  // used by eme-controller
  drmSystemOptions: {},
  // used by eme-controller
  requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess,
  // used by eme-controller
  testBandwidth: true,
  progressive: false,
  lowLatencyMode: true,
  cmcd: void 0,
  enableDateRangeMetadataCues: true,
  enableEmsgMetadataCues: true,
  enableEmsgKLVMetadata: false,
  enableID3MetadataCues: true,
  enableInterstitialPlayback: true,
  interstitialAppendInPlace: true,
  interstitialLiveLookAhead: 10,
  useMediaCapabilities: true,
  certLoadPolicy: {
    default: defaultLoadPolicy
  },
  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: Infinity,
      maxLoadTimeMs: 2e4,
      timeoutRetry: {
        maxNumRetry: 2,
        retryDelayMs: 0,
        maxRetryDelayMs: 0
      },
      errorRetry: {
        maxNumRetry: 1,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 8e3
      }
    }
  },
  playlistLoadPolicy: {
    default: {
      maxTimeToFirstByteMs: 1e4,
      maxLoadTimeMs: 2e4,
      timeoutRetry: {
        maxNumRetry: 2,
        retryDelayMs: 0,
        maxRetryDelayMs: 0
      },
      errorRetry: {
        maxNumRetry: 2,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 8e3
      }
    }
  },
  fragLoadPolicy: {
    default: {
      maxTimeToFirstByteMs: 1e4,
      maxLoadTimeMs: 12e4,
      timeoutRetry: {
        maxNumRetry: 4,
        retryDelayMs: 0,
        maxRetryDelayMs: 0
      },
      errorRetry: {
        maxNumRetry: 6,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 8e3
      }
    }
  },
  steeringManifestLoadPolicy: {
    default: {
      maxTimeToFirstByteMs: 1e4,
      maxLoadTimeMs: 2e4,
      timeoutRetry: {
        maxNumRetry: 2,
        retryDelayMs: 0,
        maxRetryDelayMs: 0
      },
      errorRetry: {
        maxNumRetry: 1,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 8e3
      }
    }
  },
  interstitialAssetListLoadPolicy: {
    default: {
      maxTimeToFirstByteMs: 1e4,
      maxLoadTimeMs: 3e4,
      timeoutRetry: {
        maxNumRetry: 0,
        retryDelayMs: 0,
        maxRetryDelayMs: 0
      },
      errorRetry: {
        maxNumRetry: 0,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 8e3
      }
    }
  },
  // These default settings are deprecated in favor of the above policies
  // and are maintained for backwards compatibility
  manifestLoadingTimeOut: 1e4,
  manifestLoadingMaxRetry: 1,
  manifestLoadingRetryDelay: 1e3,
  manifestLoadingMaxRetryTimeout: 64e3,
  levelLoadingTimeOut: 1e4,
  levelLoadingMaxRetry: 4,
  levelLoadingRetryDelay: 1e3,
  levelLoadingMaxRetryTimeout: 64e3,
  fragLoadingTimeOut: 2e4,
  fragLoadingMaxRetry: 6,
  fragLoadingRetryDelay: 1e3,
  fragLoadingMaxRetryTimeout: 64e3
}, timelineConfig()), {}, {
  subtitleStreamController: SubtitleStreamController,
  subtitleTrackController: SubtitleTrackController,
  timelineController: TimelineController,
  audioStreamController: AudioStreamController,
  audioTrackController: AudioTrackController,
  emeController: EMEController,
  cmcdController: CMCDController,
  contentSteeringController: ContentSteeringController,
  interstitialsController: InterstitialsController
});
function timelineConfig() {
  return {
    cueHandler: Cues,
    // used by timeline-controller
    enableWebVTT: true,
    // used by timeline-controller
    enableIMSC1: true,
    // used by timeline-controller
    enableCEA708Captions: true,
    // 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: true
  };
}
function mergeConfig(defaultConfig, userConfig, logger4) {
  if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
    throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  }
  if (userConfig.liveMaxLatencyDurationCount !== void 0 && (userConfig.liveSyncDurationCount === void 0 || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
    throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  }
  if (userConfig.liveMaxLatencyDuration !== void 0 && (userConfig.liveSyncDuration === void 0 || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
    throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  }
  const defaultsCopy = deepCpy(defaultConfig);
  const deprecatedSettingTypes = ["manifest", "level", "frag"];
  const deprecatedSettings = ["TimeOut", "MaxRetry", "RetryDelay", "MaxRetryTimeout"];
  deprecatedSettingTypes.forEach((type2) => {
    const policyName = `${type2 === "level" ? "playlist" : type2}LoadPolicy`;
    const policyNotSet = userConfig[policyName] === void 0;
    const report = [];
    deprecatedSettings.forEach((setting) => {
      const deprecatedSetting = `${type2}Loading${setting}`;
      const value = userConfig[deprecatedSetting];
      if (value !== void 0 && policyNotSet) {
        report.push(deprecatedSetting);
        const settings = defaultsCopy[policyName].default;
        userConfig[policyName] = {
          default: settings
        };
        switch (setting) {
          case "TimeOut":
            settings.maxLoadTimeMs = value;
            settings.maxTimeToFirstByteMs = value;
            break;
          case "MaxRetry":
            settings.errorRetry.maxNumRetry = value;
            settings.timeoutRetry.maxNumRetry = value;
            break;
          case "RetryDelay":
            settings.errorRetry.retryDelayMs = value;
            settings.timeoutRetry.retryDelayMs = value;
            break;
          case "MaxRetryTimeout":
            settings.errorRetry.maxRetryDelayMs = value;
            settings.timeoutRetry.maxRetryDelayMs = value;
            break;
        }
      }
    });
    if (report.length) {
      logger4.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${stringify(userConfig[policyName])}`);
    }
  });
  return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
}
function deepCpy(obj) {
  if (obj && typeof obj === "object") {
    if (Array.isArray(obj)) {
      return obj.map(deepCpy);
    }
    return Object.keys(obj).reduce((result, key) => {
      result[key] = deepCpy(obj[key]);
      return result;
    }, {});
  }
  return obj;
}
function enableStreamingMode(config, logger4) {
  const currentLoader = config.loader;
  if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
    logger4.log("[config]: Custom loader detected, cannot enable progressive streaming");
    config.progressive = false;
  } else {
    const canStreamProgressively = fetchSupported();
    if (canStreamProgressively) {
      config.loader = FetchLoader;
      config.progressive = true;
      config.enableSoftwareAES = true;
      logger4.log("[config]: Progressive streaming enabled, using FetchLoader");
    }
  }
}
var MAX_START_GAP_JUMP = 2;
var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
var SKIP_BUFFER_RANGE_START = 0.05;
var TICK_INTERVAL$1 = 100;
var GapController = class extends TaskLoop {
  constructor(hls, fragmentTracker) {
    super("gap-controller", hls.logger);
    this.hls = null;
    this.fragmentTracker = null;
    this.media = null;
    this.mediaSource = void 0;
    this.nudgeRetry = 0;
    this.stallReported = false;
    this.stalled = null;
    this.moved = false;
    this.seeking = false;
    this.buffered = {};
    this.lastCurrentTime = 0;
    this.ended = 0;
    this.waiting = 0;
    this.onMediaPlaying = () => {
      this.ended = 0;
      this.waiting = 0;
    };
    this.onMediaWaiting = () => {
      var _this$media;
      if ((_this$media = this.media) != null && _this$media.seeking) {
        return;
      }
      this.waiting = self.performance.now();
      this.tick();
    };
    this.onMediaEnded = () => {
      if (this.hls) {
        var _this$media2;
        this.ended = ((_this$media2 = this.media) == null ? void 0 : _this$media2.currentTime) || 1;
        this.hls.trigger(Events.MEDIA_ENDED, {
          stalled: false
        });
      }
    };
    this.hls = hls;
    this.fragmentTracker = fragmentTracker;
    this.registerListeners();
  }
  registerListeners() {
    const {
      hls
    } = this;
    if (hls) {
      hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
      hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
      hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
    }
  }
  unregisterListeners() {
    const {
      hls
    } = this;
    if (hls) {
      hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
      hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
      hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
    }
  }
  destroy() {
    super.destroy();
    this.unregisterListeners();
    this.media = this.hls = this.fragmentTracker = null;
    this.mediaSource = void 0;
  }
  onMediaAttached(event, data) {
    this.setInterval(TICK_INTERVAL$1);
    this.mediaSource = data.mediaSource;
    const media = this.media = data.media;
    addEventListener(media, "playing", this.onMediaPlaying);
    addEventListener(media, "waiting", this.onMediaWaiting);
    addEventListener(media, "ended", this.onMediaEnded);
  }
  onMediaDetaching(event, data) {
    this.clearInterval();
    const {
      media
    } = this;
    if (media) {
      removeEventListener(media, "playing", this.onMediaPlaying);
      removeEventListener(media, "waiting", this.onMediaWaiting);
      removeEventListener(media, "ended", this.onMediaEnded);
      this.media = null;
    }
    this.mediaSource = void 0;
  }
  onBufferAppended(event, data) {
    this.buffered = data.timeRanges;
  }
  get hasBuffered() {
    return Object.keys(this.buffered).length > 0;
  }
  tick() {
    var _this$media3;
    if (!((_this$media3 = this.media) != null && _this$media3.readyState) || !this.hasBuffered) {
      return;
    }
    const currentTime = this.media.currentTime;
    this.poll(currentTime, this.lastCurrentTime);
    this.lastCurrentTime = currentTime;
  }
  /**
   * 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(currentTime, lastCurrentTime) {
    var _this$hls, _this$hls2;
    const config = (_this$hls = this.hls) == null ? void 0 : _this$hls.config;
    if (!config) {
      return;
    }
    const {
      media,
      stalled
    } = this;
    if (!media) {
      return;
    }
    const {
      seeking
    } = media;
    const seeked = this.seeking && !seeking;
    const beginSeek = !this.seeking && seeking;
    const pausedEndedOrHalted = media.paused && !seeking || media.ended || media.playbackRate === 0;
    this.seeking = seeking;
    if (currentTime !== lastCurrentTime) {
      if (lastCurrentTime) {
        this.ended = 0;
      }
      this.moved = true;
      if (!seeking) {
        this.nudgeRetry = 0;
        if (config.nudgeOnVideoHole && !pausedEndedOrHalted && currentTime > lastCurrentTime) {
          this.nudgeOnVideoHole(currentTime, lastCurrentTime);
        }
      }
      if (this.waiting === 0) {
        this.stallResolved(currentTime);
      }
      return;
    }
    if (beginSeek || seeked) {
      if (seeked) {
        this.stallResolved(currentTime);
      }
      return;
    }
    if (pausedEndedOrHalted) {
      this.nudgeRetry = 0;
      this.stallResolved(currentTime);
      if (!this.ended && media.ended && this.hls) {
        this.ended = currentTime || 1;
        this.hls.trigger(Events.MEDIA_ENDED, {
          stalled: false
        });
      }
      return;
    }
    if (!BufferHelper.getBuffered(media).length) {
      this.nudgeRetry = 0;
      return;
    }
    const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
    const nextStart = bufferInfo.nextStart || 0;
    const fragmentTracker = this.fragmentTracker;
    if (seeking && fragmentTracker && this.hls) {
      const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, currentTime);
      const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
      const noBufferHole = !nextStart || inFlightDependency || nextStart - currentTime > MAX_START_GAP_JUMP && !fragmentTracker.getPartialFragment(currentTime);
      if (hasEnoughBuffer || noBufferHole) {
        return;
      }
      this.moved = false;
    }
    const levelDetails = (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails;
    if (!this.moved && this.stalled !== null && fragmentTracker) {
      const isBuffered = bufferInfo.len > 0;
      if (!isBuffered && !nextStart) {
        return;
      }
      const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
      const isLive = !!(levelDetails != null && levelDetails.live);
      const maxStartGapJump = isLive ? levelDetails.targetduration * 2 : MAX_START_GAP_JUMP;
      const partialOrGap = fragmentTracker.getPartialFragment(currentTime);
      if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
        if (!media.paused) {
          this._trySkipBufferHole(partialOrGap);
        }
        return;
      }
    }
    const detectStallWithCurrentTimeMs = config.detectStallWithCurrentTimeMs;
    const tnow = self.performance.now();
    const tWaiting = this.waiting;
    if (stalled === null) {
      if (tWaiting > 0 && tnow - tWaiting < detectStallWithCurrentTimeMs) {
        this.stalled = tWaiting;
      } else {
        this.stalled = tnow;
      }
      return;
    }
    const stalledDuration = tnow - stalled;
    if (!seeking && (stalledDuration >= detectStallWithCurrentTimeMs || tWaiting) && this.hls) {
      var _this$mediaSource;
      if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) === "ended" && !(levelDetails != null && levelDetails.live) && Math.abs(currentTime - ((levelDetails == null ? void 0 : levelDetails.edge) || 0)) < 1) {
        if (this.ended) {
          return;
        }
        this.ended = currentTime || 1;
        this.hls.trigger(Events.MEDIA_ENDED, {
          stalled: true
        });
        return;
      }
      this._reportStall(bufferInfo);
      if (!this.media || !this.hls) {
        return;
      }
    }
    const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
    this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
  }
  stallResolved(currentTime) {
    const stalled = this.stalled;
    if (stalled && this.hls) {
      this.stalled = null;
      if (this.stallReported) {
        const stalledDuration = self.performance.now() - stalled;
        this.log(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);
        this.stallReported = false;
        this.waiting = 0;
        this.hls.trigger(Events.STALL_RESOLVED, {});
      }
    }
  }
  nudgeOnVideoHole(currentTime, lastCurrentTime) {
    var _this$buffered$audio;
    const videoSourceBuffered = this.buffered.video;
    if (this.hls && this.media && this.fragmentTracker && (_this$buffered$audio = this.buffered.audio) != null && _this$buffered$audio.length && videoSourceBuffered && videoSourceBuffered.length > 1 && currentTime > videoSourceBuffered.end(0)) {
      const audioBufferInfo = BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio), currentTime, 0);
      if (audioBufferInfo.len > 1 && lastCurrentTime >= audioBufferInfo.start) {
        const videoTimes = BufferHelper.timeRangesToArray(videoSourceBuffered);
        const lastBufferedIndex = BufferHelper.bufferedInfo(videoTimes, lastCurrentTime, 0).bufferedIndex;
        if (lastBufferedIndex > -1 && lastBufferedIndex < videoTimes.length - 1) {
          const bufferedIndex = BufferHelper.bufferedInfo(videoTimes, currentTime, 0).bufferedIndex;
          const holeStart = videoTimes[lastBufferedIndex].end;
          const holeEnd = videoTimes[lastBufferedIndex + 1].start;
          if ((bufferedIndex === -1 || bufferedIndex > lastBufferedIndex) && holeEnd - holeStart < 1 && // `maxBufferHole` may be too small and setting it to 0 should not disable this feature
          currentTime - holeStart < 2) {
            const error = new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${currentTime} hole: ${holeStart} -> ${holeEnd} buffered index: ${bufferedIndex}`);
            this.warn(error.message);
            this.media.currentTime += 1e-6;
            const frag = this.fragmentTracker.getPartialFragment(currentTime) || void 0;
            const bufferInfo = BufferHelper.bufferInfo(this.media, currentTime, 0);
            this.hls.trigger(Events.ERROR, {
              type: ErrorTypes.MEDIA_ERROR,
              details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
              fatal: false,
              error,
              reason: error.message,
              frag,
              buffer: bufferInfo.len,
              bufferInfo
            });
          }
        }
      }
    }
  }
  /**
   * 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(bufferInfo, stalledDurationMs) {
    var _this$hls3, _this$hls4;
    const {
      fragmentTracker,
      media
    } = this;
    const config = (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.config;
    if (!media || !fragmentTracker || !config) {
      return;
    }
    const currentTime = media.currentTime;
    const levelDetails = (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.latestLevelDetails;
    const partial = fragmentTracker.getPartialFragment(currentTime);
    if (partial || levelDetails != null && levelDetails.live && currentTime < levelDetails.fragmentStart) {
      const targetTime = this._trySkipBufferHole(partial);
      if (targetTime || !this.media) {
        return;
      }
    }
    const bufferedRanges = bufferInfo.buffered;
    if ((bufferedRanges && bufferedRanges.length > 1 && bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && bufferInfo.nextStart - currentTime < config.maxBufferHole) && (stalledDurationMs > config.highBufferWatchdogPeriod * 1e3 || this.waiting)) {
      this.warn("Trying to nudge playhead over buffer-hole");
      this._tryNudgeBuffer(bufferInfo);
    }
  }
  /**
   * 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(bufferInfo) {
    const {
      hls,
      media,
      stallReported,
      stalled
    } = this;
    if (!stallReported && stalled !== null && media && hls) {
      this.stallReported = true;
      const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${stringify(bufferInfo)})`);
      this.warn(error.message);
      hls.trigger(Events.ERROR, {
        type: ErrorTypes.MEDIA_ERROR,
        details: ErrorDetails.BUFFER_STALLED_ERROR,
        fatal: false,
        error,
        buffer: bufferInfo.len,
        bufferInfo,
        stalled: {
          start: stalled
        }
      });
    }
  }
  /**
   * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
   * @param partial - The partial fragment found at the current time (where playback is stalling).
   * @private
   */
  _trySkipBufferHole(partial) {
    var _this$hls5;
    const {
      fragmentTracker,
      media
    } = this;
    const config = (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.config;
    if (!media || !fragmentTracker || !config) {
      return 0;
    }
    const currentTime = media.currentTime;
    const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
    const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
    if (startTime && this.hls) {
      const bufferStarved = bufferInfo.len <= config.maxBufferHole;
      const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
      const gapLength = startTime - currentTime;
      if (gapLength > 0 && (bufferStarved || waiting)) {
        if (gapLength > config.maxBufferHole) {
          let startGap = false;
          if (currentTime === 0) {
            const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
            if (startFrag && startTime < startFrag.end) {
              startGap = true;
            }
          }
          if (!startGap) {
            const startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
            if (startProvisioned) {
              var _this$hls$loadLevelOb;
              if (!((_this$hls$loadLevelOb = this.hls.loadLevelObj) != null && _this$hls$loadLevelOb.details)) {
                return 0;
              }
              const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, startTime);
              if (inFlightDependency) {
                return 0;
              }
              let moreToLoad = false;
              let pos = startProvisioned.end;
              while (pos < startTime) {
                const provisioned = fragmentTracker.getPartialFragment(pos);
                if (provisioned) {
                  pos += provisioned.duration;
                } else {
                  moreToLoad = true;
                  break;
                }
              }
              if (moreToLoad) {
                return 0;
              }
            }
          }
        }
        const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
        this.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);
        this.moved = true;
        media.currentTime = targetTime;
        if (!(partial != null && partial.gap)) {
          const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);
          this.hls.trigger(Events.ERROR, {
            type: ErrorTypes.MEDIA_ERROR,
            details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
            fatal: false,
            error,
            reason: error.message,
            frag: partial || void 0,
            buffer: bufferInfo.len,
            bufferInfo
          });
        }
        return targetTime;
      }
    }
    return 0;
  }
  /**
   * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
   * @private
   */
  _tryNudgeBuffer(bufferInfo) {
    const {
      hls,
      media,
      nudgeRetry
    } = this;
    const config = hls == null ? void 0 : hls.config;
    if (!media || !config) {
      return 0;
    }
    const currentTime = media.currentTime;
    this.nudgeRetry++;
    if (nudgeRetry < config.nudgeMaxRetry) {
      const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
      const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);
      this.warn(error.message);
      media.currentTime = targetTime;
      hls.trigger(Events.ERROR, {
        type: ErrorTypes.MEDIA_ERROR,
        details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
        error,
        fatal: false,
        buffer: bufferInfo.len,
        bufferInfo
      });
    } else {
      const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);
      this.error(error.message);
      hls.trigger(Events.ERROR, {
        type: ErrorTypes.MEDIA_ERROR,
        details: ErrorDetails.BUFFER_STALLED_ERROR,
        error,
        fatal: true,
        buffer: bufferInfo.len,
        bufferInfo
      });
    }
  }
};
function getInFlightDependency(inFlightFragments, currentTime) {
  const main = inFlight(inFlightFragments.main);
  if (main && main.start <= currentTime) {
    return main;
  }
  const audio = inFlight(inFlightFragments.audio);
  if (audio && audio.start <= currentTime) {
    return audio;
  }
  return null;
}
function inFlight(inFlightData) {
  if (!inFlightData) {
    return null;
  }
  switch (inFlightData.state) {
    case State.IDLE:
    case State.STOPPED:
    case State.ENDED:
    case State.ERROR:
      return null;
  }
  return inFlightData.frag;
}
var MIN_CUE_DURATION = 0.25;
function getCueClass() {
  if (typeof self === "undefined") return void 0;
  return self.VTTCue || self.TextTrackCue;
}
function createCueWithDataFields(Cue, startTime, endTime, data, type2) {
  let cue = new Cue(startTime, endTime, "");
  try {
    cue.value = data;
    if (type2) {
      cue.type = type2;
    }
  } catch (e) {
    cue = new Cue(startTime, endTime, stringify(type2 ? _objectSpread2({
      type: type2
    }, data) : data));
  }
  return cue;
}
var MAX_CUE_ENDTIME = (() => {
  const Cue = getCueClass();
  try {
    Cue && new Cue(0, Number.POSITIVE_INFINITY, "");
  } catch (e) {
    return Number.MAX_VALUE;
  }
  return Number.POSITIVE_INFINITY;
})();
function hexToArrayBuffer(str) {
  return Uint8Array.from(str.replace(/^0x/, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")).buffer;
}
var ID3TrackController = class {
  constructor(hls) {
    this.hls = void 0;
    this.id3Track = null;
    this.media = null;
    this.dateRangeCuesAppended = {};
    this.removeCues = true;
    this.onEventCueEnter = () => {
      if (!this.hls) {
        return;
      }
      this.hls.trigger(Events.EVENT_CUE_ENTER, {});
    };
    this.hls = hls;
    this._registerListeners();
  }
  destroy() {
    this._unregisterListeners();
    this.id3Track = null;
    this.media = null;
    this.dateRangeCuesAppended = {};
    this.hls = this.onEventCueEnter = null;
  }
  _registerListeners() {
    const {
      hls
    } = this;
    hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
    hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
    hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
    hls.on(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  }
  _unregisterListeners() {
    const {
      hls
    } = this;
    hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
    hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
    hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
    hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
    hls.off(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  }
  // Add ID3 metatadata text track.
  onMediaAttaching(event, data) {
    var _data$overrides;
    this.media = data.media;
    if (((_data$overrides = data.overrides) == null ? void 0 : _data$overrides.cueRemoval) === false) {
      this.removeCues = false;
    }
  }
  onMediaAttached() {
    const details = this.hls.latestLevelDetails;
    if (details) {
      this.updateDateRangeCues(details);
    }
  }
  onMediaDetaching(event, data) {
    this.media = null;
    const transferringMedia = !!data.transferMedia;
    if (transferringMedia) {
      return;
    }
    if (this.id3Track) {
      if (this.removeCues) {
        clearCurrentCues(this.id3Track, this.onEventCueEnter);
      }
      this.id3Track = null;
    }
    this.dateRangeCuesAppended = {};
  }
  onManifestLoading() {
    this.dateRangeCuesAppended = {};
  }
  createTrack(media) {
    const track = this.getID3Track(media.textTracks);
    track.mode = "hidden";
    return track;
  }
  getID3Track(textTracks) {
    if (!this.media) {
      return;
    }
    for (let i = 0; i < textTracks.length; i++) {
      const textTrack = textTracks[i];
      if (textTrack.kind === "metadata" && textTrack.label === "id3") {
        sendAddTrackEvent(textTrack, this.media);
        return textTrack;
      }
    }
    return this.media.addTextTrack("metadata", "id3");
  }
  onFragParsingMetadata(event, data) {
    if (!this.media) {
      return;
    }
    const {
      hls: {
        config: {
          enableEmsgMetadataCues,
          enableID3MetadataCues
        }
      }
    } = this;
    if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
      return;
    }
    const {
      samples
    } = data;
    if (!this.id3Track) {
      this.id3Track = this.createTrack(this.media);
    }
    const Cue = getCueClass();
    if (!Cue) {
      return;
    }
    for (let i = 0; i < samples.length; i++) {
      const type2 = samples[i].type;
      if (type2 === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
        continue;
      }
      const frames = getId3Frames(samples[i].data);
      if (frames) {
        const startTime = samples[i].pts;
        let endTime = startTime + samples[i].duration;
        if (endTime > MAX_CUE_ENDTIME) {
          endTime = MAX_CUE_ENDTIME;
        }
        const timeDiff = endTime - startTime;
        if (timeDiff <= 0) {
          endTime = startTime + MIN_CUE_DURATION;
        }
        for (let j = 0; j < frames.length; j++) {
          const frame = frames[j];
          if (!isId3TimestampFrame(frame)) {
            this.updateId3CueEnds(startTime, type2);
            const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type2);
            if (cue) {
              this.id3Track.addCue(cue);
            }
          }
        }
      }
    }
  }
  updateId3CueEnds(startTime, type2) {
    var _this$id3Track;
    const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
    if (cues) {
      for (let i = cues.length; i--; ) {
        const cue = cues[i];
        if (cue.type === type2 && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
          cue.endTime = startTime;
        }
      }
    }
  }
  onBufferFlushing(event, {
    startOffset,
    endOffset,
    type: type2
  }) {
    const {
      id3Track,
      hls
    } = this;
    if (!hls) {
      return;
    }
    const {
      config: {
        enableEmsgMetadataCues,
        enableID3MetadataCues
      }
    } = hls;
    if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
      let predicate;
      if (type2 === "audio") {
        predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
      } else if (type2 === "video") {
        predicate = (cue) => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
      } else {
        predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
      }
      removeCuesInRange(id3Track, startOffset, endOffset, predicate);
    }
  }
  onLevelUpdated(event, {
    details
  }) {
    this.updateDateRangeCues(details, true);
  }
  onLevelPtsUpdated(event, data) {
    if (Math.abs(data.drift) > 0.01) {
      this.updateDateRangeCues(data.details);
    }
  }
  updateDateRangeCues(details, removeOldCues) {
    if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
      return;
    }
    const {
      id3Track
    } = this;
    const {
      dateRanges
    } = details;
    const ids = Object.keys(dateRanges);
    let dateRangeCuesAppended = this.dateRangeCuesAppended;
    if (id3Track && removeOldCues) {
      var _id3Track$cues;
      if ((_id3Track$cues = id3Track.cues) != null && _id3Track$cues.length) {
        const idsToRemove = Object.keys(dateRangeCuesAppended).filter((id) => !ids.includes(id));
        for (let i = idsToRemove.length; i--; ) {
          const id = idsToRemove[i];
          const cues = dateRangeCuesAppended[id].cues;
          delete dateRangeCuesAppended[id];
          Object.keys(cues).forEach((key) => {
            try {
              const cue = cues[key];
              cue.removeEventListener("enter", this.onEventCueEnter);
              id3Track.removeCue(cue);
            } catch (e) {
            }
          });
        }
      } else {
        dateRangeCuesAppended = this.dateRangeCuesAppended = {};
      }
    }
    const lastFragment = details.fragments[details.fragments.length - 1];
    if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
      return;
    }
    if (!this.id3Track) {
      this.id3Track = this.createTrack(this.media);
    }
    const Cue = getCueClass();
    for (let i = 0; i < ids.length; i++) {
      const id = ids[i];
      const dateRange = dateRanges[id];
      const startTime = dateRange.startTime;
      const appendedDateRangeCues = dateRangeCuesAppended[id];
      const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
      let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
      let endTime = MAX_CUE_ENDTIME;
      const {
        duration: duration5,
        endDate
      } = dateRange;
      if (endDate && duration5 !== null) {
        endTime = startTime + duration5;
        durationKnown = true;
      } else if (dateRange.endOnNext && !durationKnown) {
        const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id2) => {
          if (id2 !== dateRange.id) {
            const otherDateRange = dateRanges[id2];
            if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
              return otherDateRange;
            }
          }
          return candidateDateRange;
        }, null);
        if (nextDateRangeWithSameClass) {
          endTime = nextDateRangeWithSameClass.startTime;
          durationKnown = true;
        }
      }
      const attributes = Object.keys(dateRange.attr);
      for (let j = 0; j < attributes.length; j++) {
        const key = attributes[j];
        if (!isDateRangeCueAttribute(key)) {
          continue;
        }
        const cue = cues[key];
        if (cue) {
          if (durationKnown && !appendedDateRangeCues.durationKnown) {
            cue.endTime = endTime;
          } else if (Math.abs(cue.startTime - startTime) > 0.01) {
            cue.startTime = startTime;
            cue.endTime = endTime;
          }
        } else if (Cue) {
          let data = dateRange.attr[key];
          if (isSCTE35Attribute(key)) {
            data = hexToArrayBuffer(data);
          }
          const payload = {
            key,
            data
          };
          const _cue = createCueWithDataFields(Cue, startTime, endTime, payload, MetadataSchema.dateRange);
          if (_cue) {
            _cue.id = id;
            this.id3Track.addCue(_cue);
            cues[key] = _cue;
            if (this.hls.config.interstitialsController) {
              if (key === "X-ASSET-LIST" || key === "X-ASSET-URL") {
                _cue.addEventListener("enter", this.onEventCueEnter);
              }
            }
          }
        }
      }
      dateRangeCuesAppended[id] = {
        cues,
        dateRange,
        durationKnown
      };
    }
  }
};
var LatencyController = class {
  constructor(hls) {
    this.hls = void 0;
    this.config = void 0;
    this.media = null;
    this.currentTime = 0;
    this.stallCount = 0;
    this._latency = null;
    this._targetLatencyUpdated = false;
    this.onTimeupdate = () => {
      const {
        media
      } = this;
      const levelDetails = this.levelDetails;
      if (!media || !levelDetails) {
        return;
      }
      this.currentTime = media.currentTime;
      const latency = this.computeLatency();
      if (latency === null) {
        return;
      }
      this._latency = latency;
      const {
        lowLatencyMode,
        maxLiveSyncPlaybackRate
      } = this.config;
      if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
        return;
      }
      const targetLatency = this.targetLatency;
      if (targetLatency === null) {
        return;
      }
      const distanceFromTarget = latency - targetLatency;
      const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
      const inLiveRange = distanceFromTarget < liveMinLatencyDuration;
      if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
        const max = Math.min(2, Math.max(1, maxLiveSyncPlaybackRate));
        const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
        const playbackRate = Math.min(max, Math.max(1, rate));
        this.changeMediaPlaybackRate(media, playbackRate);
      } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
        this.changeMediaPlaybackRate(media, 1);
      }
    };
    this.hls = hls;
    this.config = hls.config;
    this.registerListeners();
  }
  get levelDetails() {
    var _this$hls;
    return ((_this$hls = this.hls) == null ? void 0 : _this$hls.latestLevelDetails) || null;
  }
  get latency() {
    return this._latency || 0;
  }
  get maxLatency() {
    const {
      config
    } = this;
    if (config.liveMaxLatencyDuration !== void 0) {
      return config.liveMaxLatencyDuration;
    }
    const levelDetails = this.levelDetails;
    return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  }
  get targetLatency() {
    const levelDetails = this.levelDetails;
    if (levelDetails === null || this.hls === null) {
      return null;
    }
    const {
      holdBack,
      partHoldBack,
      targetduration
    } = levelDetails;
    const {
      liveSyncDuration,
      liveSyncDurationCount,
      lowLatencyMode
    } = this.config;
    const userConfig = this.hls.userConfig;
    let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
    if (this._targetLatencyUpdated || userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
      targetLatency = liveSyncDuration !== void 0 ? liveSyncDuration : liveSyncDurationCount * targetduration;
    }
    const maxLiveSyncOnStallIncrease = targetduration;
    return targetLatency + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  }
  set targetLatency(latency) {
    this.stallCount = 0;
    this.config.liveSyncDuration = latency;
    this._targetLatencyUpdated = true;
  }
  get liveSyncPosition() {
    const liveEdge = this.estimateLiveEdge();
    const targetLatency = this.targetLatency;
    if (liveEdge === null || targetLatency === null) {
      return null;
    }
    const levelDetails = this.levelDetails;
    if (levelDetails === null) {
      return null;
    }
    const edge = levelDetails.edge;
    const syncPosition = liveEdge - targetLatency - this.edgeStalled;
    const min = edge - levelDetails.totalduration;
    const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
    return Math.min(Math.max(min, syncPosition), max);
  }
  get drift() {
    const levelDetails = this.levelDetails;
    if (levelDetails === null) {
      return 1;
    }
    return levelDetails.drift;
  }
  get edgeStalled() {
    const levelDetails = this.levelDetails;
    if (levelDetails === null) {
      return 0;
    }
    const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
    return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  }
  get forwardBufferLength() {
    const {
      media
    } = this;
    const levelDetails = this.levelDetails;
    if (!media || !levelDetails) {
      return 0;
    }
    const bufferedRanges = media.buffered.length;
    return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  }
  destroy() {
    this.unregisterListeners();
    this.onMediaDetaching();
    this.hls = null;
  }
  registerListeners() {
    const {
      hls
    } = this;
    if (!hls) {
      return;
    }
    hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
    hls.on(Events.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls
    } = this;
    if (!hls) {
      return;
    }
    hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
    hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
    hls.off(Events.ERROR, this.onError, this);
  }
  onMediaAttached(event, data) {
    this.media = data.media;
    this.media.addEventListener("timeupdate", this.onTimeupdate);
  }
  onMediaDetaching() {
    if (this.media) {
      this.media.removeEventListener("timeupdate", this.onTimeupdate);
      this.media = null;
    }
  }
  onManifestLoading() {
    this._latency = null;
    this.stallCount = 0;
  }
  onLevelUpdated(event, {
    details
  }) {
    if (details.advanced) {
      this.onTimeupdate();
    }
    if (!details.live && this.media) {
      this.media.removeEventListener("timeupdate", this.onTimeupdate);
    }
  }
  onError(event, data) {
    var _this$levelDetails;
    if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
      return;
    }
    this.stallCount++;
    if (this.hls && (_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
      this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency");
    }
  }
  changeMediaPlaybackRate(media, playbackRate) {
    var _this$hls2, _this$targetLatency;
    if (media.playbackRate === playbackRate) {
      return;
    }
    (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(_this$targetLatency = this.targetLatency) == null ? void 0 : _this$targetLatency.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${media.playbackRate} to ${playbackRate}`);
    media.playbackRate = playbackRate;
  }
  estimateLiveEdge() {
    const levelDetails = this.levelDetails;
    if (levelDetails === null) {
      return null;
    }
    return levelDetails.edge + levelDetails.age;
  }
  computeLatency() {
    const liveEdge = this.estimateLiveEdge();
    if (liveEdge === null) {
      return null;
    }
    return liveEdge - this.currentTime;
  }
};
var LevelController = class extends BasePlaylistController {
  constructor(hls, contentSteeringController) {
    super(hls, "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 = contentSteeringController;
    this._registerListeners();
  }
  _registerListeners() {
    const {
      hls
    } = this;
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
    hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
    hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
    hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
    hls.on(Events.ERROR, this.onError, this);
  }
  _unregisterListeners() {
    const {
      hls
    } = this;
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
    hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
    hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
    hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
    hls.off(Events.ERROR, this.onError, this);
  }
  destroy() {
    this._unregisterListeners();
    this.steering = null;
    this.resetLevels();
    super.destroy();
  }
  stopLoad() {
    const levels = this._levels;
    levels.forEach((level) => {
      level.loadError = 0;
      level.fragmentError = 0;
    });
    super.stopLoad();
  }
  resetLevels() {
    this._startLevel = void 0;
    this.manualLevelIndex = -1;
    this.currentLevelIndex = -1;
    this.currentLevel = null;
    this._levels = [];
    this._maxAutoLevel = -1;
  }
  onManifestLoading(event, data) {
    this.resetLevels();
  }
  onManifestLoaded(event, data) {
    const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
    const levels = [];
    const redundantSet = {};
    const generatePathwaySet = {};
    let resolutionFound = false;
    let videoCodecFound = false;
    let audioCodecFound = false;
    data.levels.forEach((levelParsed) => {
      var _videoCodec;
      const attributes = levelParsed.attrs;
      let {
        audioCodec,
        videoCodec
      } = levelParsed;
      if (audioCodec) {
        levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource) || void 0;
      }
      if (((_videoCodec = videoCodec) == null ? void 0 : _videoCodec.indexOf("avc1")) === 0) {
        videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
      }
      const {
        width: width2,
        height: height2,
        unknownCodecs
      } = levelParsed;
      let unknownUnsupportedCodecCount = unknownCodecs ? unknownCodecs.length : 0;
      if (unknownCodecs) {
        for (let i = unknownUnsupportedCodecCount; i--; ) {
          const unknownCodec = unknownCodecs[i];
          if (this.isAudioSupported(unknownCodec)) {
            levelParsed.audioCodec = audioCodec = audioCodec ? `${audioCodec},${unknownCodec}` : unknownCodec;
            unknownUnsupportedCodecCount--;
            sampleEntryCodesISO.audio[audioCodec.substring(0, 4)] = 2;
          } else if (this.isVideoSupported(unknownCodec)) {
            levelParsed.videoCodec = videoCodec = videoCodec ? `${videoCodec},${unknownCodec}` : unknownCodec;
            unknownUnsupportedCodecCount--;
            sampleEntryCodesISO.video[videoCodec.substring(0, 4)] = 2;
          }
        }
      }
      resolutionFound || (resolutionFound = !!(width2 && height2));
      videoCodecFound || (videoCodecFound = !!videoCodec);
      audioCodecFound || (audioCodecFound = !!audioCodec);
      if (unknownUnsupportedCodecCount || audioCodec && !this.isAudioSupported(audioCodec) || videoCodec && !this.isVideoSupported(videoCodec)) {
        this.log(`Some or all CODECS not supported "${attributes.CODECS}"`);
        return;
      }
      const {
        CODECS,
        "FRAME-RATE": FRAMERATE,
        "HDCP-LEVEL": HDCP,
        "PATHWAY-ID": PATHWAY,
        RESOLUTION,
        "VIDEO-RANGE": VIDEO_RANGE
      } = attributes;
      const contentSteeringPrefix = `${PATHWAY || "."}-`;
      const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;
      if (!redundantSet[levelKey]) {
        const level = this.createLevel(levelParsed);
        redundantSet[levelKey] = level;
        generatePathwaySet[levelKey] = 1;
        levels.push(level);
      } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs["PATHWAY-ID"]) {
        const pathwayCount = generatePathwaySet[levelKey] += 1;
        levelParsed.attrs["PATHWAY-ID"] = new Array(pathwayCount + 1).join(".");
        const level = this.createLevel(levelParsed);
        redundantSet[levelKey] = level;
        levels.push(level);
      } else {
        redundantSet[levelKey].addGroupId("audio", attributes.AUDIO);
        redundantSet[levelKey].addGroupId("text", attributes.SUBTITLES);
      }
    });
    this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  }
  createLevel(levelParsed) {
    const level = new Level(levelParsed);
    const supplemental = levelParsed.supplemental;
    if (supplemental != null && supplemental.videoCodec && !this.isVideoSupported(supplemental.videoCodec)) {
      const error = new Error(`SUPPLEMENTAL-CODECS not supported "${supplemental.videoCodec}"`);
      this.log(error.message);
      level.supportedResult = getUnsupportedResult(error, []);
    }
    return level;
  }
  isAudioSupported(codec) {
    return areCodecsMediaSourceSupported(codec, "audio", this.hls.config.preferManagedMediaSource);
  }
  isVideoSupported(codec) {
    return areCodecsMediaSourceSupported(codec, "video", this.hls.config.preferManagedMediaSource);
  }
  filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
    let audioTracks = [];
    let subtitleTracks = [];
    let levels = filteredLevels;
    if ((resolutionFound || videoCodecFound) && audioCodecFound) {
      levels = levels.filter(({
        videoCodec,
        videoRange,
        width: width2,
        height: height2
      }) => (!!videoCodec || !!(width2 && height2)) && isVideoRange(videoRange));
    }
    if (levels.length === 0) {
      Promise.resolve().then(() => {
        if (this.hls) {
          let message = "no level with compatible codecs found in manifest";
          let reason = message;
          if (data.levels.length) {
            reason = `one or more CODECS in variant not supported: ${stringify(data.levels.map((level) => level.attrs.CODECS).filter((value, index, array) => array.indexOf(value) === index))}`;
            this.warn(reason);
            message += ` (${reason})`;
          }
          const error = new Error(message);
          this.hls.trigger(Events.ERROR, {
            type: ErrorTypes.MEDIA_ERROR,
            details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
            fatal: true,
            url: data.url,
            error,
            reason
          });
        }
      });
      return;
    }
    if (data.audioTracks) {
      audioTracks = data.audioTracks.filter((track) => !track.audioCodec || this.isAudioSupported(track.audioCodec));
      assignTrackIdsByGroup(audioTracks);
    }
    if (data.subtitles) {
      subtitleTracks = data.subtitles;
      assignTrackIdsByGroup(subtitleTracks);
    }
    const unsortedLevels = levels.slice(0);
    levels.sort((a, b) => {
      if (a.attrs["HDCP-LEVEL"] !== b.attrs["HDCP-LEVEL"]) {
        return (a.attrs["HDCP-LEVEL"] || "") > (b.attrs["HDCP-LEVEL"] || "") ? 1 : -1;
      }
      if (resolutionFound && a.height !== b.height) {
        return a.height - b.height;
      }
      if (a.frameRate !== b.frameRate) {
        return a.frameRate - b.frameRate;
      }
      if (a.videoRange !== b.videoRange) {
        return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
      }
      if (a.videoCodec !== b.videoCodec) {
        const valueA = videoCodecPreferenceValue(a.videoCodec);
        const valueB = videoCodecPreferenceValue(b.videoCodec);
        if (valueA !== valueB) {
          return valueB - valueA;
        }
      }
      if (a.uri === b.uri && a.codecSet !== b.codecSet) {
        const valueA = codecsSetSelectionPreferenceValue(a.codecSet);
        const valueB = codecsSetSelectionPreferenceValue(b.codecSet);
        if (valueA !== valueB) {
          return valueB - valueA;
        }
      }
      if (a.averageBitrate !== b.averageBitrate) {
        return a.averageBitrate - b.averageBitrate;
      }
      return 0;
    });
    let firstLevelInPlaylist = unsortedLevels[0];
    if (this.steering) {
      levels = this.steering.filterParsedLevels(levels);
      if (levels.length !== unsortedLevels.length) {
        for (let i = 0; i < unsortedLevels.length; i++) {
          if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
            firstLevelInPlaylist = unsortedLevels[i];
            break;
          }
        }
      }
    }
    this._levels = levels;
    for (let i = 0; i < levels.length; i++) {
      if (levels[i] === firstLevelInPlaylist) {
        var _this$hls$userConfig;
        this._firstLevel = i;
        const firstLevelBitrate = firstLevelInPlaylist.bitrate;
        const bandwidthEstimate = this.hls.bandwidthEstimate;
        this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);
        if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === void 0) {
          const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
          if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === this.hls.abrEwmaDefaultEstimate) {
            this.hls.bandwidthEstimate = startingBwEstimate;
          }
        }
        break;
      }
    }
    const audioOnly3 = audioCodecFound && !videoCodecFound;
    const config = this.hls.config;
    const altAudioEnabled = !!(config.audioStreamController && config.audioTrackController);
    const edata = {
      levels,
      audioTracks,
      subtitleTracks,
      sessionData: data.sessionData,
      sessionKeys: data.sessionKeys,
      firstLevel: this._firstLevel,
      stats: data.stats,
      audio: audioCodecFound,
      video: videoCodecFound,
      altAudio: altAudioEnabled && !audioOnly3 && audioTracks.some((t2) => !!t2.url)
    };
    this.hls.trigger(Events.MANIFEST_PARSED, edata);
  }
  get levels() {
    if (this._levels.length === 0) {
      return null;
    }
    return this._levels;
  }
  get loadLevelObj() {
    return this.currentLevel;
  }
  get level() {
    return this.currentLevelIndex;
  }
  set level(newLevel) {
    const levels = this._levels;
    if (levels.length === 0) {
      return;
    }
    if (newLevel < 0 || newLevel >= levels.length) {
      const error = new Error("invalid level idx");
      const fatal = newLevel < 0;
      this.hls.trigger(Events.ERROR, {
        type: ErrorTypes.OTHER_ERROR,
        details: ErrorDetails.LEVEL_SWITCH_ERROR,
        level: newLevel,
        fatal,
        error,
        reason: error.message
      });
      if (fatal) {
        return;
      }
      newLevel = Math.min(newLevel, levels.length - 1);
    }
    const lastLevelIndex = this.currentLevelIndex;
    const lastLevel = this.currentLevel;
    const lastPathwayId = lastLevel ? lastLevel.attrs["PATHWAY-ID"] : void 0;
    const level = levels[newLevel];
    const pathwayId = level.attrs["PATHWAY-ID"];
    this.currentLevelIndex = newLevel;
    this.currentLevel = level;
    if (lastLevelIndex === newLevel && lastLevel && lastPathwayId === pathwayId) {
      return;
    }
    this.log(`Switching to level ${newLevel} (${level.height ? level.height + "p " : ""}${level.videoRange ? level.videoRange + " " : ""}${level.codecSet ? level.codecSet + " " : ""}@${level.bitrate})${pathwayId ? " with Pathway " + pathwayId : ""} from level ${lastLevelIndex}${lastPathwayId ? " with Pathway " + lastPathwayId : ""}`);
    const levelSwitchingData = {
      level: newLevel,
      attrs: level.attrs,
      details: level.details,
      bitrate: level.bitrate,
      averageBitrate: level.averageBitrate,
      maxBitrate: level.maxBitrate,
      realBitrate: level.realBitrate,
      width: level.width,
      height: level.height,
      codecSet: level.codecSet,
      audioCodec: level.audioCodec,
      videoCodec: level.videoCodec,
      audioGroups: level.audioGroups,
      subtitleGroups: level.subtitleGroups,
      loaded: level.loaded,
      loadError: level.loadError,
      fragmentError: level.fragmentError,
      name: level.name,
      id: level.id,
      uri: level.uri,
      url: level.url,
      urlId: 0,
      audioGroupIds: level.audioGroupIds,
      textGroupIds: level.textGroupIds
    };
    this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
    const levelDetails = level.details;
    if (!levelDetails || levelDetails.live) {
      const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
      this.loadPlaylist(hlsUrlParameters);
    }
  }
  get manualLevel() {
    return this.manualLevelIndex;
  }
  set manualLevel(newLevel) {
    this.manualLevelIndex = newLevel;
    if (this._startLevel === void 0) {
      this._startLevel = newLevel;
    }
    if (newLevel !== -1) {
      this.level = newLevel;
    }
  }
  get firstLevel() {
    return this._firstLevel;
  }
  set firstLevel(newLevel) {
    this._firstLevel = newLevel;
  }
  get startLevel() {
    if (this._startLevel === void 0) {
      const configStartLevel = this.hls.config.startLevel;
      if (configStartLevel !== void 0) {
        return configStartLevel;
      }
      return this.hls.firstAutoLevel;
    }
    return this._startLevel;
  }
  set startLevel(newLevel) {
    this._startLevel = newLevel;
  }
  get pathways() {
    if (this.steering) {
      return this.steering.pathways();
    }
    return [];
  }
  get pathwayPriority() {
    if (this.steering) {
      return this.steering.pathwayPriority;
    }
    return null;
  }
  set pathwayPriority(pathwayPriority) {
    if (this.steering) {
      const pathwaysList = this.steering.pathways();
      const filteredPathwayPriority = pathwayPriority.filter((pathwayId) => {
        return pathwaysList.indexOf(pathwayId) !== -1;
      });
      if (pathwayPriority.length < 1) {
        this.warn(`pathwayPriority ${pathwayPriority} should contain at least one pathway from list: ${pathwaysList}`);
        return;
      }
      this.steering.pathwayPriority = filteredPathwayPriority;
    }
  }
  onError(event, data) {
    if (data.fatal || !data.context) {
      return;
    }
    if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
      this.checkRetry(data);
    }
  }
  // reset errors on the successful load of a fragment
  onFragBuffered(event, {
    frag
  }) {
    if (frag !== void 0 && frag.type === PlaylistLevelType.MAIN) {
      const el = frag.elementaryStreams;
      if (!Object.keys(el).some((type2) => !!el[type2])) {
        return;
      }
      const level = this._levels[frag.level];
      if (level != null && level.loadError) {
        this.log(`Resetting level error count of ${level.loadError} on frag buffered`);
        level.loadError = 0;
      }
    }
  }
  onLevelLoaded(event, data) {
    var _data$deliveryDirecti2;
    const {
      level,
      details
    } = data;
    const curLevel = data.levelInfo;
    if (!curLevel) {
      var _data$deliveryDirecti;
      this.warn(`Invalid level index ${level}`);
      if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
        details.deltaUpdateFailed = true;
      }
      return;
    }
    if (curLevel === this.currentLevel || data.withoutMultiVariant) {
      if (curLevel.fragmentError === 0) {
        curLevel.loadError = 0;
      }
      let previousDetails = curLevel.details;
      if (previousDetails === data.details && previousDetails.advanced) {
        previousDetails = void 0;
      }
      this.playlistLoaded(level, data, previousDetails);
    } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
      details.deltaUpdateFailed = true;
    }
  }
  loadPlaylist(hlsUrlParameters) {
    super.loadPlaylist();
    if (this.shouldLoadPlaylist(this.currentLevel)) {
      this.scheduleLoading(this.currentLevel, hlsUrlParameters);
    }
  }
  loadingPlaylist(currentLevel, hlsUrlParameters) {
    super.loadingPlaylist(currentLevel, hlsUrlParameters);
    const url = this.getUrlWithDirectives(currentLevel.uri, hlsUrlParameters);
    const currentLevelIndex = this.currentLevelIndex;
    const pathwayId = currentLevel.attrs["PATHWAY-ID"];
    const details = currentLevel.details;
    const age = details == null ? void 0 : details.age;
    this.log(`Loading level index ${currentLevelIndex}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== void 0 ? " at sn " + hlsUrlParameters.msn + " part " + hlsUrlParameters.part : ""}${pathwayId ? " Pathway " + pathwayId : ""}${age && details.live ? " age " + age.toFixed(1) + (details.type ? " " + details.type || "" : "") : ""} ${url}`);
    this.hls.trigger(Events.LEVEL_LOADING, {
      url,
      level: currentLevelIndex,
      levelInfo: currentLevel,
      pathwayId: currentLevel.attrs["PATHWAY-ID"],
      id: 0,
      // Deprecated Level urlId
      deliveryDirectives: hlsUrlParameters || null
    });
  }
  get nextLoadLevel() {
    if (this.manualLevelIndex !== -1) {
      return this.manualLevelIndex;
    } else {
      return this.hls.nextAutoLevel;
    }
  }
  set nextLoadLevel(nextLevel) {
    this.level = nextLevel;
    if (this.manualLevelIndex === -1) {
      this.hls.nextAutoLevel = nextLevel;
    }
  }
  removeLevel(levelIndex) {
    var _this$currentLevel;
    if (this._levels.length === 1) {
      return;
    }
    const levels = this._levels.filter((level, index) => {
      if (index !== levelIndex) {
        return true;
      }
      if (this.steering) {
        this.steering.removeLevel(level);
      }
      if (level === this.currentLevel) {
        this.currentLevel = null;
        this.currentLevelIndex = -1;
        if (level.details) {
          level.details.fragments.forEach((f) => f.level = -1);
        }
      }
      return false;
    });
    reassignFragmentLevelIndexes(levels);
    this._levels = levels;
    if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
      this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
    }
    if (this.manualLevelIndex > -1) {
      this.manualLevelIndex = this.currentLevelIndex;
    }
    const maxLevel = levels.length - 1;
    this._firstLevel = Math.min(this._firstLevel, maxLevel);
    if (this._startLevel) {
      this._startLevel = Math.min(this._startLevel, maxLevel);
    }
    this.hls.trigger(Events.LEVELS_UPDATED, {
      levels
    });
  }
  onLevelsUpdated(event, {
    levels
  }) {
    this._levels = levels;
  }
  checkMaxAutoUpdated() {
    const {
      autoLevelCapping,
      maxAutoLevel,
      maxHdcpLevel
    } = this.hls;
    if (this._maxAutoLevel !== maxAutoLevel) {
      this._maxAutoLevel = maxAutoLevel;
      this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
        autoLevelCapping,
        levels: this.levels,
        maxAutoLevel,
        minAutoLevel: this.hls.minAutoLevel,
        maxHdcpLevel
      });
    }
  }
};
function assignTrackIdsByGroup(tracks) {
  const groups = {};
  tracks.forEach((track) => {
    const groupId = track.groupId || "";
    track.id = groups[groupId] = groups[groupId] || 0;
    groups[groupId]++;
  });
}
function getSourceBuffer() {
  return self.SourceBuffer || self.WebKitSourceBuffer;
}
function isMSESupported() {
  const mediaSource = getMediaSource();
  if (!mediaSource) {
    return false;
  }
  const sourceBuffer = getSourceBuffer();
  return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === "function" && typeof sourceBuffer.prototype.remove === "function";
}
function isSupported() {
  if (!isMSESupported()) {
    return false;
  }
  const mediaSource = getMediaSource();
  return typeof (mediaSource == null ? void 0 : mediaSource.isTypeSupported) === "function" && (["avc1.42E01E,mp4a.40.2", "av01.0.01M.08", "vp09.00.50.08"].some((codecsForVideoContainer) => mediaSource.isTypeSupported(mimeTypeForCodec(codecsForVideoContainer, "video"))) || ["mp4a.40.2", "fLaC"].some((codecForAudioContainer) => mediaSource.isTypeSupported(mimeTypeForCodec(codecForAudioContainer, "audio"))));
}
function changeTypeSupported() {
  var _sourceBuffer$prototy;
  const sourceBuffer = getSourceBuffer();
  return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === "function";
}
var TICK_INTERVAL = 100;
var StreamController = class extends BaseStreamController {
  constructor(hls, fragmentTracker, keyLoader) {
    super(hls, fragmentTracker, keyLoader, "stream-controller", PlaylistLevelType.MAIN);
    this.audioCodecSwap = false;
    this.level = -1;
    this._forceStartLoad = false;
    this._hasEnoughToStart = false;
    this.altAudio = 0;
    this.audioOnly = false;
    this.fragPlaying = null;
    this.fragLastKbps = 0;
    this.couldBacktrack = false;
    this.backtrackFragment = null;
    this.audioCodecSwitch = false;
    this.videoBuffer = null;
    this.onMediaPlaying = () => {
      this.tick();
    };
    this.onMediaSeeked = () => {
      const media = this.media;
      const currentTime = media ? media.currentTime : null;
      if (currentTime === null || !isFiniteNumber(currentTime)) {
        return;
      }
      this.log(`Media seeked to ${currentTime.toFixed(3)}`);
      if (!this.getBufferedFrag(currentTime)) {
        return;
      }
      const bufferInfo = this.getFwdBufferInfoAtPos(media, currentTime, PlaylistLevelType.MAIN, 0);
      if (bufferInfo === null || bufferInfo.len === 0) {
        this.warn(`Main forward buffer length at ${currentTime} on "seeked" event ${bufferInfo ? bufferInfo.len : "empty"})`);
        return;
      }
      this.tick();
    };
    this.registerListeners();
  }
  registerListeners() {
    super.registerListeners();
    const {
      hls
    } = this;
    hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
    hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
    hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
    hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
    hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
    hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
    hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
    hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
    hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  }
  unregisterListeners() {
    super.unregisterListeners();
    const {
      hls
    } = this;
    hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
    hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
    hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
    hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
    hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
    hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
    hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
    hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
    hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  }
  onHandlerDestroying() {
    this.onMediaPlaying = this.onMediaSeeked = null;
    this.unregisterListeners();
    super.onHandlerDestroying();
  }
  startLoad(startPosition, skipSeekToStartPosition) {
    if (this.levels) {
      const {
        lastCurrentTime,
        hls
      } = this;
      this.stopLoad();
      this.setInterval(TICK_INTERVAL);
      this.level = -1;
      if (!this.startFragRequested) {
        let startLevel = hls.startLevel;
        if (startLevel === -1) {
          if (hls.config.testBandwidth && this.levels.length > 1) {
            startLevel = 0;
            this.bitrateTest = true;
          } else {
            startLevel = hls.firstAutoLevel;
          }
        }
        hls.nextLoadLevel = startLevel;
        this.level = hls.loadLevel;
        this._hasEnoughToStart = !!skipSeekToStartPosition;
      }
      if (lastCurrentTime > 0 && startPosition === -1 && !skipSeekToStartPosition) {
        this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
        startPosition = lastCurrentTime;
      }
      this.state = State.IDLE;
      this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
      this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
      this.tick();
    } else {
      this._forceStartLoad = true;
      this.state = State.STOPPED;
    }
  }
  stopLoad() {
    this._forceStartLoad = false;
    super.stopLoad();
  }
  doTick() {
    switch (this.state) {
      case State.WAITING_LEVEL: {
        const {
          levels,
          level
        } = this;
        const currentLevel = levels == null ? void 0 : levels[level];
        const details = currentLevel == null ? void 0 : currentLevel.details;
        if (details && (!details.live || this.levelLastLoaded === currentLevel && !this.waitForLive(currentLevel))) {
          if (this.waitForCdnTuneIn(details)) {
            break;
          }
          this.state = State.IDLE;
          break;
        } else if (this.hls.nextLoadLevel !== this.level) {
          this.state = State.IDLE;
          break;
        }
        break;
      }
      case State.FRAG_LOADING_WAITING_RETRY:
        {
          var _this$media;
          const now2 = self.performance.now();
          const retryDate = this.retryDate;
          if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
            const {
              levels,
              level
            } = this;
            const currentLevel = levels == null ? void 0 : levels[level];
            this.resetStartWhenNotLoaded(currentLevel || null);
            this.state = State.IDLE;
          }
        }
        break;
    }
    if (this.state === State.IDLE) {
      this.doTickIdle();
    }
    this.onTickEnd();
  }
  onTickEnd() {
    var _this$media2;
    super.onTickEnd();
    if ((_this$media2 = this.media) != null && _this$media2.readyState && this.media.seeking === false) {
      this.lastCurrentTime = this.media.currentTime;
    }
    this.checkFragmentChanged();
  }
  doTickIdle() {
    const {
      hls,
      levelLastLoaded,
      levels,
      media
    } = this;
    if (levelLastLoaded === null || !media && !this.primaryPrefetch && (this.startFragRequested || !hls.config.startFragPrefetch)) {
      return;
    }
    if (this.altAudio && this.audioOnly) {
      return;
    }
    const level = this.buffering ? hls.nextLoadLevel : hls.loadLevel;
    if (!(levels != null && levels[level])) {
      return;
    }
    const levelInfo = levels[level];
    const bufferInfo = this.getMainFwdBufferInfo();
    if (bufferInfo === null) {
      return;
    }
    const lastDetails = this.getLevelDetails();
    if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
      const data = {};
      if (this.altAudio === 2) {
        data.type = "video";
      }
      this.hls.trigger(Events.BUFFER_EOS, data);
      this.state = State.ENDED;
      return;
    }
    if (!this.buffering) {
      return;
    }
    if (hls.loadLevel !== level && hls.manualLevel === -1) {
      this.log(`Adapting to level ${level} from level ${this.level}`);
    }
    this.level = hls.nextLoadLevel = level;
    const levelDetails = levelInfo.details;
    if (!levelDetails || this.state === State.WAITING_LEVEL || this.waitForLive(levelInfo)) {
      this.level = level;
      this.state = State.WAITING_LEVEL;
      this.startFragRequested = false;
      return;
    }
    const bufferLen = bufferInfo.len;
    const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
    if (bufferLen >= maxBufLen) {
      return;
    }
    if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
      this.backtrackFragment = null;
    }
    const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
    let frag = this.getNextFragment(targetBufferTime, levelDetails);
    if (this.couldBacktrack && !this.fragPrevious && frag && isMediaFragment(frag) && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
      var _this$backtrackFragme;
      const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
      const fragIdx = backtrackSn - levelDetails.startSN;
      const backtrackFrag = levelDetails.fragments[fragIdx - 1];
      if (backtrackFrag && frag.cc === backtrackFrag.cc) {
        frag = backtrackFrag;
        this.fragmentTracker.removeFragment(backtrackFrag);
      }
    } else if (this.backtrackFragment && bufferInfo.len) {
      this.backtrackFragment = null;
    }
    if (frag && this.isLoopLoading(frag, targetBufferTime)) {
      const gapStart = frag.gap;
      if (!gapStart) {
        const type2 = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
        const mediaBuffer = (type2 === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
        if (mediaBuffer) {
          this.afterBufferFlushed(mediaBuffer, type2, PlaylistLevelType.MAIN);
        }
      }
      frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
    }
    if (!frag) {
      return;
    }
    if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
      frag = frag.initSegment;
    }
    this.loadFragment(frag, levelInfo, targetBufferTime);
  }
  loadFragment(frag, level, targetBufferTime) {
    const fragState = this.fragmentTracker.getState(frag);
    if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
      if (!isMediaFragment(frag)) {
        this._loadInitSegment(frag, level);
      } else if (this.bitrateTest) {
        this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);
        this._loadBitrateTestFrag(frag, level);
      } else {
        super.loadFragment(frag, level, targetBufferTime);
      }
    } else {
      this.clearTrackerIfNeeded(frag);
    }
  }
  getBufferedFrag(position) {
    return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  }
  followingBufferedFrag(frag) {
    if (frag) {
      return this.getBufferedFrag(frag.end + 0.5);
    }
    return 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,
      media
    } = this;
    if (media != null && media.readyState) {
      let fetchdelay;
      const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
      if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
        this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
      }
      const levelDetails = this.getLevelDetails();
      if (levelDetails != null && levelDetails.live) {
        const bufferInfo = this.getMainFwdBufferInfo();
        if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
          return;
        }
      }
      if (!media.paused && levels) {
        const nextLevelId = this.hls.nextLoadLevel;
        const nextLevel = levels[nextLevelId];
        const fragLastKbps = this.fragLastKbps;
        if (fragLastKbps && this.fragCurrent) {
          fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1e3 * fragLastKbps) + 1;
        } else {
          fetchdelay = 0;
        }
      } else {
        fetchdelay = 0;
      }
      const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
      if (bufferedFrag) {
        const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
        if (nextBufferedFrag) {
          this.abortCurrentFrag();
          const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
          const fragDuration = nextBufferedFrag.duration;
          const startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * (this.couldBacktrack ? 0.5 : 0.125)), fragDuration * (this.couldBacktrack ? 0.75 : 0.25)));
          this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
        }
      }
    }
  }
  abortCurrentFrag() {
    const fragCurrent = this.fragCurrent;
    this.fragCurrent = null;
    this.backtrackFragment = null;
    if (fragCurrent) {
      fragCurrent.abortRequests();
      this.fragmentTracker.removeFragment(fragCurrent);
    }
    switch (this.state) {
      case State.KEY_LOADING:
      case State.FRAG_LOADING:
      case State.FRAG_LOADING_WAITING_RETRY:
      case State.PARSING:
      case State.PARSED:
        this.state = State.IDLE;
        break;
    }
    this.nextLoadPosition = this.getLoadPosition();
  }
  flushMainBuffer(startOffset, endOffset) {
    super.flushMainBuffer(startOffset, endOffset, this.altAudio === 2 ? "video" : null);
  }
  onMediaAttached(event, data) {
    super.onMediaAttached(event, data);
    const media = data.media;
    addEventListener(media, "playing", this.onMediaPlaying);
    addEventListener(media, "seeked", this.onMediaSeeked);
  }
  onMediaDetaching(event, data) {
    const {
      media
    } = this;
    if (media) {
      removeEventListener(media, "playing", this.onMediaPlaying);
      removeEventListener(media, "seeked", this.onMediaSeeked);
    }
    this.videoBuffer = null;
    this.fragPlaying = null;
    super.onMediaDetaching(event, data);
    const transferringMedia = !!data.transferMedia;
    if (transferringMedia) {
      return;
    }
    this._hasEnoughToStart = false;
  }
  onManifestLoading() {
    super.onManifestLoading();
    this.log("Trigger BUFFER_RESET");
    this.hls.trigger(Events.BUFFER_RESET, void 0);
    this.couldBacktrack = false;
    this.fragLastKbps = 0;
    this.fragPlaying = this.backtrackFragment = null;
    this.altAudio = 0;
    this.audioOnly = false;
  }
  onManifestParsed(event, data) {
    let aac2 = false;
    let heaac = false;
    data.levels.forEach((level) => {
      const codec = level.audioCodec;
      if (codec) {
        aac2 = aac2 || codec.indexOf("mp4a.40.2") !== -1;
        heaac = heaac || codec.indexOf("mp4a.40.5") !== -1;
      }
    });
    this.audioCodecSwitch = aac2 && heaac && !changeTypeSupported();
    if (this.audioCodecSwitch) {
      this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC");
    }
    this.levels = data.levels;
    this.startFragRequested = false;
  }
  onLevelLoading(event, data) {
    const {
      levels
    } = this;
    if (!levels || this.state !== State.IDLE) {
      return;
    }
    const level = data.levelInfo;
    if (!level.details || level.details.live && (this.levelLastLoaded !== level || level.details.expired) || this.waitForCdnTuneIn(level.details)) {
      this.state = State.WAITING_LEVEL;
    }
  }
  onLevelLoaded(event, data) {
    var _curLevel$details;
    const {
      levels,
      startFragRequested
    } = this;
    const newLevelId = data.level;
    const newDetails = data.details;
    const duration5 = newDetails.totalduration;
    if (!levels) {
      this.warn(`Levels were reset while loading level ${newLevelId}`);
      return;
    }
    this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration5}`);
    const curLevel = data.levelInfo;
    const fragCurrent = this.fragCurrent;
    if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
      if (fragCurrent.level !== data.level && fragCurrent.loader) {
        this.abortCurrentFrag();
      }
    }
    let sliding = 0;
    if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
      var _this$levelLastLoaded;
      this.checkLiveUpdate(newDetails);
      if (newDetails.deltaUpdateFailed) {
        return;
      }
      sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
    }
    curLevel.details = newDetails;
    this.levelLastLoaded = curLevel;
    if (!startFragRequested) {
      this.setStartPosition(newDetails, sliding);
    }
    this.hls.trigger(Events.LEVEL_UPDATED, {
      details: newDetails,
      level: newLevelId
    });
    if (this.state === State.WAITING_LEVEL) {
      if (this.waitForCdnTuneIn(newDetails)) {
        return;
      }
      this.state = State.IDLE;
    }
    if (startFragRequested && newDetails.live) {
      this.synchronizeToLiveEdge(newDetails);
    }
    this.tick();
  }
  synchronizeToLiveEdge(levelDetails) {
    const {
      config,
      media
    } = this;
    if (!media) {
      return;
    }
    const liveSyncPosition = this.hls.liveSyncPosition;
    const currentTime = this.getLoadPosition();
    const start2 = levelDetails.fragmentStart;
    const end = levelDetails.edge;
    const withinSlidingWindow = currentTime >= start2 - config.maxFragLookUpTolerance && currentTime <= end;
    if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
      const maxLatency = config.liveMaxLatencyDuration !== void 0 ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
      if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
        if (!this._hasEnoughToStart) {
          this.nextLoadPosition = liveSyncPosition;
        }
        if (media.readyState) {
          this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
          media.currentTime = liveSyncPosition;
        }
      }
    }
  }
  _handleFragmentLoadProgress(data) {
    var _frag$initSegment;
    const frag = data.frag;
    const {
      part,
      payload
    } = data;
    const {
      levels
    } = this;
    if (!levels) {
      this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
      return;
    }
    const currentLevel = levels[frag.level];
    if (!currentLevel) {
      this.warn(`Level ${frag.level} not found on progress`);
      return;
    }
    const details = currentLevel.details;
    if (!details) {
      this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);
      this.fragmentTracker.removeFragment(frag);
      return;
    }
    const videoCodec = currentLevel.videoCodec;
    const accurateTimeOffset = details.PTSKnown || !details.live;
    const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
    const audioCodec = this._getAudioCodec(currentLevel);
    const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
    const partIndex = part ? part.index : -1;
    const partial = partIndex !== -1;
    const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
    const initPTS = this.initPTS[frag.cc];
    transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  }
  onAudioTrackSwitching(event, data) {
    const hls = this.hls;
    const fromAltAudio = this.altAudio === 2;
    const altAudio = useAlternateAudio(data.url, hls);
    if (!altAudio) {
      if (this.mediaBuffer !== this.media) {
        this.log("Switching on main audio, use media.buffered to schedule main fragment loading");
        this.mediaBuffer = this.media;
        const fragCurrent = this.fragCurrent;
        if (fragCurrent) {
          this.log("Switching to main audio track, cancel main fragment load");
          fragCurrent.abortRequests();
          this.fragmentTracker.removeFragment(fragCurrent);
        }
        this.resetTransmuxer();
        this.resetLoadingState();
      } else if (this.audioOnly) {
        this.resetTransmuxer();
      }
      if (fromAltAudio) {
        this.fragmentTracker.removeAllFragments();
        hls.once(Events.BUFFER_FLUSHED, () => {
          var _this$hls;
          (_this$hls = this.hls) == null ? void 0 : _this$hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
        });
        hls.trigger(Events.BUFFER_FLUSHING, {
          startOffset: 0,
          endOffset: Number.POSITIVE_INFINITY,
          type: null
        });
        return;
      }
      hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
    } else {
      this.altAudio = 1;
    }
  }
  onAudioTrackSwitched(event, data) {
    const altAudio = useAlternateAudio(data.url, this.hls);
    if (altAudio) {
      const videoBuffer = this.videoBuffer;
      if (videoBuffer && this.mediaBuffer !== videoBuffer) {
        this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading");
        this.mediaBuffer = videoBuffer;
      }
    }
    this.altAudio = altAudio ? 2 : 0;
    this.tick();
  }
  onBufferCreated(event, data) {
    const tracks = data.tracks;
    let mediaTrack;
    let name;
    let alternate = false;
    for (const type2 in tracks) {
      const track = tracks[type2];
      if (track.id === "main") {
        name = type2;
        mediaTrack = track;
        if (type2 === "video") {
          const videoTrack = tracks[type2];
          if (videoTrack) {
            this.videoBuffer = videoTrack.buffer;
          }
        }
      } else {
        alternate = true;
      }
    }
    if (alternate && mediaTrack) {
      this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);
      this.mediaBuffer = mediaTrack.buffer;
    } else {
      this.mediaBuffer = this.media;
    }
  }
  onFragBuffered(event, data) {
    const {
      frag,
      part
    } = data;
    const bufferedMainFragment = frag.type === PlaylistLevelType.MAIN;
    if (bufferedMainFragment) {
      if (this.fragContextChanged(frag)) {
        this.warn(`Fragment ${frag.sn}${part ? " p: " + part.index : ""} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);
        if (this.state === State.PARSED) {
          this.state = State.IDLE;
        }
        return;
      }
      const stats = part ? part.stats : frag.stats;
      this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
      if (isMediaFragment(frag)) {
        this.fragPrevious = frag;
      }
      this.fragBufferedComplete(frag, part);
    }
    const media = this.media;
    if (!media) {
      return;
    }
    if (!this._hasEnoughToStart && BufferHelper.getBuffered(media).length) {
      this._hasEnoughToStart = true;
      this.seekToStartPos();
    }
    if (bufferedMainFragment) {
      this.tick();
    }
  }
  get hasEnoughToStart() {
    return this._hasEnoughToStart;
  }
  onError(event, data) {
    var _data$context;
    if (data.fatal) {
      this.state = State.ERROR;
      return;
    }
    switch (data.details) {
      case ErrorDetails.FRAG_GAP:
      case ErrorDetails.FRAG_PARSING_ERROR:
      case ErrorDetails.FRAG_DECRYPT_ERROR:
      case ErrorDetails.FRAG_LOAD_ERROR:
      case ErrorDetails.FRAG_LOAD_TIMEOUT:
      case ErrorDetails.KEY_LOAD_ERROR:
      case ErrorDetails.KEY_LOAD_TIMEOUT:
        this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
        break;
      case ErrorDetails.LEVEL_LOAD_ERROR:
      case ErrorDetails.LEVEL_LOAD_TIMEOUT:
      case ErrorDetails.LEVEL_PARSING_ERROR:
        if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
          this.state = State.IDLE;
        }
        break;
      case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
      case ErrorDetails.BUFFER_APPEND_ERROR:
        if (data.parent !== "main") {
          return;
        }
        this.resetLoadingState();
        break;
      case ErrorDetails.BUFFER_FULL_ERROR:
        if (data.parent !== "main") {
          return;
        }
        if (this.reduceLengthAndFlushBuffer(data)) {
          this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
        }
        break;
      case ErrorDetails.INTERNAL_EXCEPTION:
        this.recoverWorkerError(data);
        break;
    }
  }
  onFragLoadEmergencyAborted() {
    this.state = State.IDLE;
    if (!this._hasEnoughToStart) {
      this.startFragRequested = false;
      this.nextLoadPosition = this.lastCurrentTime;
    }
    this.tickImmediate();
  }
  onBufferFlushed(event, {
    type: type2
  }) {
    if (type2 !== ElementaryStreamTypes.AUDIO || !this.altAudio) {
      const mediaBuffer = (type2 === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
      if (mediaBuffer) {
        this.afterBufferFlushed(mediaBuffer, type2, PlaylistLevelType.MAIN);
        this.tick();
      }
    }
  }
  onLevelsUpdated(event, data) {
    if (this.level > -1 && this.fragCurrent) {
      this.level = this.fragCurrent.level;
      if (this.level === -1) {
        this.resetWhenMissingContext(this.fragCurrent);
      }
    }
    this.levels = data.levels;
  }
  swapAudioCodec() {
    this.audioCodecSwap = !this.audioCodecSwap;
  }
  /**
   * Seeks to the set startPosition if not equal to the mediaElement's current time.
   */
  seekToStartPos() {
    const {
      media
    } = this;
    if (!media) {
      return;
    }
    const currentTime = media.currentTime;
    let startPosition = this.startPosition;
    if (startPosition >= 0 && currentTime < startPosition) {
      if (media.seeking) {
        this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
        return;
      }
      const timelineOffset = this.timelineOffset;
      if (timelineOffset && startPosition) {
        startPosition += timelineOffset;
      }
      const details = this.getLevelDetails();
      const buffered = BufferHelper.getBuffered(media);
      const bufferStart = buffered.length ? buffered.start(0) : 0;
      const delta = bufferStart - startPosition;
      const skipTolerance = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
      if (delta > 0 && (delta < skipTolerance || this.loadingParts && delta < 2 * ((details == null ? void 0 : details.partTarget) || 0))) {
        this.log(`adjusting start position by ${delta} to match buffer start`);
        startPosition += delta;
        this.startPosition = startPosition;
      }
      if (currentTime < startPosition) {
        this.log(`seek to target start position ${startPosition} from current time ${currentTime} buffer start ${bufferStart}`);
        media.currentTime = startPosition;
      }
    }
  }
  _getAudioCodec(currentLevel) {
    let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
    if (this.audioCodecSwap && audioCodec) {
      this.log("Swapping audio codec");
      if (audioCodec.indexOf("mp4a.40.5") !== -1) {
        audioCodec = "mp4a.40.2";
      } else {
        audioCodec = "mp4a.40.5";
      }
    }
    return audioCodec;
  }
  _loadBitrateTestFrag(fragment, level) {
    fragment.bitrateTest = true;
    this._doFragLoad(fragment, level).then((data) => {
      const {
        hls
      } = this;
      const frag = data == null ? void 0 : data.frag;
      if (!frag || this.fragContextChanged(frag)) {
        return;
      }
      level.fragmentError = 0;
      this.state = State.IDLE;
      this.startFragRequested = false;
      this.bitrateTest = false;
      const stats = frag.stats;
      stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
      hls.trigger(Events.FRAG_LOADED, data);
      frag.bitrateTest = false;
    });
  }
  _handleTransmuxComplete(transmuxResult) {
    var _id3$samples;
    const id = this.playlistType;
    const {
      hls
    } = this;
    const {
      remuxResult,
      chunkMeta
    } = transmuxResult;
    const context = this.getCurrentContext(chunkMeta);
    if (!context) {
      this.resetWhenMissingContext(chunkMeta);
      return;
    }
    const {
      frag,
      part,
      level
    } = context;
    const {
      video,
      text,
      id3,
      initSegment
    } = remuxResult;
    const {
      details
    } = level;
    const audio = this.altAudio ? void 0 : remuxResult.audio;
    if (this.fragContextChanged(frag)) {
      this.fragmentTracker.removeFragment(frag);
      return;
    }
    this.state = State.PARSING;
    if (initSegment) {
      if (initSegment != null && initSegment.tracks) {
        const mapFragment = frag.initSegment || frag;
        this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
        hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
          frag: mapFragment,
          id,
          tracks: initSegment.tracks
        });
      }
      const initPTS = initSegment.initPTS;
      const timescale2 = initSegment.timescale;
      if (isFiniteNumber(initPTS)) {
        this.initPTS[frag.cc] = {
          baseTime: initPTS,
          timescale: timescale2
        };
        hls.trigger(Events.INIT_PTS_FOUND, {
          frag,
          id,
          initPTS,
          timescale: timescale2
        });
      }
    }
    if (video && details) {
      if (!audio && video.type === "audiovideo") {
        this.logMuxedErr(frag);
      }
      const prevFrag = details.fragments[frag.sn - 1 - details.startSN];
      const isFirstFragment = frag.sn === details.startSN;
      const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
      if (remuxResult.independent !== false) {
        const {
          startPTS,
          endPTS,
          startDTS,
          endDTS
        } = video;
        if (part) {
          part.elementaryStreams[video.type] = {
            startPTS,
            endPTS,
            startDTS,
            endDTS
          };
        } else {
          if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
            this.couldBacktrack = true;
          }
          if (video.dropped && video.independent) {
            const bufferInfo = this.getMainFwdBufferInfo();
            const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
            const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
            if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
              this.backtrack(frag);
              return;
            } else if (isFirstInDiscontinuity) {
              frag.gap = true;
            }
            frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
          } else if (isFirstFragment && startPTS - (details.appliedTimelineOffset || 0) > MAX_START_GAP_JUMP) {
            frag.gap = true;
          }
        }
        frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
        if (this.backtrackFragment) {
          this.backtrackFragment = frag;
        }
        this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
      } else if (isFirstFragment || isFirstInDiscontinuity) {
        frag.gap = true;
      } else {
        this.backtrack(frag);
        return;
      }
    }
    if (audio) {
      const {
        startPTS,
        endPTS,
        startDTS,
        endDTS
      } = audio;
      if (part) {
        part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
          startPTS,
          endPTS,
          startDTS,
          endDTS
        };
      }
      frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
      this.bufferFragmentData(audio, frag, part, chunkMeta);
    }
    if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
      const emittedID3 = {
        id,
        frag,
        details,
        samples: id3.samples
      };
      hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
    }
    if (details && text) {
      const emittedText = {
        id,
        frag,
        details,
        samples: text.samples
      };
      hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
    }
  }
  logMuxedErr(frag) {
    this.warn(`${isMediaFragment(frag) ? "Media" : "Init"} segment with muxed audiovideo where only video expected: ${frag.url}`);
  }
  _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
    if (this.state !== State.PARSING) {
      return;
    }
    this.audioOnly = !!tracks.audio && !tracks.video;
    if (this.altAudio && !this.audioOnly) {
      delete tracks.audio;
      if (tracks.audiovideo) {
        this.logMuxedErr(frag);
      }
    }
    const {
      audio,
      video,
      audiovideo
    } = tracks;
    if (audio) {
      let audioCodec = pickMostCompleteCodecName(audio.codec, currentLevel.audioCodec);
      if (audioCodec === "mp4a") {
        audioCodec = "mp4a.40.5";
      }
      const ua = navigator.userAgent.toLowerCase();
      if (this.audioCodecSwitch) {
        if (audioCodec) {
          if (audioCodec.indexOf("mp4a.40.5") !== -1) {
            audioCodec = "mp4a.40.2";
          } else {
            audioCodec = "mp4a.40.5";
          }
        }
        const audioMetadata = audio.metadata;
        if (audioMetadata && "channelCount" in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf("firefox") === -1) {
          audioCodec = "mp4a.40.5";
        }
      }
      if (audioCodec && audioCodec.indexOf("mp4a.40.5") !== -1 && ua.indexOf("android") !== -1 && audio.container !== "audio/mpeg") {
        audioCodec = "mp4a.40.2";
        this.log(`Android: force audio codec to ${audioCodec}`);
      }
      if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
        this.log(`Swapping manifest audio codec "${currentLevel.audioCodec}" for "${audioCodec}"`);
      }
      audio.levelCodec = audioCodec;
      audio.id = PlaylistLevelType.MAIN;
      this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ""}/${currentLevel.audioCodec || ""}/${audio.codec}]`);
      delete tracks.audiovideo;
    }
    if (video) {
      video.levelCodec = currentLevel.videoCodec;
      video.id = PlaylistLevelType.MAIN;
      const parsedVideoCodec = video.codec;
      if ((parsedVideoCodec == null ? void 0 : parsedVideoCodec.length) === 4) {
        switch (parsedVideoCodec) {
          case "hvc1":
          case "hev1":
            video.codec = "hvc1.1.6.L120.90";
            break;
          case "av01":
            video.codec = "av01.0.04M.08";
            break;
          case "avc1":
            video.codec = "avc1.42e01e";
            break;
        }
      }
      this.log(`Init video buffer, container:${video.container}, codecs[level/parsed]=[${currentLevel.videoCodec || ""}/${parsedVideoCodec}]${video.codec !== parsedVideoCodec ? " parsed-corrected=" + video.codec : ""}${video.supplemental ? " supplemental=" + video.supplemental : ""}`);
      delete tracks.audiovideo;
    }
    if (audiovideo) {
      this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);
      delete tracks.video;
      delete tracks.audio;
    }
    const trackTypes = Object.keys(tracks);
    if (trackTypes.length) {
      this.hls.trigger(Events.BUFFER_CODECS, tracks);
      if (!this.hls) {
        return;
      }
      trackTypes.forEach((trackName) => {
        const track = tracks[trackName];
        const initSegment = track.initSegment;
        if (initSegment != null && initSegment.byteLength) {
          this.hls.trigger(Events.BUFFER_APPENDING, {
            type: trackName,
            data: initSegment,
            frag,
            part: null,
            chunkMeta,
            parent: frag.type
          });
        }
      });
    }
    this.tickImmediate();
  }
  getMainFwdBufferInfo() {
    const bufferOutput = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
    return this.getFwdBufferInfo(bufferOutput, PlaylistLevelType.MAIN);
  }
  get maxBufferLength() {
    const {
      levels,
      level
    } = this;
    const levelInfo = levels == null ? void 0 : levels[level];
    if (!levelInfo) {
      return this.config.maxBufferLength;
    }
    return this.getMaxBufferLength(levelInfo.maxBitrate);
  }
  backtrack(frag) {
    this.couldBacktrack = true;
    this.backtrackFragment = frag;
    this.resetTransmuxer();
    this.flushBufferGap(frag);
    this.fragmentTracker.removeFragment(frag);
    this.fragPrevious = null;
    this.nextLoadPosition = frag.start;
    this.state = State.IDLE;
  }
  checkFragmentChanged() {
    const video = this.media;
    let fragPlayingCurrent = null;
    if (video && video.readyState > 1 && video.seeking === false) {
      const currentTime = video.currentTime;
      if (BufferHelper.isBuffered(video, currentTime)) {
        fragPlayingCurrent = this.getAppendedFrag(currentTime);
      } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
        fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
      }
      if (fragPlayingCurrent) {
        this.backtrackFragment = null;
        const fragPlaying = this.fragPlaying;
        const fragCurrentLevel = fragPlayingCurrent.level;
        if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
          this.fragPlaying = fragPlayingCurrent;
          this.hls.trigger(Events.FRAG_CHANGED, {
            frag: fragPlayingCurrent
          });
          if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
            this.hls.trigger(Events.LEVEL_SWITCHED, {
              level: fragCurrentLevel
            });
          }
        }
      }
    }
  }
  get nextLevel() {
    const frag = this.nextBufferedFrag;
    if (frag) {
      return frag.level;
    }
    return -1;
  }
  get currentFrag() {
    var _this$media3;
    if (this.fragPlaying) {
      return this.fragPlaying;
    }
    const currentTime = ((_this$media3 = this.media) == null ? void 0 : _this$media3.currentTime) || this.lastCurrentTime;
    if (isFiniteNumber(currentTime)) {
      return this.getAppendedFrag(currentTime);
    }
    return null;
  }
  get currentProgramDateTime() {
    var _this$media4;
    const currentTime = ((_this$media4 = this.media) == null ? void 0 : _this$media4.currentTime) || this.lastCurrentTime;
    if (isFiniteNumber(currentTime)) {
      const details = this.getLevelDetails();
      const frag = this.currentFrag || (details ? findFragmentByPTS(null, details.fragments, currentTime) : null);
      if (frag) {
        const programDateTime = frag.programDateTime;
        if (programDateTime !== null) {
          const epocMs = programDateTime + (currentTime - frag.start) * 1e3;
          return new Date(epocMs);
        }
      }
    }
    return null;
  }
  get currentLevel() {
    const frag = this.currentFrag;
    if (frag) {
      return frag.level;
    }
    return -1;
  }
  get nextBufferedFrag() {
    const frag = this.currentFrag;
    if (frag) {
      return this.followingBufferedFrag(frag);
    }
    return null;
  }
  get forceStartLoad() {
    return this._forceStartLoad;
  }
};
var KeyLoader = class {
  constructor(config) {
    this.config = void 0;
    this.keyUriToKeyInfo = {};
    this.emeController = null;
    this.config = config;
  }
  abort(type2) {
    for (const uri in this.keyUriToKeyInfo) {
      const loader = this.keyUriToKeyInfo[uri].loader;
      if (loader) {
        var _loader$context;
        if (type2 && type2 !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
          return;
        }
        loader.abort();
      }
    }
  }
  detach() {
    for (const uri in this.keyUriToKeyInfo) {
      const keyInfo = this.keyUriToKeyInfo[uri];
      if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
        delete this.keyUriToKeyInfo[uri];
      }
    }
  }
  destroy() {
    this.detach();
    for (const uri in this.keyUriToKeyInfo) {
      const loader = this.keyUriToKeyInfo[uri].loader;
      if (loader) {
        loader.destroy();
      }
    }
    this.keyUriToKeyInfo = {};
  }
  createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) {
    return new LoadError({
      type: ErrorTypes.NETWORK_ERROR,
      details,
      fatal: false,
      frag,
      response,
      error,
      networkDetails
    });
  }
  loadClear(loadingFrag, encryptedFragments) {
    if (this.emeController && this.config.emeEnabled) {
      const {
        sn,
        cc
      } = loadingFrag;
      for (let i = 0; i < encryptedFragments.length; i++) {
        const frag = encryptedFragments[i];
        if (cc <= frag.cc && (sn === "initSegment" || frag.sn === "initSegment" || sn < frag.sn)) {
          this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
            frag.setKeyFormat(keySystemFormat);
          });
          break;
        }
      }
    }
  }
  load(frag) {
    if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) {
      return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
        return this.loadInternal(frag, keySystemFormat);
      });
    }
    return this.loadInternal(frag);
  }
  loadInternal(frag, keySystemFormat) {
    var _keyInfo, _keyInfo2;
    if (keySystemFormat) {
      frag.setKeyFormat(keySystemFormat);
    }
    const decryptdata = frag.decryptdata;
    if (!decryptdata) {
      const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : "Missing decryption data on fragment in onKeyLoading");
      return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
    }
    const uri = decryptdata.uri;
    if (!uri) {
      return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`)));
    }
    let keyInfo = this.keyUriToKeyInfo[uri];
    if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
      decryptdata.key = keyInfo.decryptdata.key;
      return Promise.resolve({
        frag,
        keyInfo
      });
    }
    if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
      var _keyInfo$mediaKeySess;
      switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
        case void 0:
        case "status-pending":
        case "usable":
        case "usable-in-future":
          return keyInfo.keyLoadPromise.then((keyLoadedData) => {
            decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
            return {
              frag,
              keyInfo
            };
          });
      }
    }
    keyInfo = this.keyUriToKeyInfo[uri] = {
      decryptdata,
      keyLoadPromise: null,
      loader: null,
      mediaKeySessionContext: null
    };
    switch (decryptdata.method) {
      case "ISO-23001-7":
      case "SAMPLE-AES":
      case "SAMPLE-AES-CENC":
      case "SAMPLE-AES-CTR":
        if (decryptdata.keyFormat === "identity") {
          return this.loadKeyHTTP(keyInfo, frag);
        }
        return this.loadKeyEME(keyInfo, frag);
      case "AES-128":
      case "AES-256":
      case "AES-256-CTR":
        return this.loadKeyHTTP(keyInfo, frag);
      default:
        return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`)));
    }
  }
  loadKeyEME(keyInfo, frag) {
    const keyLoadedData = {
      frag,
      keyInfo
    };
    if (this.emeController && this.config.emeEnabled) {
      const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
      if (keySessionContextPromise) {
        return (keyInfo.keyLoadPromise = keySessionContextPromise.then((keySessionContext) => {
          keyInfo.mediaKeySessionContext = keySessionContext;
          return keyLoadedData;
        })).catch((error) => {
          keyInfo.keyLoadPromise = null;
          throw error;
        });
      }
    }
    return Promise.resolve(keyLoadedData);
  }
  loadKeyHTTP(keyInfo, frag) {
    const config = this.config;
    const Loader = config.loader;
    const keyLoader = new Loader(config);
    frag.keyLoader = keyInfo.loader = keyLoader;
    return keyInfo.keyLoadPromise = new Promise((resolve, reject) => {
      const loaderContext = {
        keyInfo,
        frag,
        responseType: "arraybuffer",
        url: keyInfo.decryptdata.uri
      };
      const loadPolicy = config.keyLoadPolicy.default;
      const loaderConfig = {
        loadPolicy,
        timeout: loadPolicy.maxLoadTimeMs,
        maxRetry: 0,
        retryDelay: 0,
        maxRetryDelay: 0
      };
      const loaderCallbacks = {
        onSuccess: (response, stats, context, networkDetails) => {
          const {
            frag: frag2,
            keyInfo: keyInfo2,
            url: uri
          } = context;
          if (!frag2.decryptdata || keyInfo2 !== this.keyUriToKeyInfo[uri]) {
            return reject(this.createKeyLoadError(frag2, ErrorDetails.KEY_LOAD_ERROR, new Error("after key load, decryptdata unset or changed"), networkDetails));
          }
          keyInfo2.decryptdata.key = frag2.decryptdata.key = new Uint8Array(response.data);
          frag2.keyLoader = null;
          keyInfo2.loader = null;
          resolve({
            frag: frag2,
            keyInfo: keyInfo2
          });
        },
        onError: (response, context, networkDetails, stats) => {
          this.resetLoader(context);
          reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({
            url: loaderContext.url,
            data: void 0
          }, response)));
        },
        onTimeout: (stats, context, networkDetails) => {
          this.resetLoader(context);
          reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error("key loading timed out"), networkDetails));
        },
        onAbort: (stats, context, networkDetails) => {
          this.resetLoader(context);
          reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error("key loading aborted"), networkDetails));
        }
      };
      keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
    });
  }
  resetLoader(context) {
    const {
      frag,
      keyInfo,
      url: uri
    } = context;
    const loader = keyInfo.loader;
    if (frag.keyLoader === loader) {
      frag.keyLoader = null;
      keyInfo.loader = null;
    }
    delete this.keyUriToKeyInfo[uri];
    if (loader) {
      loader.destroy();
    }
  }
};
function mapContextToLevelType(context) {
  const {
    type: type2
  } = context;
  switch (type2) {
    case PlaylistContextType.AUDIO_TRACK:
      return PlaylistLevelType.AUDIO;
    case PlaylistContextType.SUBTITLE_TRACK:
      return PlaylistLevelType.SUBTITLE;
    default:
      return PlaylistLevelType.MAIN;
  }
}
function getResponseUrl(response, context) {
  let url = response.url;
  if (url === void 0 || url.indexOf("data:") === 0) {
    url = context.url;
  }
  return url;
}
var PlaylistLoader = class {
  constructor(hls) {
    this.hls = void 0;
    this.loaders = /* @__PURE__ */ Object.create(null);
    this.variableList = null;
    this.onManifestLoaded = this.checkAutostartLoad;
    this.hls = hls;
    this.registerListeners();
  }
  startLoad(startPosition) {
  }
  stopLoad() {
    this.destroyInternalLoaders();
  }
  registerListeners() {
    const {
      hls
    } = this;
    hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
    hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
    hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
    hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  }
  unregisterListeners() {
    const {
      hls
    } = this;
    hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
    hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
    hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
    hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
    hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  }
  /**
   * Returns defaults or configured loader-type overloads (pLoader and loader config params)
   */
  createInternalLoader(context) {
    const config = this.hls.config;
    const PLoader = config.pLoader;
    const Loader = config.loader;
    const InternalLoader = PLoader || Loader;
    const loader = new InternalLoader(config);
    this.loaders[context.type] = loader;
    return loader;
  }
  getInternalLoader(context) {
    return this.loaders[context.type];
  }
  resetInternalLoader(contextType) {
    if (this.loaders[contextType]) {
      delete this.loaders[contextType];
    }
  }
  /**
   * Call `destroy` on all internal loader instances mapped (one per context type)
   */
  destroyInternalLoaders() {
    for (const contextType in this.loaders) {
      const loader = this.loaders[contextType];
      if (loader) {
        loader.destroy();
      }
      this.resetInternalLoader(contextType);
    }
  }
  destroy() {
    this.variableList = null;
    this.unregisterListeners();
    this.destroyInternalLoaders();
  }
  onManifestLoading(event, data) {
    const {
      url
    } = data;
    this.variableList = null;
    this.load({
      id: null,
      level: 0,
      responseType: "text",
      type: PlaylistContextType.MANIFEST,
      url,
      deliveryDirectives: null,
      levelOrTrack: null
    });
  }
  onLevelLoading(event, data) {
    const {
      id,
      level,
      pathwayId,
      url,
      deliveryDirectives,
      levelInfo
    } = data;
    this.load({
      id,
      level,
      pathwayId,
      responseType: "text",
      type: PlaylistContextType.LEVEL,
      url,
      deliveryDirectives,
      levelOrTrack: levelInfo
    });
  }
  onAudioTrackLoading(event, data) {
    const {
      id,
      groupId,
      url,
      deliveryDirectives,
      track
    } = data;
    this.load({
      id,
      groupId,
      level: null,
      responseType: "text",
      type: PlaylistContextType.AUDIO_TRACK,
      url,
      deliveryDirectives,
      levelOrTrack: track
    });
  }
  onSubtitleTrackLoading(event, data) {
    const {
      id,
      groupId,
      url,
      deliveryDirectives,
      track
    } = data;
    this.load({
      id,
      groupId,
      level: null,
      responseType: "text",
      type: PlaylistContextType.SUBTITLE_TRACK,
      url,
      deliveryDirectives,
      levelOrTrack: track
    });
  }
  onLevelsUpdated(event, data) {
    const loader = this.loaders[PlaylistContextType.LEVEL];
    if (loader) {
      const context = loader.context;
      if (context && !data.levels.some((lvl) => lvl === context.levelOrTrack)) {
        loader.abort();
        delete this.loaders[PlaylistContextType.LEVEL];
      }
    }
  }
  load(context) {
    var _context$deliveryDire;
    const config = this.hls.config;
    let loader = this.getInternalLoader(context);
    if (loader) {
      const logger4 = this.hls.logger;
      const loaderContext = loader.context;
      if (loaderContext && loaderContext.levelOrTrack === context.levelOrTrack && (loaderContext.url === context.url || loaderContext.deliveryDirectives && !context.deliveryDirectives)) {
        if (loaderContext.url === context.url) {
          logger4.log(`[playlist-loader]: ignore ${context.url} ongoing request`);
        } else {
          logger4.log(`[playlist-loader]: ignore ${context.url} in favor of ${loaderContext.url}`);
        }
        return;
      }
      logger4.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);
      loader.abort();
    }
    let loadPolicy;
    if (context.type === PlaylistContextType.MANIFEST) {
      loadPolicy = config.manifestLoadPolicy.default;
    } else {
      loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
        timeoutRetry: null,
        errorRetry: null
      });
    }
    loader = this.createInternalLoader(context);
    if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
      let levelDetails;
      if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
        levelDetails = this.hls.levels[context.level].details;
      } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
        levelDetails = this.hls.audioTracks[context.id].details;
      } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
        levelDetails = this.hls.subtitleTracks[context.id].details;
      }
      if (levelDetails) {
        const partTarget = levelDetails.partTarget;
        const targetDuration = levelDetails.targetduration;
        if (partTarget && targetDuration) {
          const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1e3;
          loadPolicy = _extends({}, loadPolicy, {
            maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
            maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
          });
        }
      }
    }
    const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
    const loaderConfig = {
      loadPolicy,
      timeout: loadPolicy.maxLoadTimeMs,
      maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
      retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
      maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
    };
    const loaderCallbacks = {
      onSuccess: (response, stats, context2, networkDetails) => {
        const loader2 = this.getInternalLoader(context2);
        this.resetInternalLoader(context2.type);
        const string = response.data;
        if (string.indexOf("#EXTM3U") !== 0) {
          this.handleManifestParsingError(response, context2, new Error("no EXTM3U delimiter"), networkDetails || null, stats);
          return;
        }
        stats.parsing.start = performance.now();
        if (M3U8Parser.isMediaPlaylist(string) || context2.type !== PlaylistContextType.MANIFEST) {
          this.handleTrackOrLevelPlaylist(response, stats, context2, networkDetails || null, loader2);
        } else {
          this.handleMasterPlaylist(response, stats, context2, networkDetails);
        }
      },
      onError: (response, context2, networkDetails, stats) => {
        this.handleNetworkError(context2, networkDetails, false, response, stats);
      },
      onTimeout: (stats, context2, networkDetails) => {
        this.handleNetworkError(context2, networkDetails, true, void 0, stats);
      }
    };
    loader.load(context, loaderConfig, loaderCallbacks);
  }
  checkAutostartLoad() {
    if (!this.hls) {
      return;
    }
    const {
      config: {
        autoStartLoad,
        startPosition
      },
      forceStartLoad
    } = this.hls;
    if (autoStartLoad || forceStartLoad) {
      this.hls.logger.log(`${autoStartLoad ? "auto" : "force"} startLoad with configured startPosition ${startPosition}`);
      this.hls.startLoad(startPosition);
    }
  }
  handleMasterPlaylist(response, stats, context, networkDetails) {
    const hls = this.hls;
    const string = response.data;
    const url = getResponseUrl(response, context);
    const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
    if (parsedResult.playlistParsingError) {
      this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
      return;
    }
    const {
      contentSteering,
      levels,
      sessionData,
      sessionKeys,
      startTimeOffset,
      variableList
    } = parsedResult;
    this.variableList = variableList;
    const {
      AUDIO: audioTracks = [],
      SUBTITLES: subtitles,
      "CLOSED-CAPTIONS": captions
    } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);
    if (audioTracks.length) {
      const embeddedAudioFound = audioTracks.some((audioTrack) => !audioTrack.url);
      if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
        this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one");
        audioTracks.unshift({
          type: "main",
          name: "main",
          groupId: "main",
          default: false,
          autoselect: false,
          forced: false,
          id: -1,
          attrs: new AttrList({}),
          bitrate: 0,
          url: ""
        });
      }
    }
    hls.trigger(Events.MANIFEST_LOADED, {
      levels,
      audioTracks,
      subtitles,
      captions,
      contentSteering,
      url,
      stats,
      networkDetails,
      sessionData,
      sessionKeys,
      startTimeOffset,
      variableList
    });
  }
  handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
    const hls = this.hls;
    const {
      id,
      level,
      type: type2
    } = context;
    const url = getResponseUrl(response, context);
    const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
    const levelType = mapContextToLevelType(context);
    const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, 0, this.variableList);
    if (type2 === PlaylistContextType.MANIFEST) {
      const singleLevel = {
        attrs: new AttrList({}),
        bitrate: 0,
        details: levelDetails,
        name: "",
        url
      };
      levelDetails.requestScheduled = stats.loading.start + computeReloadInterval(levelDetails, 0);
      hls.trigger(Events.MANIFEST_LOADED, {
        levels: [singleLevel],
        audioTracks: [],
        url,
        stats,
        networkDetails,
        sessionData: null,
        sessionKeys: null,
        contentSteering: null,
        startTimeOffset: null,
        variableList: null
      });
    }
    stats.parsing.end = performance.now();
    context.levelDetails = levelDetails;
    this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  }
  handleManifestParsingError(response, context, error, networkDetails, stats) {
    this.hls.trigger(Events.ERROR, {
      type: ErrorTypes.NETWORK_ERROR,
      details: ErrorDetails.MANIFEST_PARSING_ERROR,
      fatal: context.type === PlaylistContextType.MANIFEST,
      url: response.url,
      err: error,
      error,
      reason: error.message,
      response,
      context,
      networkDetails,
      stats
    });
  }
  handleNetworkError(context, networkDetails, timeout = false, response, stats) {
    let message = `A network ${timeout ? "timeout" : "error" + (response ? " (status " + response.code + ")" : "")} occurred while loading ${context.type}`;
    if (context.type === PlaylistContextType.LEVEL) {
      message += `: ${context.level} id: ${context.id}`;
    } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
      message += ` id: ${context.id} group-id: "${context.groupId}"`;
    }
    const error = new Error(message);
    this.hls.logger.warn(`[playlist-loader]: ${message}`);
    let details = ErrorDetails.UNKNOWN;
    let fatal = false;
    const loader = this.getInternalLoader(context);
    switch (context.type) {
      case PlaylistContextType.MANIFEST:
        details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
        fatal = true;
        break;
      case PlaylistContextType.LEVEL:
        details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
        fatal = false;
        break;
      case PlaylistContextType.AUDIO_TRACK:
        details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
        fatal = false;
        break;
      case PlaylistContextType.SUBTITLE_TRACK:
        details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
        fatal = false;
        break;
    }
    if (loader) {
      this.resetInternalLoader(context.type);
    }
    const errorData = {
      type: ErrorTypes.NETWORK_ERROR,
      details,
      fatal,
      url: context.url,
      loader,
      context,
      error,
      networkDetails,
      stats
    };
    if (response) {
      const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
      errorData.response = _objectSpread2({
        url,
        data: void 0
      }, response);
    }
    this.hls.trigger(Events.ERROR, errorData);
  }
  handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
    const hls = this.hls;
    const {
      type: type2,
      level,
      id,
      groupId,
      deliveryDirectives
    } = context;
    const url = getResponseUrl(response, context);
    const parent = mapContextToLevelType(context);
    const levelIndex = typeof context.level === "number" && parent === PlaylistLevelType.MAIN ? level : void 0;
    if (!levelDetails.fragments.length) {
      const _error = levelDetails.playlistParsingError = new Error("No Segments found in Playlist");
      hls.trigger(Events.ERROR, {
        type: ErrorTypes.NETWORK_ERROR,
        details: ErrorDetails.LEVEL_EMPTY_ERROR,
        fatal: false,
        url,
        error: _error,
        reason: _error.message,
        response,
        context,
        level: levelIndex,
        parent,
        networkDetails,
        stats
      });
      return;
    }
    if (!levelDetails.targetduration) {
      levelDetails.playlistParsingError = new Error("Missing Target Duration");
    }
    const error = levelDetails.playlistParsingError;
    if (error) {
      this.hls.logger.warn(error);
      if (!hls.config.ignorePlaylistParsingErrors) {
        hls.trigger(Events.ERROR, {
          type: ErrorTypes.NETWORK_ERROR,
          details: ErrorDetails.LEVEL_PARSING_ERROR,
          fatal: false,
          url,
          error,
          reason: error.message,
          response,
          context,
          level: levelIndex,
          parent,
          networkDetails,
          stats
        });
        return;
      }
      levelDetails.playlistParsingError = null;
    }
    if (levelDetails.live && loader) {
      if (loader.getCacheAge) {
        levelDetails.ageHeader = loader.getCacheAge() || 0;
      }
      if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
        levelDetails.ageHeader = 0;
      }
    }
    switch (type2) {
      case PlaylistContextType.MANIFEST:
      case PlaylistContextType.LEVEL:
        hls.trigger(Events.LEVEL_LOADED, {
          details: levelDetails,
          levelInfo: context.levelOrTrack || hls.levels[0],
          level: levelIndex || 0,
          id: id || 0,
          stats,
          networkDetails,
          deliveryDirectives,
          withoutMultiVariant: type2 === PlaylistContextType.MANIFEST
        });
        break;
      case PlaylistContextType.AUDIO_TRACK:
        hls.trigger(Events.AUDIO_TRACK_LOADED, {
          details: levelDetails,
          track: context.levelOrTrack,
          id: id || 0,
          groupId: groupId || "",
          stats,
          networkDetails,
          deliveryDirectives
        });
        break;
      case PlaylistContextType.SUBTITLE_TRACK:
        hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
          details: levelDetails,
          track: context.levelOrTrack,
          id: id || 0,
          groupId: groupId || "",
          stats,
          networkDetails,
          deliveryDirectives
        });
        break;
    }
  }
};
var Hls = class _Hls {
  /**
   * Get the video-dev/hls.js package version.
   */
  static get version() {
    return version;
  }
  /**
   * Check if the required MediaSource Extensions are available.
   */
  static isMSESupported() {
    return isMSESupported();
  }
  /**
   * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
   */
  static isSupported() {
    return isSupported();
  }
  /**
   * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
   */
  static getMediaSource() {
    return getMediaSource();
  }
  static get Events() {
    return Events;
  }
  static get MetadataSchema() {
    return MetadataSchema;
  }
  static get ErrorTypes() {
    return ErrorTypes;
  }
  static get ErrorDetails() {
    return ErrorDetails;
  }
  /**
   * Get the default configuration applied to new instances.
   */
  static get DefaultConfig() {
    if (!_Hls.defaultConfig) {
      return hlsDefaultConfig;
    }
    return _Hls.defaultConfig;
  }
  /**
   * Replace the default configuration applied to new instances.
   */
  static set DefaultConfig(defaultConfig) {
    _Hls.defaultConfig = defaultConfig;
  }
  /**
   * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
   * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
   */
  constructor(userConfig = {}) {
    this.config = void 0;
    this.userConfig = void 0;
    this.logger = void 0;
    this.coreComponents = void 0;
    this.networkControllers = void 0;
    this._emitter = new EventEmitter();
    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 = false;
    const logger4 = this.logger = enableLogs(userConfig.debug || false, "Hls instance", userConfig.assetPlayerId);
    const config = this.config = mergeConfig(_Hls.DefaultConfig, userConfig, logger4);
    this.userConfig = userConfig;
    if (config.progressive) {
      enableStreamingMode(config, logger4);
    }
    const {
      abrController: _AbrController,
      bufferController: _BufferController,
      capLevelController: _CapLevelController,
      errorController: _ErrorController,
      fpsController: _FpsController
    } = config;
    const errorController = new _ErrorController(this);
    const abrController = this.abrController = new _AbrController(this);
    const fragmentTracker = new FragmentTracker(this);
    const _InterstitialsController = config.interstitialsController;
    const interstitialsController = _InterstitialsController ? this.interstitialsController = new _InterstitialsController(this, _Hls) : null;
    const bufferController = this.bufferController = new _BufferController(this, fragmentTracker);
    const capLevelController = this.capLevelController = new _CapLevelController(this);
    const fpsController = new _FpsController(this);
    const playListLoader = new PlaylistLoader(this);
    const _ContentSteeringController = config.contentSteeringController;
    const contentSteering = _ContentSteeringController ? new _ContentSteeringController(this) : null;
    const levelController = this.levelController = new LevelController(this, contentSteering);
    const id3TrackController = new ID3TrackController(this);
    const keyLoader = new KeyLoader(this.config);
    const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
    const gapController = this.gapController = new GapController(this, fragmentTracker);
    capLevelController.setStreamController(streamController);
    fpsController.setStreamController(streamController);
    const networkControllers = [playListLoader, levelController, streamController];
    if (interstitialsController) {
      networkControllers.splice(1, 0, interstitialsController);
    }
    if (contentSteering) {
      networkControllers.splice(1, 0, contentSteering);
    }
    this.networkControllers = networkControllers;
    const coreComponents = [abrController, bufferController, gapController, capLevelController, fpsController, id3TrackController, fragmentTracker];
    this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
    const AudioStreamControllerClass = config.audioStreamController;
    if (AudioStreamControllerClass) {
      networkControllers.push(this.audioStreamController = new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
    }
    this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
    const SubtitleStreamControllerClass = config.subtitleStreamController;
    if (SubtitleStreamControllerClass) {
      networkControllers.push(this.subtititleStreamController = new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
    }
    this.createController(config.timelineController, coreComponents);
    keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
    this.cmcdController = this.createController(config.cmcdController, coreComponents);
    this.latencyController = this.createController(LatencyController, coreComponents);
    this.coreComponents = coreComponents;
    networkControllers.push(errorController);
    const onErrorOut = errorController.onErrorOut;
    if (typeof onErrorOut === "function") {
      this.on(Events.ERROR, onErrorOut, errorController);
    }
    this.on(Events.MANIFEST_LOADED, playListLoader.onManifestLoaded, playListLoader);
  }
  createController(ControllerClass, components) {
    if (ControllerClass) {
      const controllerInstance = new ControllerClass(this);
      if (components) {
        components.push(controllerInstance);
      }
      return controllerInstance;
    }
    return null;
  }
  // Delegate the EventEmitter through the public API of Hls.js
  on(event, listener, context = this) {
    this._emitter.on(event, listener, context);
  }
  once(event, listener, context = this) {
    this._emitter.once(event, listener, context);
  }
  removeAllListeners(event) {
    this._emitter.removeAllListeners(event);
  }
  off(event, listener, context = this, once) {
    this._emitter.off(event, listener, context, once);
  }
  listeners(event) {
    return this._emitter.listeners(event);
  }
  emit(event, name, eventObject) {
    return this._emitter.emit(event, name, eventObject);
  }
  trigger(event, eventObject) {
    if (this.config.debug) {
      return this.emit(event, event, eventObject);
    } else {
      try {
        return this.emit(event, event, eventObject);
      } catch (error) {
        this.logger.error("An internal error happened while handling event " + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
        if (!this.triggeringException) {
          this.triggeringException = true;
          const fatal = event === Events.ERROR;
          this.trigger(Events.ERROR, {
            type: ErrorTypes.OTHER_ERROR,
            details: ErrorDetails.INTERNAL_EXCEPTION,
            fatal,
            event,
            error
          });
          this.triggeringException = false;
        }
      }
    }
    return false;
  }
  listenerCount(event) {
    return this._emitter.listenerCount(event);
  }
  /**
   * Dispose of the instance
   */
  destroy() {
    this.logger.log("destroy");
    this.trigger(Events.DESTROYING, void 0);
    this.detachMedia();
    this.removeAllListeners();
    this._autoLevelCapping = -1;
    this._url = null;
    this.networkControllers.forEach((component) => component.destroy());
    this.networkControllers.length = 0;
    this.coreComponents.forEach((component) => component.destroy());
    this.coreComponents.length = 0;
    const config = this.config;
    config.xhrSetup = config.fetchSetup = void 0;
    this.userConfig = null;
  }
  /**
   * Attaches Hls.js to a media element
   */
  attachMedia(data) {
    if (!data || "media" in data && !data.media) {
      const error = new Error(`attachMedia failed: invalid argument (${data})`);
      this.trigger(Events.ERROR, {
        type: ErrorTypes.OTHER_ERROR,
        details: ErrorDetails.ATTACH_MEDIA_ERROR,
        fatal: true,
        error
      });
      return;
    }
    this.logger.log(`attachMedia`);
    if (this._media) {
      this.logger.warn(`media must be detached before attaching`);
      this.detachMedia();
    }
    const attachMediaSource = "media" in data;
    const media = attachMediaSource ? data.media : data;
    const attachingData = attachMediaSource ? data : {
      media
    };
    this._media = media;
    this.trigger(Events.MEDIA_ATTACHING, attachingData);
  }
  /**
   * Detach Hls.js from the media
   */
  detachMedia() {
    this.logger.log("detachMedia");
    this.trigger(Events.MEDIA_DETACHING, {});
    this._media = null;
  }
  /**
   * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance
   */
  transferMedia() {
    this._media = null;
    const transferMedia = this.bufferController.transferMedia();
    this.trigger(Events.MEDIA_DETACHING, {
      transferMedia
    });
    return transferMedia;
  }
  /**
   * Set the source URL. Can be relative or absolute.
   */
  loadSource(url) {
    this.stopLoad();
    const media = this.media;
    const loadedSource = this._url;
    const loadingSource = this._url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
      alwaysNormalize: true
    });
    this._autoLevelCapping = -1;
    this._maxHdcpLevel = null;
    this.logger.log(`loadSource:${loadingSource}`);
    if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
      this.detachMedia();
      this.attachMedia(media);
    }
    this.trigger(Events.MANIFEST_LOADING, {
      url
    });
  }
  /**
   * 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(startPosition = -1, skipSeekToStartPosition) {
    this.logger.log(`startLoad(${startPosition + (skipSeekToStartPosition ? ", <skip seek to start>" : "")})`);
    this.started = true;
    this.resumeBuffering();
    for (let i = 0; i < this.networkControllers.length; i++) {
      this.networkControllers[i].startLoad(startPosition, skipSeekToStartPosition);
      if (!this.started || !this.networkControllers) {
        break;
      }
    }
  }
  /**
   * Stop loading of any stream data.
   */
  stopLoad() {
    this.logger.log("stopLoad");
    this.started = false;
    for (let i = 0; i < this.networkControllers.length; i++) {
      this.networkControllers[i].stopLoad();
      if (this.started || !this.networkControllers) {
        break;
      }
    }
  }
  /**
   * 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() {
    if (!this.bufferingEnabled) {
      this.logger.log(`resume buffering`);
      this.networkControllers.forEach((controller) => {
        if (controller.resumeBuffering) {
          controller.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() {
    if (this.bufferingEnabled) {
      this.logger.log(`pause buffering`);
      this.networkControllers.forEach((controller) => {
        if (controller.pauseBuffering) {
          controller.pauseBuffering();
        }
      });
    }
  }
  get inFlightFragments() {
    const inFlightData = {
      [PlaylistLevelType.MAIN]: this.streamController.inFlightFrag
    };
    if (this.audioStreamController) {
      inFlightData[PlaylistLevelType.AUDIO] = this.audioStreamController.inFlightFrag;
    }
    if (this.subtititleStreamController) {
      inFlightData[PlaylistLevelType.SUBTITLE] = this.subtititleStreamController.inFlightFrag;
    }
    return inFlightData;
  }
  /**
   * 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 media = this._media;
    const time = media == null ? void 0 : media.currentTime;
    this.detachMedia();
    if (media) {
      this.attachMedia(media);
      if (time) {
        this.startLoad(time);
      }
    }
  }
  removeLevel(levelIndex) {
    this.levelController.removeLevel(levelIndex);
  }
  /**
   * @returns a UUID for this player instance
   */
  get sessionId() {
    let _sessionId = this._sessionId;
    if (!_sessionId) {
      _sessionId = this._sessionId = uuid();
    }
    return _sessionId;
  }
  /**
   * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
   */
  get levels() {
    const levels = this.levelController.levels;
    return levels ? levels : [];
  }
  /**
   * @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(newLevel) {
    this.logger.log(`set currentLevel:${newLevel}`);
    this.levelController.manualLevel = newLevel;
    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(newLevel) {
    this.logger.log(`set nextLevel:${newLevel}`);
    this.levelController.manualLevel = newLevel;
    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(newLevel) {
    this.logger.log(`set loadLevel:${newLevel}`);
    this.levelController.manualLevel = newLevel;
  }
  /**
   * 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(level) {
    this.levelController.nextLoadLevel = level;
  }
  /**
   * 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(newLevel) {
    this.logger.log(`set firstLevel:${newLevel}`);
    this.levelController.firstLevel = newLevel;
  }
  /**
   * 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 startLevel = this.levelController.startLevel;
    if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
      return this.abrController.forcedAutoLevel;
    }
    return startLevel;
  }
  /**
   * 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(newLevel) {
    this.logger.log(`set startLevel:${newLevel}`);
    if (newLevel !== -1) {
      newLevel = Math.max(newLevel, this.minAutoLevel);
    }
    this.levelController.startLevel = newLevel;
  }
  /**
   * 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(shouldStartCapping) {
    const newCapLevelToPlayerSize = !!shouldStartCapping;
    if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
      if (newCapLevelToPlayerSize) {
        this.capLevelController.startCapping();
      } else {
        this.capLevelController.stopCapping();
        this.autoLevelCapping = -1;
        this.streamController.nextLevelSwitch();
      }
      this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
    }
  }
  /**
   * 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
    } = this.abrController;
    if (!bwEstimator) {
      return NaN;
    }
    return bwEstimator.getEstimate();
  }
  set bandwidthEstimate(abrEwmaDefaultEstimate) {
    this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  }
  get abrEwmaDefaultEstimate() {
    const {
      bwEstimator
    } = this.abrController;
    if (!bwEstimator) {
      return NaN;
    }
    return bwEstimator.defaultEstimate;
  }
  /**
   * get time to first byte estimate
   * @type {number}
   */
  get ttfbEstimate() {
    const {
      bwEstimator
    } = this.abrController;
    if (!bwEstimator) {
      return NaN;
    }
    return bwEstimator.getEstimateTTFB();
  }
  /**
   * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
   */
  set autoLevelCapping(newLevel) {
    if (this._autoLevelCapping !== newLevel) {
      this.logger.log(`set autoLevelCapping:${newLevel}`);
      this._autoLevelCapping = newLevel;
      this.levelController.checkMaxAutoUpdated();
    }
  }
  get maxHdcpLevel() {
    return this._maxHdcpLevel;
  }
  set maxHdcpLevel(value) {
    if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
      this._maxHdcpLevel = value;
      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,
      config: {
        minAutoBitrate
      }
    } = this;
    if (!levels) return 0;
    const len = levels.length;
    for (let i = 0; i < len; i++) {
      if (levels[i].maxBitrate >= minAutoBitrate) {
        return i;
      }
    }
    return 0;
  }
  /**
   * max level selectable in auto mode according to autoLevelCapping
   */
  get maxAutoLevel() {
    const {
      levels,
      autoLevelCapping,
      maxHdcpLevel
    } = this;
    let maxAutoLevel;
    if (autoLevelCapping === -1 && levels != null && levels.length) {
      maxAutoLevel = levels.length - 1;
    } else {
      maxAutoLevel = autoLevelCapping;
    }
    if (maxHdcpLevel) {
      for (let i = maxAutoLevel; i--; ) {
        const hdcpLevel = levels[i].attrs["HDCP-LEVEL"];
        if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
          return i;
        }
      }
    }
    return maxAutoLevel;
  }
  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(nextLevel) {
    this.abrController.nextAutoLevel = nextLevel;
  }
  /**
   * 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(audioOption) {
    var _this$audioTrackContr;
    return ((_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption)) || 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(subtitleOption) {
    var _this$subtitleTrackCo;
    return ((_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption)) || null;
  }
  /**
   * Get the complete list of audio tracks across all media groups
   */
  get allAudioTracks() {
    const audioTrackController = this.audioTrackController;
    return audioTrackController ? audioTrackController.allAudioTracks : [];
  }
  /**
   * Get the list of selectable audio tracks
   */
  get audioTracks() {
    const audioTrackController = this.audioTrackController;
    return audioTrackController ? audioTrackController.audioTracks : [];
  }
  /**
   * index of the selected audio track (index in audio track lists)
   */
  get audioTrack() {
    const audioTrackController = this.audioTrackController;
    return audioTrackController ? audioTrackController.audioTrack : -1;
  }
  /**
   * selects an audio track, based on its index in audio track lists
   */
  set audioTrack(audioTrackId) {
    const audioTrackController = this.audioTrackController;
    if (audioTrackController) {
      audioTrackController.audioTrack = audioTrackId;
    }
  }
  /**
   * get the complete list of subtitle tracks across all media groups
   */
  get allSubtitleTracks() {
    const subtitleTrackController = this.subtitleTrackController;
    return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  }
  /**
   * get alternate subtitle tracks list from playlist
   */
  get subtitleTracks() {
    const subtitleTrackController = this.subtitleTrackController;
    return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  }
  /**
   * index of the selected subtitle track (index in subtitle track lists)
   */
  get subtitleTrack() {
    const subtitleTrackController = this.subtitleTrackController;
    return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  }
  get media() {
    return this._media;
  }
  /**
   * select an subtitle track, based on its index in subtitle track lists
   */
  set subtitleTrack(subtitleTrackId) {
    const subtitleTrackController = this.subtitleTrackController;
    if (subtitleTrackController) {
      subtitleTrackController.subtitleTrack = subtitleTrackId;
    }
  }
  /**
   * Whether subtitle display is enabled or not
   */
  get subtitleDisplay() {
    const subtitleTrackController = this.subtitleTrackController;
    return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  }
  /**
   * Enable/disable subtitle display rendering
   */
  set subtitleDisplay(value) {
    const subtitleTrackController = this.subtitleTrackController;
    if (subtitleTrackController) {
      subtitleTrackController.subtitleDisplay = value;
    }
  }
  /**
   * 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(mode) {
    this.config.lowLatencyMode = mode;
  }
  /**
   * 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(latency) {
    this.latencyController.targetLatency = latency;
  }
  /**
   * 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(pathwayPriority) {
    this.levelController.pathwayPriority = pathwayPriority;
  }
  /**
   * returns true when all SourceBuffers are buffered to the end
   */
  get bufferedToEnd() {
    var _this$bufferControlle;
    return !!((_this$bufferControlle = this.bufferController) != null && _this$bufferControlle.bufferedToEnd);
  }
  /**
   * returns Interstitials Program Manager
   */
  get interstitialsManager() {
    var _this$interstitialsCo;
    return ((_this$interstitialsCo = this.interstitialsController) == null ? void 0 : _this$interstitialsCo.interstitialsManager) || null;
  }
  /**
   * returns mediaCapabilities.decodingInfo for a variant/rendition
   */
  getMediaDecodingInfo(level, audioTracks = this.allAudioTracks) {
    const audioTracksByGroup = getAudioTracksByGroup(audioTracks);
    return getMediaDecodingInfoPromise(level, audioTracksByGroup, navigator.mediaCapabilities);
  }
};
Hls.defaultConfig = void 0;

// src/app/player/components/art-player/art-player.component.ts
var ArtPlayerComponent = class _ArtPlayerComponent {
  constructor(elementRef) {
    this.elementRef = elementRef;
    this.volume = 1;
    this.showCaptions = false;
  }
  ngOnInit() {
    this.initPlayer();
  }
  ngOnDestroy() {
    if (this.player) {
      this.player.destroy();
    }
  }
  ngOnChanges(changes) {
    if (changes["channel"] && !changes["channel"].firstChange) {
      if (this.player) {
        this.player.destroy();
      }
      this.initPlayer();
    }
  }
  initPlayer() {
    const el = this.elementRef.nativeElement.querySelector(".artplayer-container");
    const isLive = this.channel.url.toLowerCase().includes("m3u8");
    this.player = new import_artplayer.default({
      container: el,
      url: this.channel.url + (this.channel.epgParams || ""),
      volume: this.volume,
      isLive,
      autoplay: true,
      type: this.getVideoType(this.channel.url),
      pip: true,
      autoSize: true,
      autoMini: true,
      screenshot: true,
      setting: true,
      playbackRate: true,
      aspectRatio: true,
      fullscreen: true,
      fullscreenWeb: true,
      customType: {
        m3u8: function(video, url) {
          if (Hls.isSupported()) {
            const hls = new Hls();
            hls.loadSource(url);
            hls.attachMedia(video);
          } else if (video.canPlayType("application/vnd.apple.mpegurl")) {
            video.src = url;
          }
        },
        mkv: function(video, url) {
          video.src = url;
          video.onerror = () => {
            console.error("Error loading MKV file:", video.error);
            video.src = url;
          };
        }
      }
    });
  }
  getVideoType(url) {
    const extension = url.split(".").pop()?.toLowerCase();
    switch (extension) {
      case "mkv":
        return "video/matroska";
      // Changed from 'mkv'
      case "m3u8":
        return "m3u8";
      case "mp4":
        return "mp4";
      default:
        return "auto";
    }
  }
  static {
    this.\u0275fac = function ArtPlayerComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || _ArtPlayerComponent)(\u0275\u0275directiveInject(ElementRef));
    };
  }
  static {
    this.\u0275cmp = /* @__PURE__ */ \u0275\u0275defineComponent({ type: _ArtPlayerComponent, selectors: [["app-art-player"]], inputs: { channel: "channel", volume: "volume", showCaptions: "showCaptions" }, features: [\u0275\u0275NgOnChangesFeature], decls: 2, vars: 0, consts: [["artplayer", ""], [1, "artplayer-container"]], template: function ArtPlayerComponent_Template(rf, ctx) {
      if (rf & 1) {
        \u0275\u0275element(0, "div", 1, 0);
      }
    }, dependencies: [CommonModule], styles: ["\n\n[_nghost-%COMP%] {\n  display: block;\n  width: 100%;\n  height: 100%;\n}\n.artplayer-container[_ngcontent-%COMP%] {\n  width: 100%;\n  height: 100%;\n}"] });
  }
};
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ArtPlayerComponent, [{
    type: Component,
    args: [{ selector: "app-art-player", imports: [CommonModule], template: `<div #artplayer class="artplayer-container"></div>`, styles: ["/* angular:styles/component:css;cd5c4322bd319fd57b1e967c7b9d32dbb054e43d64d8cf543916434a7dcdeaae;/Users/allen/dev/browser-extentions/dailyflim/src/app/player/components/art-player/art-player.component.ts */\n:host {\n  display: block;\n  width: 100%;\n  height: 100%;\n}\n.artplayer-container {\n  width: 100%;\n  height: 100%;\n}\n"] }]
  }], () => [{ type: ElementRef }], { channel: [{
    type: Input
  }], volume: [{
    type: Input
  }], showCaptions: [{
    type: Input
  }] });
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && \u0275setClassDebugInfo(ArtPlayerComponent, { className: "ArtPlayerComponent", filePath: "src/app/player/components/art-player/art-player.component.ts", lineNumber: 33 });
})();

// src/app/player/components/d-player/d-player.component.ts
var import_dplayer = __toESM(require_DPlayer_min());
var DPlayerComponent = class _DPlayerComponent {
  constructor(elementRef) {
    this.elementRef = elementRef;
    this.volume = 1;
    this.showCaptions = false;
  }
  ngOnInit() {
    this.initPlayer();
  }
  ngOnDestroy() {
    if (this.player) {
      this.player.destroy();
    }
  }
  ngOnChanges(changes) {
    if (changes["channel"] && !changes["channel"].firstChange) {
      if (this.player) {
        this.player.destroy();
      }
      this.initPlayer();
    }
  }
  initPlayer() {
    const el = this.elementRef.nativeElement.querySelector(".dplayer-container");
    const isLive = this.channel.url.toLowerCase().includes("m3u8");
    this.player = new import_dplayer.default({
      container: el,
      live: isLive,
      volume: this.volume,
      autoplay: true,
      video: {
        url: this.channel.url + (this.channel.epgParams || ""),
        type: this.getVideoType(this.channel.url)
      },
      logo: this.channel.tvg?.logo
    });
  }
  getVideoType(url) {
    const extension = url.split(".").pop()?.toLowerCase();
    switch (extension) {
      case "mkv":
        return "video/matroska";
      case "m3u8":
        return "hls";
      case "mp4":
        return "auto";
      default:
        return "auto";
    }
  }
  static {
    this.\u0275fac = function DPlayerComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || _DPlayerComponent)(\u0275\u0275directiveInject(ElementRef));
    };
  }
  static {
    this.\u0275cmp = /* @__PURE__ */ \u0275\u0275defineComponent({ type: _DPlayerComponent, selectors: [["app-d-player"]], inputs: { channel: "channel", volume: "volume", showCaptions: "showCaptions" }, features: [\u0275\u0275NgOnChangesFeature], decls: 2, vars: 0, consts: [["dplayer", ""], [1, "dplayer-container"]], template: function DPlayerComponent_Template(rf, ctx) {
      if (rf & 1) {
        \u0275\u0275element(0, "div", 1, 0);
      }
    }, dependencies: [CommonModule], styles: ["\n\n.dplayer-container[_ngcontent-%COMP%] {\n  width: 100%;\n  height: calc(100vh - 64px);\n}"] });
  }
};
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(DPlayerComponent, [{
    type: Component,
    args: [{ selector: "app-d-player", imports: [CommonModule], template: `<div #dplayer class="dplayer-container"></div>`, styles: ["/* angular:styles/component:css;1cec33dda68e87bc803b8932543d672018bed73a466b92d3d431737280b5e876;/Users/allen/dev/browser-extentions/dailyflim/src/app/player/components/d-player/d-player.component.ts */\n.dplayer-container {\n  width: 100%;\n  height: calc(100vh - 64px);\n}\n"] }]
  }], () => [{ type: ElementRef }], { channel: [{
    type: Input
  }], volume: [{
    type: Input
  }], showCaptions: [{
    type: Input
  }] });
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && \u0275setClassDebugInfo(DPlayerComponent, { className: "DPlayerComponent", filePath: "src/app/player/components/d-player/d-player.component.ts", lineNumber: 27 });
})();

// src/app/player/components/html-video-player/html-video-player.component.ts
var _c0 = ["videoPlayer"];
var HtmlVideoPlayerComponent = class _HtmlVideoPlayerComponent {
  constructor(dataService) {
    this.volume = 1;
    this.dataService = dataService;
  }
  ngOnInit() {
    this.videoPlayer.nativeElement.addEventListener("volumechange", () => {
      this.onVolumeChange();
    });
  }
  /**
   * Listen for component input changes
   * @param changes component changes
   */
  ngOnChanges(changes) {
    if (changes.channel && changes.channel.currentValue) {
      this.playChannel(changes.channel.currentValue);
    }
    if (changes.volume?.currentValue !== void 0) {
      console.log("Setting HTML5 player volume to:", changes.volume.currentValue);
      this.videoPlayer.nativeElement.volume = changes.volume.currentValue;
    }
  }
  /**
   * Starts to play the given channel
   * @param channel given channel object
   */
  playChannel(channel) {
    if (this.hls)
      this.hls.destroy();
    if (channel.url) {
      const url = channel.url + (channel.epgParams ?? "");
      const extension = getExtensionFromUrl(channel.url);
      this.dataService.sendIpcEvent(CHANNEL_SET_USER_AGENT, {
        userAgent: channel.http?.["user-agent"] ?? "",
        referer: channel.http?.referrer ?? "",
        origin: channel.http?.origin ?? ""
      }).then(() => {
        if (extension !== "mp4" && extension !== "mpv" && Hls && Hls.isSupported()) {
          console.log("... switching channel to ", channel.name, url);
          this.hls = new Hls();
          this.hls.attachMedia(this.videoPlayer.nativeElement);
          this.hls.loadSource(url);
          this.handlePlayOperation();
        } else {
          console.log("Using native video player...");
          this.addSourceToVideo(this.videoPlayer.nativeElement, url, "video/mp4");
          this.videoPlayer.nativeElement.play();
        }
      }).catch((error) => {
        console.error("Error setting user agent:", error);
        if (extension !== "mp4" && extension !== "mpv" && Hls && Hls.isSupported()) {
          this.hls = new Hls();
          this.hls.attachMedia(this.videoPlayer.nativeElement);
          this.hls.loadSource(url);
          this.handlePlayOperation();
        } else {
          this.addSourceToVideo(this.videoPlayer.nativeElement, url, "video/mp4");
          this.videoPlayer.nativeElement.play();
        }
      });
    }
  }
  addSourceToVideo(element, url, type2) {
    const source = document.createElement("source");
    source.src = url;
    source.type = type2;
    element.appendChild(source);
  }
  /**
   * Disables text based captions based on the global settings
   */
  disableCaptions() {
    for (let i = 0; i < this.videoPlayer.nativeElement.textTracks.length; i++) {
      this.videoPlayer.nativeElement.textTracks[i].mode = "hidden";
    }
  }
  /**
   * Handles promise based play operation
   */
  handlePlayOperation() {
    const playPromise = this.videoPlayer.nativeElement.play();
    if (playPromise !== void 0) {
      playPromise.then(() => {
        if (!this.showCaptions) {
          this.disableCaptions();
        }
      }).catch(() => {
      });
    }
  }
  /**
   * Save volume when user changes it
   */
  onVolumeChange() {
    const currentVolume = this.videoPlayer.nativeElement.volume;
    console.log("Volume changed to:", currentVolume);
    localStorage.setItem("volume", currentVolume.toString());
  }
  /**
   * Destroy hls instance on component destroy and clean up event listener
   */
  ngOnDestroy() {
    this.videoPlayer.nativeElement.removeEventListener("volumechange", this.onVolumeChange);
    if (this.hls) {
      this.hls.destroy();
    }
  }
  static {
    this.\u0275fac = function HtmlVideoPlayerComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || _HtmlVideoPlayerComponent)(\u0275\u0275directiveInject(DataService));
    };
  }
  static {
    this.\u0275cmp = /* @__PURE__ */ \u0275\u0275defineComponent({ type: _HtmlVideoPlayerComponent, selectors: [["app-html-video-player"]], viewQuery: function HtmlVideoPlayerComponent_Query(rf, ctx) {
      if (rf & 1) {
        \u0275\u0275viewQuery(_c0, 7);
      }
      if (rf & 2) {
        let _t;
        \u0275\u0275queryRefresh(_t = \u0275\u0275loadQuery()) && (ctx.videoPlayer = _t.first);
      }
    }, inputs: { channel: "channel", volume: "volume", showCaptions: "showCaptions" }, features: [\u0275\u0275NgOnChangesFeature], decls: 3, vars: 0, consts: [["videoPlayer", ""], ["id", "video-player", "autoplay", "true", "controls", "true"]], template: function HtmlVideoPlayerComponent_Template(rf, ctx) {
      if (rf & 1) {
        \u0275\u0275element(0, "video", 1, 0);
        \u0275\u0275text(2, "\n");
      }
    }, styles: ["\n\n#video-player[_ngcontent-%COMP%] {\n  width: 100%;\n  height: calc(100vh - 60px);\n}\n@media only screen and (max-width: 599px) {\n  #video-player[_ngcontent-%COMP%] {\n    width: 100%;\n    height: calc(50vh - 60px) !important;\n  }\n}"] });
  }
};
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(HtmlVideoPlayerComponent, [{
    type: Component,
    args: [{ selector: "app-html-video-player", standalone: true, template: '<video #videoPlayer id="video-player" autoplay="true" controls="true"></video>\n', styles: ["/* src/app/player/components/html-video-player/html-video-player.component.scss */\n#video-player {\n  width: 100%;\n  height: calc(100vh - 60px);\n}\n@media only screen and (max-width: 599px) {\n  #video-player {\n    width: 100%;\n    height: calc(50vh - 60px) !important;\n  }\n}\n"] }]
  }], () => [{ type: DataService }], { channel: [{
    type: Input
  }], volume: [{
    type: Input
  }], videoPlayer: [{
    type: ViewChild,
    args: ["videoPlayer", { static: true }]
  }], showCaptions: [{
    type: Input
  }] });
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && \u0275setClassDebugInfo(HtmlVideoPlayerComponent, { className: "HtmlVideoPlayerComponent", filePath: "src/app/player/components/html-video-player/html-video-player.component.ts", lineNumber: 26 });
})();

// src/app/player/components/shaka-player/shaka-player.component.ts
var import_shaka_player_ui = __toESM(require_shaka_player_ui());
var _c02 = ["videoElement"];
var _c1 = ["playerContainer"];
var ShakaPlayerComponent = class _ShakaPlayerComponent {
  constructor() {
    this.volume = 1;
    this.showCaptions = false;
  }
  /**
   * Initialize Shaka Player on component init
   */
  ngOnInit() {
    this.initializePlayer();
  }
  /**
   * Async initialization method
   */
  initializePlayer() {
    return __async(this, null, function* () {
      try {
        if (typeof shaka === "undefined") {
          console.error("Shaka Player: shaka object is not available");
          return;
        }
        shaka.polyfill.installAll();
        if (shaka.Player.isBrowserSupported()) {
          yield this.initPlayer();
        } else {
          console.error("Shaka Player: Browser not supported!");
        }
      } catch (error) {
        console.error("Shaka Player: Error during initialization:", error);
      }
    });
  }
  /**
   * Handle input changes
   */
  ngOnChanges(changes) {
    this.handleChanges(changes);
  }
  /**
   * Async changes handler
   */
  handleChanges(changes) {
    return __async(this, null, function* () {
      if (changes.options && this.player && changes.options.currentValue) {
        yield this.loadStream(changes.options.currentValue.url);
      } else if (changes.channel && this.player && changes.channel.currentValue) {
        yield this.loadStream(changes.channel.currentValue.url);
      }
      if (changes.volume?.currentValue !== void 0 && this.videoElement) {
        this.videoElement.nativeElement.volume = changes.volume.currentValue;
      }
    });
  }
  /**
   * Initialize UI overlay with controls
   */
  initializeUI() {
    if (!this.player || !this.videoElement?.nativeElement)
      return;
    try {
      this.ui = new shaka.ui.Overlay(this.player, this.videoElement.nativeElement.parentElement, this.videoElement.nativeElement);
      const uiConfig = {
        "enableTooltips": true,
        "customContextMenu": true,
        "contextMenuElements": ["save_video_frame", "statistics"],
        "controlPanelElements": [
          "play_pause",
          "mute",
          "volume",
          "time_and_duration",
          "spacer",
          "chapter",
          "captions",
          "overflow_menu",
          "picture_in_picture",
          "fullscreen"
        ],
        "overflowMenuButtons": [
          "captions",
          "language",
          "quality",
          "playback_rate",
          "statistics",
          "save_video_frame"
        ]
      };
      this.ui.configure(uiConfig);
    } catch (error) {
      console.error("Failed to initialize UI:", error);
    }
  }
  /**
   * Initialize the Shaka Player
   */
  initPlayer() {
    return __async(this, null, function* () {
      try {
        const video = this.videoElement.nativeElement;
        if (!video) {
          console.error("Shaka Player: Video element not found");
          return;
        }
        this.player = new shaka.Player(video);
        this.initializeUI();
        this.player.configure({
          streaming: {
            lowLatencyMode: true,
            rebufferingGoal: 3,
            bufferingGoal: 10,
            bufferBehind: 20
          },
          manifest: {
            dash: {
              autoCorrectDrift: true
            }
          }
        });
        video.volume = this.volume;
        const savedVolume = localStorage.getItem("volume");
        if (savedVolume) {
          video.volume = parseFloat(savedVolume);
        }
        video.addEventListener("volumechange", () => {
          localStorage.setItem("volume", video.volume.toString());
        });
        this.player.addEventListener("error", this.onErrorEvent.bind(this));
        if (this.options?.url) {
          yield this.loadStream(this.options.url);
        } else if (this.channel?.url) {
          yield this.loadStream(this.channel.url);
        } else {
          console.log("Shaka Player: No stream URL provided");
        }
      } catch (error) {
        console.error("Shaka Player: Error during player initialization:", error);
      }
    });
  }
  /**
   * Load a stream into the player
   */
  loadStream(url) {
    return __async(this, null, function* () {
      try {
        yield this.player.load(url);
      } catch (error) {
        console.error("Shaka Player: Error loading stream:", error);
      }
    });
  }
  /**
   * Handle player errors
   */
  onErrorEvent(event) {
    console.error("Shaka Player error:", event.detail);
  }
  /**
   * Clean up on component destroy
   */
  ngOnDestroy() {
    this.cleanup();
  }
  /**
   * Async cleanup method
   */
  cleanup() {
    return __async(this, null, function* () {
      if (this.ui) {
        this.ui.destroy();
      }
      if (this.player) {
        yield this.player.destroy();
      }
    });
  }
  static {
    this.\u0275fac = function ShakaPlayerComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || _ShakaPlayerComponent)();
    };
  }
  static {
    this.\u0275cmp = /* @__PURE__ */ \u0275\u0275defineComponent({ type: _ShakaPlayerComponent, selectors: [["app-shaka-player"]], viewQuery: function ShakaPlayerComponent_Query(rf, ctx) {
      if (rf & 1) {
        \u0275\u0275viewQuery(_c02, 7);
        \u0275\u0275viewQuery(_c1, 7);
      }
      if (rf & 2) {
        let _t;
        \u0275\u0275queryRefresh(_t = \u0275\u0275loadQuery()) && (ctx.videoElement = _t.first);
        \u0275\u0275queryRefresh(_t = \u0275\u0275loadQuery()) && (ctx.playerContainer = _t.first);
      }
    }, inputs: { channel: "channel", options: "options", volume: "volume", showCaptions: "showCaptions" }, features: [\u0275\u0275NgOnChangesFeature], decls: 6, vars: 0, consts: [["playerContainer", ""], ["videoElement", ""], [1, "shaka-player"], ["autoplay", "", "muted", "", "playsinline", "", "preload", "metadata", 1, "video-shaka"]], template: function ShakaPlayerComponent_Template(rf, ctx) {
      if (rf & 1) {
        \u0275\u0275elementStart(0, "div", 2, 0);
        \u0275\u0275text(2, "\n    ");
        \u0275\u0275element(3, "video", 3, 1);
        \u0275\u0275text(5, "\n");
        \u0275\u0275elementEnd();
      }
    }, styles: ["/* src/app/player/components/shaka-player/shaka-player.component.scss */\n.shaka-player {\n  position: relative !important;\n  width: 100% !important;\n  height: calc(100vh - 65px);\n}\n.video-shaka {\n  width: 100%;\n  height: 100%;\n  object-fit: contain;\n}\n@media only screen and (max-width: 599px) {\n  .shaka-player {\n    height: calc(50vh - 65px) !important;\n  }\n}\n"], encapsulation: 2 });
  }
};
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ShakaPlayerComponent, [{
    type: Component,
    args: [{ selector: "app-shaka-player", encapsulation: ViewEncapsulation.None, standalone: true, template: '<div class="shaka-player" #playerContainer>\n    <video\n        #videoElement\n        class="video-shaka"\n        autoplay\n        muted\n        playsinline\n        preload="metadata"\n    ></video>\n</div>', styles: ["/* src/app/player/components/shaka-player/shaka-player.component.scss */\n.shaka-player {\n  position: relative !important;\n  width: 100% !important;\n  height: calc(100vh - 65px);\n}\n.video-shaka {\n  width: 100%;\n  height: 100%;\n  object-fit: contain;\n}\n@media only screen and (max-width: 599px) {\n  .shaka-player {\n    height: calc(50vh - 65px) !important;\n  }\n}\n"] }]
  }], null, { videoElement: [{
    type: ViewChild,
    args: ["videoElement", { static: true }]
  }], playerContainer: [{
    type: ViewChild,
    args: ["playerContainer", { static: true }]
  }], channel: [{
    type: Input
  }], options: [{
    type: Input
  }], volume: [{
    type: Input
  }], showCaptions: [{
    type: Input
  }] });
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && \u0275setClassDebugInfo(ShakaPlayerComponent, { className: "ShakaPlayerComponent", filePath: "src/app/player/components/shaka-player/shaka-player.component.ts", lineNumber: 26 });
})();

// node_modules/.pnpm/video.js@7.20.3/node_modules/video.js/dist/video.es.js
var import_window6 = __toESM(require_window());
var import_document = __toESM(require_document2());

// node_modules/.pnpm/@babel+runtime@7.28.2/node_modules/@babel/runtime/helpers/esm/extends.js
function _extends2() {
  return _extends2 = Object.assign ? Object.assign.bind() : function(n) {
    for (var e = 1; e < arguments.length; e++) {
      var t2 = arguments[e];
      for (var r2 in t2) ({}).hasOwnProperty.call(t2, r2) && (n[r2] = t2[r2]);
    }
    return n;
  }, _extends2.apply(null, arguments);
}

// node_modules/.pnpm/video.js@7.20.3/node_modules/video.js/dist/video.es.js
var import_keycode = __toESM(require_keycode());

// node_modules/.pnpm/@babel+runtime@7.28.2/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
function _assertThisInitialized(e) {
  if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  return e;
}

// node_modules/.pnpm/@babel+runtime@7.28.2/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js
function _setPrototypeOf(t2, e) {
  return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function(t3, e2) {
    return t3.__proto__ = e2, t3;
  }, _setPrototypeOf(t2, e);
}

// node_modules/.pnpm/@babel+runtime@7.28.2/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js
function _inheritsLoose(t2, o) {
  t2.prototype = Object.create(o.prototype), t2.prototype.constructor = t2, _setPrototypeOf(t2, o);
}

// node_modules/.pnpm/video.js@7.20.3/node_modules/video.js/dist/video.es.js
var import_tuple = __toESM(require_tuple());
var import_xhr = __toESM(require_lib());
var import_videojs_vtt = __toESM(require_browser_index());

// node_modules/.pnpm/@babel+runtime@7.28.2/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js
function _isNativeReflectConstruct() {
  try {
    var t2 = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t3) {
  }
  return (_isNativeReflectConstruct = function _isNativeReflectConstruct2() {
    return !!t2;
  })();
}

// node_modules/.pnpm/@babel+runtime@7.28.2/node_modules/@babel/runtime/helpers/esm/construct.js
function _construct(t2, e, r2) {
  if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
  var o = [null];
  o.push.apply(o, e);
  var p = new (t2.bind.apply(t2, o))();
  return r2 && _setPrototypeOf(p, r2.prototype), p;
}

// node_modules/.pnpm/@babel+runtime@7.28.2/node_modules/@babel/runtime/helpers/esm/inherits.js
function _inherits(t2, e) {
  if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
  t2.prototype = Object.create(e && e.prototype, {
    constructor: {
      value: t2,
      writable: true,
      configurable: true
    }
  }), Object.defineProperty(t2, "prototype", {
    writable: false
  }), e && _setPrototypeOf(t2, e);
}

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/resolve-url.js
var import_url_toolkit = __toESM(require_url_toolkit());
var import_window = __toESM(require_window());
var DEFAULT_LOCATION = "http://example.com";
var resolveUrl = function resolveUrl2(baseUrl, relativeUrl) {
  if (/^[a-z]+:/i.test(relativeUrl)) {
    return relativeUrl;
  }
  if (/^data:/.test(baseUrl)) {
    baseUrl = import_window.default.location && import_window.default.location.href || "";
  }
  var nativeURL = typeof import_window.default.URL === "function";
  var protocolLess = /^\/\//.test(baseUrl);
  var removeLocation = !import_window.default.location && !/\/\//i.test(baseUrl);
  if (nativeURL) {
    baseUrl = new import_window.default.URL(baseUrl, import_window.default.location || DEFAULT_LOCATION);
  } else if (!/\/\//i.test(baseUrl)) {
    baseUrl = import_url_toolkit.default.buildAbsoluteURL(import_window.default.location && import_window.default.location.href || "", baseUrl);
  }
  if (nativeURL) {
    var newUrl = new URL(relativeUrl, baseUrl);
    if (removeLocation) {
      return newUrl.href.slice(DEFAULT_LOCATION.length);
    } else if (protocolLess) {
      return newUrl.href.slice(newUrl.protocol.length);
    }
    return newUrl.href;
  }
  return import_url_toolkit.default.buildAbsoluteURL(baseUrl, relativeUrl);
};
var resolve_url_default = resolveUrl;

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/stream.js
var Stream = /* @__PURE__ */ function() {
  function Stream2() {
    this.listeners = {};
  }
  var _proto = Stream2.prototype;
  _proto.on = function on3(type2, listener) {
    if (!this.listeners[type2]) {
      this.listeners[type2] = [];
    }
    this.listeners[type2].push(listener);
  };
  _proto.off = function off2(type2, listener) {
    if (!this.listeners[type2]) {
      return false;
    }
    var index = this.listeners[type2].indexOf(listener);
    this.listeners[type2] = this.listeners[type2].slice(0);
    this.listeners[type2].splice(index, 1);
    return index > -1;
  };
  _proto.trigger = function trigger2(type2) {
    var callbacks = this.listeners[type2];
    if (!callbacks) {
      return;
    }
    if (arguments.length === 2) {
      var length = callbacks.length;
      for (var i = 0; i < length; ++i) {
        callbacks[i].call(this, arguments[1]);
      }
    } else {
      var args = Array.prototype.slice.call(arguments, 1);
      var _length = callbacks.length;
      for (var _i = 0; _i < _length; ++_i) {
        callbacks[_i].apply(this, args);
      }
    }
  };
  _proto.dispose = function dispose() {
    this.listeners = {};
  };
  _proto.pipe = function pipe(destination) {
    this.on("data", function(data) {
      destination.push(data);
    });
  };
  return Stream2;
}();

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/decode-b64-to-uint8-array.js
var import_window2 = __toESM(require_window());
var atob2 = function atob3(s) {
  return import_window2.default.atob ? import_window2.default.atob(s) : Buffer.from(s, "base64").toString("binary");
};
function decodeB64ToUint8Array(b64Text) {
  var decodedString = atob2(b64Text);
  var array = new Uint8Array(decodedString.length);
  for (var i = 0; i < decodedString.length; i++) {
    array[i] = decodedString.charCodeAt(i);
  }
  return array;
}

// node_modules/.pnpm/m3u8-parser@4.7.1/node_modules/m3u8-parser/dist/m3u8-parser.es.js
var LineStream = /* @__PURE__ */ function(_Stream) {
  _inheritsLoose(LineStream2, _Stream);
  function LineStream2() {
    var _this;
    _this = _Stream.call(this) || this;
    _this.buffer = "";
    return _this;
  }
  var _proto = LineStream2.prototype;
  _proto.push = function push2(data) {
    var nextNewline;
    this.buffer += data;
    nextNewline = this.buffer.indexOf("\n");
    for (; nextNewline > -1; nextNewline = this.buffer.indexOf("\n")) {
      this.trigger("data", this.buffer.substring(0, nextNewline));
      this.buffer = this.buffer.substring(nextNewline + 1);
    }
  };
  return LineStream2;
}(Stream);
var TAB = String.fromCharCode(9);
var parseByterange = function parseByterange2(byterangeString) {
  var match = /([0-9.]*)?@?([0-9.]*)?/.exec(byterangeString || "");
  var result = {};
  if (match[1]) {
    result.length = parseInt(match[1], 10);
  }
  if (match[2]) {
    result.offset = parseInt(match[2], 10);
  }
  return result;
};
var attributeSeparator = function attributeSeparator2() {
  var key = "[^=]*";
  var value = '"[^"]*"|[^,]*';
  var keyvalue = "(?:" + key + ")=(?:" + value + ")";
  return new RegExp("(?:^|,)(" + keyvalue + ")");
};
var parseAttributes = function parseAttributes2(attributes) {
  var attrs = attributes.split(attributeSeparator());
  var result = {};
  var i = attrs.length;
  var attr;
  while (i--) {
    if (attrs[i] === "") {
      continue;
    }
    attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1);
    attr[0] = attr[0].replace(/^\s+|\s+$/g, "");
    attr[1] = attr[1].replace(/^\s+|\s+$/g, "");
    attr[1] = attr[1].replace(/^['"](.*)['"]$/g, "$1");
    result[attr[0]] = attr[1];
  }
  return result;
};
var ParseStream = /* @__PURE__ */ function(_Stream) {
  _inheritsLoose(ParseStream2, _Stream);
  function ParseStream2() {
    var _this;
    _this = _Stream.call(this) || this;
    _this.customParsers = [];
    _this.tagMappers = [];
    return _this;
  }
  var _proto = ParseStream2.prototype;
  _proto.push = function push2(line) {
    var _this2 = this;
    var match;
    var event;
    line = line.trim();
    if (line.length === 0) {
      return;
    }
    if (line[0] !== "#") {
      this.trigger("data", {
        type: "uri",
        uri: line
      });
      return;
    }
    var newLines = this.tagMappers.reduce(function(acc, mapper) {
      var mappedLine = mapper(line);
      if (mappedLine === line) {
        return acc;
      }
      return acc.concat([mappedLine]);
    }, [line]);
    newLines.forEach(function(newLine) {
      for (var i = 0; i < _this2.customParsers.length; i++) {
        if (_this2.customParsers[i].call(_this2, newLine)) {
          return;
        }
      }
      if (newLine.indexOf("#EXT") !== 0) {
        _this2.trigger("data", {
          type: "comment",
          text: newLine.slice(1)
        });
        return;
      }
      newLine = newLine.replace("\r", "");
      match = /^#EXTM3U/.exec(newLine);
      if (match) {
        _this2.trigger("data", {
          type: "tag",
          tagType: "m3u"
        });
        return;
      }
      match = /^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "inf"
        };
        if (match[1]) {
          event.duration = parseFloat(match[1]);
        }
        if (match[2]) {
          event.title = match[2];
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "targetduration"
        };
        if (match[1]) {
          event.duration = parseInt(match[1], 10);
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-VERSION:?([0-9.]*)?/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "version"
        };
        if (match[1]) {
          event.version = parseInt(match[1], 10);
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "media-sequence"
        };
        if (match[1]) {
          event.number = parseInt(match[1], 10);
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-DISCONTINUITY-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "discontinuity-sequence"
        };
        if (match[1]) {
          event.number = parseInt(match[1], 10);
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-PLAYLIST-TYPE:?(.*)?$/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "playlist-type"
        };
        if (match[1]) {
          event.playlistType = match[1];
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-BYTERANGE:?(.*)?$/.exec(newLine);
      if (match) {
        event = _extends2(parseByterange(match[1]), {
          type: "tag",
          tagType: "byterange"
        });
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-ALLOW-CACHE:?(YES|NO)?/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "allow-cache"
        };
        if (match[1]) {
          event.allowed = !/NO/.test(match[1]);
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-MAP:?(.*)$/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "map"
        };
        if (match[1]) {
          var attributes = parseAttributes(match[1]);
          if (attributes.URI) {
            event.uri = attributes.URI;
          }
          if (attributes.BYTERANGE) {
            event.byterange = parseByterange(attributes.BYTERANGE);
          }
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-STREAM-INF:?(.*)$/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "stream-inf"
        };
        if (match[1]) {
          event.attributes = parseAttributes(match[1]);
          if (event.attributes.RESOLUTION) {
            var split = event.attributes.RESOLUTION.split("x");
            var resolution = {};
            if (split[0]) {
              resolution.width = parseInt(split[0], 10);
            }
            if (split[1]) {
              resolution.height = parseInt(split[1], 10);
            }
            event.attributes.RESOLUTION = resolution;
          }
          if (event.attributes.BANDWIDTH) {
            event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
          }
          if (event.attributes["PROGRAM-ID"]) {
            event.attributes["PROGRAM-ID"] = parseInt(event.attributes["PROGRAM-ID"], 10);
          }
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-MEDIA:?(.*)$/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "media"
        };
        if (match[1]) {
          event.attributes = parseAttributes(match[1]);
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-ENDLIST/.exec(newLine);
      if (match) {
        _this2.trigger("data", {
          type: "tag",
          tagType: "endlist"
        });
        return;
      }
      match = /^#EXT-X-DISCONTINUITY/.exec(newLine);
      if (match) {
        _this2.trigger("data", {
          type: "tag",
          tagType: "discontinuity"
        });
        return;
      }
      match = /^#EXT-X-PROGRAM-DATE-TIME:?(.*)$/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "program-date-time"
        };
        if (match[1]) {
          event.dateTimeString = match[1];
          event.dateTimeObject = new Date(match[1]);
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-KEY:?(.*)$/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "key"
        };
        if (match[1]) {
          event.attributes = parseAttributes(match[1]);
          if (event.attributes.IV) {
            if (event.attributes.IV.substring(0, 2).toLowerCase() === "0x") {
              event.attributes.IV = event.attributes.IV.substring(2);
            }
            event.attributes.IV = event.attributes.IV.match(/.{8}/g);
            event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
            event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
            event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
            event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
            event.attributes.IV = new Uint32Array(event.attributes.IV);
          }
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-START:?(.*)$/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "start"
        };
        if (match[1]) {
          event.attributes = parseAttributes(match[1]);
          event.attributes["TIME-OFFSET"] = parseFloat(event.attributes["TIME-OFFSET"]);
          event.attributes.PRECISE = /YES/.test(event.attributes.PRECISE);
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-CUE-OUT-CONT:?(.*)?$/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "cue-out-cont"
        };
        if (match[1]) {
          event.data = match[1];
        } else {
          event.data = "";
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-CUE-OUT:?(.*)?$/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "cue-out"
        };
        if (match[1]) {
          event.data = match[1];
        } else {
          event.data = "";
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-CUE-IN:?(.*)?$/.exec(newLine);
      if (match) {
        event = {
          type: "tag",
          tagType: "cue-in"
        };
        if (match[1]) {
          event.data = match[1];
        } else {
          event.data = "";
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-SKIP:(.*)$/.exec(newLine);
      if (match && match[1]) {
        event = {
          type: "tag",
          tagType: "skip"
        };
        event.attributes = parseAttributes(match[1]);
        if (event.attributes.hasOwnProperty("SKIPPED-SEGMENTS")) {
          event.attributes["SKIPPED-SEGMENTS"] = parseInt(event.attributes["SKIPPED-SEGMENTS"], 10);
        }
        if (event.attributes.hasOwnProperty("RECENTLY-REMOVED-DATERANGES")) {
          event.attributes["RECENTLY-REMOVED-DATERANGES"] = event.attributes["RECENTLY-REMOVED-DATERANGES"].split(TAB);
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-PART:(.*)$/.exec(newLine);
      if (match && match[1]) {
        event = {
          type: "tag",
          tagType: "part"
        };
        event.attributes = parseAttributes(match[1]);
        ["DURATION"].forEach(function(key) {
          if (event.attributes.hasOwnProperty(key)) {
            event.attributes[key] = parseFloat(event.attributes[key]);
          }
        });
        ["INDEPENDENT", "GAP"].forEach(function(key) {
          if (event.attributes.hasOwnProperty(key)) {
            event.attributes[key] = /YES/.test(event.attributes[key]);
          }
        });
        if (event.attributes.hasOwnProperty("BYTERANGE")) {
          event.attributes.byterange = parseByterange(event.attributes.BYTERANGE);
        }
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-SERVER-CONTROL:(.*)$/.exec(newLine);
      if (match && match[1]) {
        event = {
          type: "tag",
          tagType: "server-control"
        };
        event.attributes = parseAttributes(match[1]);
        ["CAN-SKIP-UNTIL", "PART-HOLD-BACK", "HOLD-BACK"].forEach(function(key) {
          if (event.attributes.hasOwnProperty(key)) {
            event.attributes[key] = parseFloat(event.attributes[key]);
          }
        });
        ["CAN-SKIP-DATERANGES", "CAN-BLOCK-RELOAD"].forEach(function(key) {
          if (event.attributes.hasOwnProperty(key)) {
            event.attributes[key] = /YES/.test(event.attributes[key]);
          }
        });
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-PART-INF:(.*)$/.exec(newLine);
      if (match && match[1]) {
        event = {
          type: "tag",
          tagType: "part-inf"
        };
        event.attributes = parseAttributes(match[1]);
        ["PART-TARGET"].forEach(function(key) {
          if (event.attributes.hasOwnProperty(key)) {
            event.attributes[key] = parseFloat(event.attributes[key]);
          }
        });
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-PRELOAD-HINT:(.*)$/.exec(newLine);
      if (match && match[1]) {
        event = {
          type: "tag",
          tagType: "preload-hint"
        };
        event.attributes = parseAttributes(match[1]);
        ["BYTERANGE-START", "BYTERANGE-LENGTH"].forEach(function(key) {
          if (event.attributes.hasOwnProperty(key)) {
            event.attributes[key] = parseInt(event.attributes[key], 10);
            var subkey = key === "BYTERANGE-LENGTH" ? "length" : "offset";
            event.attributes.byterange = event.attributes.byterange || {};
            event.attributes.byterange[subkey] = event.attributes[key];
            delete event.attributes[key];
          }
        });
        _this2.trigger("data", event);
        return;
      }
      match = /^#EXT-X-RENDITION-REPORT:(.*)$/.exec(newLine);
      if (match && match[1]) {
        event = {
          type: "tag",
          tagType: "rendition-report"
        };
        event.attributes = parseAttributes(match[1]);
        ["LAST-MSN", "LAST-PART"].forEach(function(key) {
          if (event.attributes.hasOwnProperty(key)) {
            event.attributes[key] = parseInt(event.attributes[key], 10);
          }
        });
        _this2.trigger("data", event);
        return;
      }
      _this2.trigger("data", {
        type: "tag",
        data: newLine.slice(4)
      });
    });
  };
  _proto.addParser = function addParser(_ref) {
    var _this3 = this;
    var expression = _ref.expression, customType = _ref.customType, dataParser = _ref.dataParser, segment = _ref.segment;
    if (typeof dataParser !== "function") {
      dataParser = function dataParser2(line) {
        return line;
      };
    }
    this.customParsers.push(function(line) {
      var match = expression.exec(line);
      if (match) {
        _this3.trigger("data", {
          type: "custom",
          data: dataParser(line),
          customType,
          segment
        });
        return true;
      }
    });
  };
  _proto.addTagMapper = function addTagMapper(_ref2) {
    var expression = _ref2.expression, map = _ref2.map;
    var mapFn = function mapFn2(line) {
      if (expression.test(line)) {
        return map(line);
      }
      return line;
    };
    this.tagMappers.push(mapFn);
  };
  return ParseStream2;
}(Stream);
var camelCase = function camelCase2(str) {
  return str.toLowerCase().replace(/-(\w)/g, function(a) {
    return a[1].toUpperCase();
  });
};
var camelCaseKeys = function camelCaseKeys2(attributes) {
  var result = {};
  Object.keys(attributes).forEach(function(key) {
    result[camelCase(key)] = attributes[key];
  });
  return result;
};
var setHoldBack = function setHoldBack2(manifest) {
  var serverControl = manifest.serverControl, targetDuration = manifest.targetDuration, partTargetDuration = manifest.partTargetDuration;
  if (!serverControl) {
    return;
  }
  var tag = "#EXT-X-SERVER-CONTROL";
  var hb = "holdBack";
  var phb = "partHoldBack";
  var minTargetDuration = targetDuration && targetDuration * 3;
  var minPartDuration = partTargetDuration && partTargetDuration * 2;
  if (targetDuration && !serverControl.hasOwnProperty(hb)) {
    serverControl[hb] = minTargetDuration;
    this.trigger("info", {
      message: tag + " defaulting HOLD-BACK to targetDuration * 3 (" + minTargetDuration + ")."
    });
  }
  if (minTargetDuration && serverControl[hb] < minTargetDuration) {
    this.trigger("warn", {
      message: tag + " clamping HOLD-BACK (" + serverControl[hb] + ") to targetDuration * 3 (" + minTargetDuration + ")"
    });
    serverControl[hb] = minTargetDuration;
  }
  if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
    serverControl[phb] = partTargetDuration * 3;
    this.trigger("info", {
      message: tag + " defaulting PART-HOLD-BACK to partTargetDuration * 3 (" + serverControl[phb] + ")."
    });
  }
  if (partTargetDuration && serverControl[phb] < minPartDuration) {
    this.trigger("warn", {
      message: tag + " clamping PART-HOLD-BACK (" + serverControl[phb] + ") to partTargetDuration * 2 (" + minPartDuration + ")."
    });
    serverControl[phb] = minPartDuration;
  }
};
var Parser = /* @__PURE__ */ function(_Stream) {
  _inheritsLoose(Parser2, _Stream);
  function Parser2() {
    var _this;
    _this = _Stream.call(this) || this;
    _this.lineStream = new LineStream();
    _this.parseStream = new ParseStream();
    _this.lineStream.pipe(_this.parseStream);
    var self2 = _assertThisInitialized(_this);
    var uris = [];
    var currentUri = {};
    var currentMap;
    var _key;
    var hasParts = false;
    var noop4 = function noop5() {
    };
    var defaultMediaGroups = {
      "AUDIO": {},
      "VIDEO": {},
      "CLOSED-CAPTIONS": {},
      "SUBTITLES": {}
    };
    var widevineUuid = "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";
    var currentTimeline = 0;
    _this.manifest = {
      allowCache: true,
      discontinuityStarts: [],
      segments: []
    };
    var lastByterangeEnd = 0;
    var lastPartByterangeEnd = 0;
    _this.on("end", function() {
      if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
        return;
      }
      if (!currentUri.map && currentMap) {
        currentUri.map = currentMap;
      }
      if (!currentUri.key && _key) {
        currentUri.key = _key;
      }
      if (!currentUri.timeline && typeof currentTimeline === "number") {
        currentUri.timeline = currentTimeline;
      }
      _this.manifest.preloadSegment = currentUri;
    });
    _this.parseStream.on("data", function(entry) {
      var mediaGroup;
      var rendition;
      ({
        tag: function tag() {
          ({
            version: function version6() {
              if (entry.version) {
                this.manifest.version = entry.version;
              }
            },
            "allow-cache": function allowCache() {
              this.manifest.allowCache = entry.allowed;
              if (!("allowed" in entry)) {
                this.trigger("info", {
                  message: "defaulting allowCache to YES"
                });
                this.manifest.allowCache = true;
              }
            },
            byterange: function byterange() {
              var byterange2 = {};
              if ("length" in entry) {
                currentUri.byterange = byterange2;
                byterange2.length = entry.length;
                if (!("offset" in entry)) {
                  entry.offset = lastByterangeEnd;
                }
              }
              if ("offset" in entry) {
                currentUri.byterange = byterange2;
                byterange2.offset = entry.offset;
              }
              lastByterangeEnd = byterange2.offset + byterange2.length;
            },
            endlist: function endlist() {
              this.manifest.endList = true;
            },
            inf: function inf() {
              if (!("mediaSequence" in this.manifest)) {
                this.manifest.mediaSequence = 0;
                this.trigger("info", {
                  message: "defaulting media sequence to zero"
                });
              }
              if (!("discontinuitySequence" in this.manifest)) {
                this.manifest.discontinuitySequence = 0;
                this.trigger("info", {
                  message: "defaulting discontinuity sequence to zero"
                });
              }
              if (entry.duration > 0) {
                currentUri.duration = entry.duration;
              }
              if (entry.duration === 0) {
                currentUri.duration = 0.01;
                this.trigger("info", {
                  message: "updating zero segment duration to a small value"
                });
              }
              this.manifest.segments = uris;
            },
            key: function key() {
              if (!entry.attributes) {
                this.trigger("warn", {
                  message: "ignoring key declaration without attribute list"
                });
                return;
              }
              if (entry.attributes.METHOD === "NONE") {
                _key = null;
                return;
              }
              if (!entry.attributes.URI) {
                this.trigger("warn", {
                  message: "ignoring key declaration without URI"
                });
                return;
              }
              if (entry.attributes.KEYFORMAT === "com.apple.streamingkeydelivery") {
                this.manifest.contentProtection = this.manifest.contentProtection || {};
                this.manifest.contentProtection["com.apple.fps.1_0"] = {
                  attributes: entry.attributes
                };
                return;
              }
              if (entry.attributes.KEYFORMAT === "com.microsoft.playready") {
                this.manifest.contentProtection = this.manifest.contentProtection || {};
                this.manifest.contentProtection["com.microsoft.playready"] = {
                  uri: entry.attributes.URI
                };
                return;
              }
              if (entry.attributes.KEYFORMAT === widevineUuid) {
                var VALID_METHODS = ["SAMPLE-AES", "SAMPLE-AES-CTR", "SAMPLE-AES-CENC"];
                if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
                  this.trigger("warn", {
                    message: "invalid key method provided for Widevine"
                  });
                  return;
                }
                if (entry.attributes.METHOD === "SAMPLE-AES-CENC") {
                  this.trigger("warn", {
                    message: "SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"
                  });
                }
                if (entry.attributes.URI.substring(0, 23) !== "data:text/plain;base64,") {
                  this.trigger("warn", {
                    message: "invalid key URI provided for Widevine"
                  });
                  return;
                }
                if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === "0x")) {
                  this.trigger("warn", {
                    message: "invalid key ID provided for Widevine"
                  });
                  return;
                }
                this.manifest.contentProtection = this.manifest.contentProtection || {};
                this.manifest.contentProtection["com.widevine.alpha"] = {
                  attributes: {
                    schemeIdUri: entry.attributes.KEYFORMAT,
                    // remove '0x' from the key id string
                    keyId: entry.attributes.KEYID.substring(2)
                  },
                  // decode the base64-encoded PSSH box
                  pssh: decodeB64ToUint8Array(entry.attributes.URI.split(",")[1])
                };
                return;
              }
              if (!entry.attributes.METHOD) {
                this.trigger("warn", {
                  message: "defaulting key method to AES-128"
                });
              }
              _key = {
                method: entry.attributes.METHOD || "AES-128",
                uri: entry.attributes.URI
              };
              if (typeof entry.attributes.IV !== "undefined") {
                _key.iv = entry.attributes.IV;
              }
            },
            "media-sequence": function mediaSequence() {
              if (!isFinite(entry.number)) {
                this.trigger("warn", {
                  message: "ignoring invalid media sequence: " + entry.number
                });
                return;
              }
              this.manifest.mediaSequence = entry.number;
            },
            "discontinuity-sequence": function discontinuitySequence() {
              if (!isFinite(entry.number)) {
                this.trigger("warn", {
                  message: "ignoring invalid discontinuity sequence: " + entry.number
                });
                return;
              }
              this.manifest.discontinuitySequence = entry.number;
              currentTimeline = entry.number;
            },
            "playlist-type": function playlistType() {
              if (!/VOD|EVENT/.test(entry.playlistType)) {
                this.trigger("warn", {
                  message: "ignoring unknown playlist type: " + entry.playlist
                });
                return;
              }
              this.manifest.playlistType = entry.playlistType;
            },
            map: function map() {
              currentMap = {};
              if (entry.uri) {
                currentMap.uri = entry.uri;
              }
              if (entry.byterange) {
                currentMap.byterange = entry.byterange;
              }
              if (_key) {
                currentMap.key = _key;
              }
            },
            "stream-inf": function streamInf() {
              this.manifest.playlists = uris;
              this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
              if (!entry.attributes) {
                this.trigger("warn", {
                  message: "ignoring empty stream-inf attributes"
                });
                return;
              }
              if (!currentUri.attributes) {
                currentUri.attributes = {};
              }
              _extends2(currentUri.attributes, entry.attributes);
            },
            media: function media() {
              this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
              if (!(entry.attributes && entry.attributes.TYPE && entry.attributes["GROUP-ID"] && entry.attributes.NAME)) {
                this.trigger("warn", {
                  message: "ignoring incomplete or missing media group"
                });
                return;
              }
              var mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
              mediaGroupType[entry.attributes["GROUP-ID"]] = mediaGroupType[entry.attributes["GROUP-ID"]] || {};
              mediaGroup = mediaGroupType[entry.attributes["GROUP-ID"]];
              rendition = {
                default: /yes/i.test(entry.attributes.DEFAULT)
              };
              if (rendition.default) {
                rendition.autoselect = true;
              } else {
                rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
              }
              if (entry.attributes.LANGUAGE) {
                rendition.language = entry.attributes.LANGUAGE;
              }
              if (entry.attributes.URI) {
                rendition.uri = entry.attributes.URI;
              }
              if (entry.attributes["INSTREAM-ID"]) {
                rendition.instreamId = entry.attributes["INSTREAM-ID"];
              }
              if (entry.attributes.CHARACTERISTICS) {
                rendition.characteristics = entry.attributes.CHARACTERISTICS;
              }
              if (entry.attributes.FORCED) {
                rendition.forced = /yes/i.test(entry.attributes.FORCED);
              }
              mediaGroup[entry.attributes.NAME] = rendition;
            },
            discontinuity: function discontinuity() {
              currentTimeline += 1;
              currentUri.discontinuity = true;
              this.manifest.discontinuityStarts.push(uris.length);
            },
            "program-date-time": function programDateTime() {
              if (typeof this.manifest.dateTimeString === "undefined") {
                this.manifest.dateTimeString = entry.dateTimeString;
                this.manifest.dateTimeObject = entry.dateTimeObject;
              }
              currentUri.dateTimeString = entry.dateTimeString;
              currentUri.dateTimeObject = entry.dateTimeObject;
            },
            targetduration: function targetduration() {
              if (!isFinite(entry.duration) || entry.duration < 0) {
                this.trigger("warn", {
                  message: "ignoring invalid target duration: " + entry.duration
                });
                return;
              }
              this.manifest.targetDuration = entry.duration;
              setHoldBack.call(this, this.manifest);
            },
            start: function start2() {
              if (!entry.attributes || isNaN(entry.attributes["TIME-OFFSET"])) {
                this.trigger("warn", {
                  message: "ignoring start declaration without appropriate attribute list"
                });
                return;
              }
              this.manifest.start = {
                timeOffset: entry.attributes["TIME-OFFSET"],
                precise: entry.attributes.PRECISE
              };
            },
            "cue-out": function cueOut() {
              currentUri.cueOut = entry.data;
            },
            "cue-out-cont": function cueOutCont() {
              currentUri.cueOutCont = entry.data;
            },
            "cue-in": function cueIn() {
              currentUri.cueIn = entry.data;
            },
            "skip": function skip() {
              this.manifest.skip = camelCaseKeys(entry.attributes);
              this.warnOnMissingAttributes_("#EXT-X-SKIP", entry.attributes, ["SKIPPED-SEGMENTS"]);
            },
            "part": function part() {
              var _this2 = this;
              hasParts = true;
              var segmentIndex = this.manifest.segments.length;
              var part2 = camelCaseKeys(entry.attributes);
              currentUri.parts = currentUri.parts || [];
              currentUri.parts.push(part2);
              if (part2.byterange) {
                if (!part2.byterange.hasOwnProperty("offset")) {
                  part2.byterange.offset = lastPartByterangeEnd;
                }
                lastPartByterangeEnd = part2.byterange.offset + part2.byterange.length;
              }
              var partIndex = currentUri.parts.length - 1;
              this.warnOnMissingAttributes_("#EXT-X-PART #" + partIndex + " for segment #" + segmentIndex, entry.attributes, ["URI", "DURATION"]);
              if (this.manifest.renditionReports) {
                this.manifest.renditionReports.forEach(function(r2, i) {
                  if (!r2.hasOwnProperty("lastPart")) {
                    _this2.trigger("warn", {
                      message: "#EXT-X-RENDITION-REPORT #" + i + " lacks required attribute(s): LAST-PART"
                    });
                  }
                });
              }
            },
            "server-control": function serverControl() {
              var attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
              if (!attrs.hasOwnProperty("canBlockReload")) {
                attrs.canBlockReload = false;
                this.trigger("info", {
                  message: "#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"
                });
              }
              setHoldBack.call(this, this.manifest);
              if (attrs.canSkipDateranges && !attrs.hasOwnProperty("canSkipUntil")) {
                this.trigger("warn", {
                  message: "#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set"
                });
              }
            },
            "preload-hint": function preloadHint() {
              var segmentIndex = this.manifest.segments.length;
              var hint = camelCaseKeys(entry.attributes);
              var isPart = hint.type && hint.type === "PART";
              currentUri.preloadHints = currentUri.preloadHints || [];
              currentUri.preloadHints.push(hint);
              if (hint.byterange) {
                if (!hint.byterange.hasOwnProperty("offset")) {
                  hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
                  if (isPart) {
                    lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
                  }
                }
              }
              var index = currentUri.preloadHints.length - 1;
              this.warnOnMissingAttributes_("#EXT-X-PRELOAD-HINT #" + index + " for segment #" + segmentIndex, entry.attributes, ["TYPE", "URI"]);
              if (!hint.type) {
                return;
              }
              for (var i = 0; i < currentUri.preloadHints.length - 1; i++) {
                var otherHint = currentUri.preloadHints[i];
                if (!otherHint.type) {
                  continue;
                }
                if (otherHint.type === hint.type) {
                  this.trigger("warn", {
                    message: "#EXT-X-PRELOAD-HINT #" + index + " for segment #" + segmentIndex + " has the same TYPE " + hint.type + " as preload hint #" + i
                  });
                }
              }
            },
            "rendition-report": function renditionReport() {
              var report = camelCaseKeys(entry.attributes);
              this.manifest.renditionReports = this.manifest.renditionReports || [];
              this.manifest.renditionReports.push(report);
              var index = this.manifest.renditionReports.length - 1;
              var required = ["LAST-MSN", "URI"];
              if (hasParts) {
                required.push("LAST-PART");
              }
              this.warnOnMissingAttributes_("#EXT-X-RENDITION-REPORT #" + index, entry.attributes, required);
            },
            "part-inf": function partInf() {
              this.manifest.partInf = camelCaseKeys(entry.attributes);
              this.warnOnMissingAttributes_("#EXT-X-PART-INF", entry.attributes, ["PART-TARGET"]);
              if (this.manifest.partInf.partTarget) {
                this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
              }
              setHoldBack.call(this, this.manifest);
            }
          }[entry.tagType] || noop4).call(self2);
        },
        uri: function uri() {
          currentUri.uri = entry.uri;
          uris.push(currentUri);
          if (this.manifest.targetDuration && !("duration" in currentUri)) {
            this.trigger("warn", {
              message: "defaulting segment duration to the target duration"
            });
            currentUri.duration = this.manifest.targetDuration;
          }
          if (_key) {
            currentUri.key = _key;
          }
          currentUri.timeline = currentTimeline;
          if (currentMap) {
            currentUri.map = currentMap;
          }
          lastPartByterangeEnd = 0;
          currentUri = {};
        },
        comment: function comment() {
        },
        custom: function custom() {
          if (entry.segment) {
            currentUri.custom = currentUri.custom || {};
            currentUri.custom[entry.customType] = entry.data;
          } else {
            this.manifest.custom = this.manifest.custom || {};
            this.manifest.custom[entry.customType] = entry.data;
          }
        }
      })[entry.type].call(self2);
    });
    return _this;
  }
  var _proto = Parser2.prototype;
  _proto.warnOnMissingAttributes_ = function warnOnMissingAttributes_(identifier, attributes, required) {
    var missing = [];
    required.forEach(function(key) {
      if (!attributes.hasOwnProperty(key)) {
        missing.push(key);
      }
    });
    if (missing.length) {
      this.trigger("warn", {
        message: identifier + " lacks required attribute(s): " + missing.join(", ")
      });
    }
  };
  _proto.push = function push2(chunk) {
    this.lineStream.push(chunk);
  };
  _proto.end = function end() {
    this.lineStream.push("\n");
    this.trigger("end");
  };
  _proto.addParser = function addParser(options) {
    this.parseStream.addParser(options);
  };
  _proto.addTagMapper = function addTagMapper(options) {
    this.parseStream.addTagMapper(options);
  };
  return Parser2;
}(Stream);

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/codecs.js
var import_window3 = __toESM(require_window());
var regexs = {
  // to determine mime types
  mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
  webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
  ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
  // to determine if a codec is audio or video
  video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
  audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
  text: /^(stpp.ttml.im1t)/,
  // mux.js support regex
  muxerVideo: /^(avc0?1)/,
  muxerAudio: /^(mp4a)/,
  // match nothing as muxer does not support text right now.
  // there cannot never be a character before the start of a string
  // so this matches nothing.
  muxerText: /a^/
};
var mediaTypes = ["video", "audio", "text"];
var upperMediaTypes = ["Video", "Audio", "Text"];
var translateLegacyCodec = function translateLegacyCodec2(codec) {
  if (!codec) {
    return codec;
  }
  return codec.replace(/avc1\.(\d+)\.(\d+)/i, function(orig, profile, avcLevel) {
    var profileHex = ("00" + Number(profile).toString(16)).slice(-2);
    var avcLevelHex = ("00" + Number(avcLevel).toString(16)).slice(-2);
    return "avc1." + profileHex + "00" + avcLevelHex;
  });
};
var parseCodecs = function parseCodecs2(codecString) {
  if (codecString === void 0) {
    codecString = "";
  }
  var codecs = codecString.split(",");
  var result = [];
  codecs.forEach(function(codec) {
    codec = codec.trim();
    var codecType;
    mediaTypes.forEach(function(name) {
      var match = regexs[name].exec(codec.toLowerCase());
      if (!match || match.length <= 1) {
        return;
      }
      codecType = name;
      var type2 = codec.substring(0, match[1].length);
      var details = codec.replace(type2, "");
      result.push({
        type: type2,
        details,
        mediaType: name
      });
    });
    if (!codecType) {
      result.push({
        type: codec,
        details: "",
        mediaType: "unknown"
      });
    }
  });
  return result;
};
var codecsFromDefault = function codecsFromDefault2(master, audioGroupId) {
  if (!master.mediaGroups.AUDIO || !audioGroupId) {
    return null;
  }
  var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
  if (!audioGroup) {
    return null;
  }
  for (var name in audioGroup) {
    var audioType = audioGroup[name];
    if (audioType.default && audioType.playlists) {
      return parseCodecs(audioType.playlists[0].attributes.CODECS);
    }
  }
  return null;
};
var isAudioCodec = function isAudioCodec2(codec) {
  if (codec === void 0) {
    codec = "";
  }
  return regexs.audio.test(codec.trim().toLowerCase());
};
var isTextCodec = function isTextCodec2(codec) {
  if (codec === void 0) {
    codec = "";
  }
  return regexs.text.test(codec.trim().toLowerCase());
};
var getMimeForCodec = function getMimeForCodec2(codecString) {
  if (!codecString || typeof codecString !== "string") {
    return;
  }
  var codecs = codecString.toLowerCase().split(",").map(function(c) {
    return translateLegacyCodec(c.trim());
  });
  var type2 = "video";
  if (codecs.length === 1 && isAudioCodec(codecs[0])) {
    type2 = "audio";
  } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
    type2 = "application";
  }
  var container = "mp4";
  if (codecs.every(function(c) {
    return regexs.mp4.test(c);
  })) {
    container = "mp4";
  } else if (codecs.every(function(c) {
    return regexs.webm.test(c);
  })) {
    container = "webm";
  } else if (codecs.every(function(c) {
    return regexs.ogg.test(c);
  })) {
    container = "ogg";
  }
  return type2 + "/" + container + ';codecs="' + codecString + '"';
};
var browserSupportsCodec = function browserSupportsCodec2(codecString) {
  if (codecString === void 0) {
    codecString = "";
  }
  return import_window3.default.MediaSource && import_window3.default.MediaSource.isTypeSupported && import_window3.default.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
};
var muxerSupportsCodec = function muxerSupportsCodec2(codecString) {
  if (codecString === void 0) {
    codecString = "";
  }
  return codecString.toLowerCase().split(",").every(function(codec) {
    codec = codec.trim();
    for (var i = 0; i < upperMediaTypes.length; i++) {
      var type2 = upperMediaTypes[i];
      if (regexs["muxer" + type2].test(codec)) {
        return true;
      }
    }
    return false;
  });
};
var DEFAULT_AUDIO_CODEC = "mp4a.40.2";
var DEFAULT_VIDEO_CODEC = "avc1.4d400d";

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/media-types.js
var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
var DASH_REGEX = /^application\/dash\+xml/i;
var simpleTypeFromSourceType = function simpleTypeFromSourceType2(type2) {
  if (MPEGURL_REGEX.test(type2)) {
    return "hls";
  }
  if (DASH_REGEX.test(type2)) {
    return "dash";
  }
  if (type2 === "application/vnd.videojs.vhs+json") {
    return "vhs-json";
  }
  return null;
};

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/byte-helpers.js
var import_window4 = __toESM(require_window());
var countBits = function countBits2(x) {
  return x.toString(2).length;
};
var countBytes = function countBytes2(x) {
  return Math.ceil(countBits(x) / 8);
};
var isArrayBufferView2 = function isArrayBufferView3(obj) {
  if (ArrayBuffer.isView === "function") {
    return ArrayBuffer.isView(obj);
  }
  return obj && obj.buffer instanceof ArrayBuffer;
};
var isTypedArray = function isTypedArray2(obj) {
  return isArrayBufferView2(obj);
};
var toUint82 = function toUint83(bytes) {
  if (bytes instanceof Uint8Array) {
    return bytes;
  }
  if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
    if (typeof bytes !== "number" || typeof bytes === "number" && bytes !== bytes) {
      bytes = 0;
    } else {
      bytes = [bytes];
    }
  }
  return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
};
var BigInt2 = import_window4.default.BigInt || Number;
var BYTE_TABLE = [BigInt2("0x1"), BigInt2("0x100"), BigInt2("0x10000"), BigInt2("0x1000000"), BigInt2("0x100000000"), BigInt2("0x10000000000"), BigInt2("0x1000000000000"), BigInt2("0x100000000000000"), BigInt2("0x10000000000000000")];
var ENDIANNESS = function() {
  var a = new Uint16Array([65484]);
  var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  if (b[0] === 255) {
    return "big";
  }
  if (b[0] === 204) {
    return "little";
  }
  return "unknown";
}();
var bytesToNumber = function bytesToNumber2(bytes, _temp) {
  var _ref = _temp === void 0 ? {} : _temp, _ref$signed = _ref.signed, signed = _ref$signed === void 0 ? false : _ref$signed, _ref$le = _ref.le, le = _ref$le === void 0 ? false : _ref$le;
  bytes = toUint82(bytes);
  var fn = le ? "reduce" : "reduceRight";
  var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
  var number = obj.call(bytes, function(total, byte, i) {
    var exponent = le ? i : Math.abs(i + 1 - bytes.length);
    return total + BigInt2(byte) * BYTE_TABLE[exponent];
  }, BigInt2(0));
  if (signed) {
    var max = BYTE_TABLE[bytes.length] / BigInt2(2) - BigInt2(1);
    number = BigInt2(number);
    if (number > max) {
      number -= max;
      number -= max;
      number -= BigInt2(2);
    }
  }
  return Number(number);
};
var numberToBytes = function numberToBytes2(number, _temp2) {
  var _ref2 = _temp2 === void 0 ? {} : _temp2, _ref2$le = _ref2.le, le = _ref2$le === void 0 ? false : _ref2$le;
  if (typeof number !== "bigint" && typeof number !== "number" || typeof number === "number" && number !== number) {
    number = 0;
  }
  number = BigInt2(number);
  var byteCount = countBytes(number);
  var bytes = new Uint8Array(new ArrayBuffer(byteCount));
  for (var i = 0; i < byteCount; i++) {
    var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
    bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt2(255));
    if (number < 0) {
      bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
      bytes[byteIndex] -= i === 0 ? 1 : 2;
    }
  }
  return bytes;
};
var bytesToString = function bytesToString2(bytes) {
  if (!bytes) {
    return "";
  }
  bytes = Array.prototype.slice.call(bytes);
  var string = String.fromCharCode.apply(null, toUint82(bytes));
  try {
    return decodeURIComponent(escape(string));
  } catch (e) {
  }
  return string;
};
var stringToBytes = function stringToBytes2(string, stringIsBytes) {
  if (typeof string !== "string" && string && typeof string.toString === "function") {
    string = string.toString();
  }
  if (typeof string !== "string") {
    return new Uint8Array();
  }
  if (!stringIsBytes) {
    string = unescape(encodeURIComponent(string));
  }
  var view2 = new Uint8Array(string.length);
  for (var i = 0; i < string.length; i++) {
    view2[i] = string.charCodeAt(i);
  }
  return view2;
};
var concatTypedArrays = function concatTypedArrays2() {
  for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
    buffers[_key] = arguments[_key];
  }
  buffers = buffers.filter(function(b) {
    return b && (b.byteLength || b.length) && typeof b !== "string";
  });
  if (buffers.length <= 1) {
    return toUint82(buffers[0]);
  }
  var totalLen = buffers.reduce(function(total, buf, i) {
    return total + (buf.byteLength || buf.length);
  }, 0);
  var tempBuffer = new Uint8Array(totalLen);
  var offset = 0;
  buffers.forEach(function(buf) {
    buf = toUint82(buf);
    tempBuffer.set(buf, offset);
    offset += buf.byteLength;
  });
  return tempBuffer;
};
var bytesMatch = function bytesMatch2(a, b, _temp3) {
  var _ref3 = _temp3 === void 0 ? {} : _temp3, _ref3$offset = _ref3.offset, offset = _ref3$offset === void 0 ? 0 : _ref3$offset, _ref3$mask = _ref3.mask, mask = _ref3$mask === void 0 ? [] : _ref3$mask;
  a = toUint82(a);
  b = toUint82(b);
  var fn = b.every ? b.every : Array.prototype.every;
  return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
  fn.call(b, function(bByte, i) {
    var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
    return bByte === aByte;
  });
};

// node_modules/.pnpm/mpd-parser@0.21.1/node_modules/mpd-parser/dist/mpd-parser.es.js
var import_window5 = __toESM(require_window());

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/media-groups.js
var forEachMediaGroup = function forEachMediaGroup2(master, groups, callback2) {
  groups.forEach(function(mediaType) {
    for (var groupKey in master.mediaGroups[mediaType]) {
      for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
        var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
        callback2(mediaProperties, mediaType, groupKey, labelKey);
      }
    }
  });
};

// node_modules/.pnpm/mpd-parser@0.21.1/node_modules/mpd-parser/dist/mpd-parser.es.js
var import_xmldom = __toESM(require_lib2());
var isObject = function isObject2(obj) {
  return !!obj && typeof obj === "object";
};
var merge = function merge2() {
  for (var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++) {
    objects[_key] = arguments[_key];
  }
  return objects.reduce(function(result, source) {
    if (typeof source !== "object") {
      return result;
    }
    Object.keys(source).forEach(function(key) {
      if (Array.isArray(result[key]) && Array.isArray(source[key])) {
        result[key] = result[key].concat(source[key]);
      } else if (isObject(result[key]) && isObject(source[key])) {
        result[key] = merge2(result[key], source[key]);
      } else {
        result[key] = source[key];
      }
    });
    return result;
  }, {});
};
var values = function values2(o) {
  return Object.keys(o).map(function(k) {
    return o[k];
  });
};
var range = function range2(start2, end) {
  var result = [];
  for (var i = start2; i < end; i++) {
    result.push(i);
  }
  return result;
};
var flatten = function flatten2(lists) {
  return lists.reduce(function(x, y) {
    return x.concat(y);
  }, []);
};
var from = function from2(list) {
  if (!list.length) {
    return [];
  }
  var result = [];
  for (var i = 0; i < list.length; i++) {
    result.push(list[i]);
  }
  return result;
};
var findIndexes = function findIndexes2(l, key) {
  return l.reduce(function(a, e, i) {
    if (e[key]) {
      a.push(i);
    }
    return a;
  }, []);
};
var findIndex = function findIndex2(list, matchingFunction) {
  for (var i = 0; i < list.length; i++) {
    if (matchingFunction(list[i])) {
      return i;
    }
  }
  return -1;
};
var union = function union2(lists, keyFunction) {
  return values(lists.reduce(function(acc, list) {
    list.forEach(function(el) {
      acc[keyFunction(el)] = el;
    });
    return acc;
  }, {}));
};
var errors = {
  INVALID_NUMBER_OF_PERIOD: "INVALID_NUMBER_OF_PERIOD",
  DASH_EMPTY_MANIFEST: "DASH_EMPTY_MANIFEST",
  DASH_INVALID_XML: "DASH_INVALID_XML",
  NO_BASE_URL: "NO_BASE_URL",
  MISSING_SEGMENT_INFORMATION: "MISSING_SEGMENT_INFORMATION",
  SEGMENT_TIME_UNSPECIFIED: "SEGMENT_TIME_UNSPECIFIED",
  UNSUPPORTED_UTC_TIMING_SCHEME: "UNSUPPORTED_UTC_TIMING_SCHEME"
};
var urlTypeToSegment = function urlTypeToSegment2(_ref) {
  var _ref$baseUrl = _ref.baseUrl, baseUrl = _ref$baseUrl === void 0 ? "" : _ref$baseUrl, _ref$source = _ref.source, source = _ref$source === void 0 ? "" : _ref$source, _ref$range = _ref.range, range3 = _ref$range === void 0 ? "" : _ref$range, _ref$indexRange = _ref.indexRange, indexRange = _ref$indexRange === void 0 ? "" : _ref$indexRange;
  var segment = {
    uri: source,
    resolvedUri: resolve_url_default(baseUrl || "", source)
  };
  if (range3 || indexRange) {
    var rangeStr = range3 ? range3 : indexRange;
    var ranges = rangeStr.split("-");
    var startRange = import_window5.default.BigInt ? import_window5.default.BigInt(ranges[0]) : parseInt(ranges[0], 10);
    var endRange = import_window5.default.BigInt ? import_window5.default.BigInt(ranges[1]) : parseInt(ranges[1], 10);
    if (startRange < Number.MAX_SAFE_INTEGER && typeof startRange === "bigint") {
      startRange = Number(startRange);
    }
    if (endRange < Number.MAX_SAFE_INTEGER && typeof endRange === "bigint") {
      endRange = Number(endRange);
    }
    var length;
    if (typeof endRange === "bigint" || typeof startRange === "bigint") {
      length = import_window5.default.BigInt(endRange) - import_window5.default.BigInt(startRange) + import_window5.default.BigInt(1);
    } else {
      length = endRange - startRange + 1;
    }
    if (typeof length === "bigint" && length < Number.MAX_SAFE_INTEGER) {
      length = Number(length);
    }
    segment.byterange = {
      length,
      offset: startRange
    };
  }
  return segment;
};
var byteRangeToString = function byteRangeToString2(byterange) {
  var endRange;
  if (typeof byterange.offset === "bigint" || typeof byterange.length === "bigint") {
    endRange = import_window5.default.BigInt(byterange.offset) + import_window5.default.BigInt(byterange.length) - import_window5.default.BigInt(1);
  } else {
    endRange = byterange.offset + byterange.length - 1;
  }
  return byterange.offset + "-" + endRange;
};
var parseEndNumber = function parseEndNumber2(endNumber) {
  if (endNumber && typeof endNumber !== "number") {
    endNumber = parseInt(endNumber, 10);
  }
  if (isNaN(endNumber)) {
    return null;
  }
  return endNumber;
};
var segmentRange = {
  /**
   * Returns the entire range of available segments for a static MPD
   *
   * @param {Object} attributes
   *        Inheritied MPD attributes
   * @return {{ start: number, end: number }}
   *         The start and end numbers for available segments
   */
  static: function _static(attributes) {
    var duration5 = attributes.duration, _attributes$timescale = attributes.timescale, timescale2 = _attributes$timescale === void 0 ? 1 : _attributes$timescale, sourceDuration = attributes.sourceDuration, periodDuration = attributes.periodDuration;
    var endNumber = parseEndNumber(attributes.endNumber);
    var segmentDuration = duration5 / timescale2;
    if (typeof endNumber === "number") {
      return {
        start: 0,
        end: endNumber
      };
    }
    if (typeof periodDuration === "number") {
      return {
        start: 0,
        end: periodDuration / segmentDuration
      };
    }
    return {
      start: 0,
      end: sourceDuration / segmentDuration
    };
  },
  /**
   * Returns the current live window range of available segments for a dynamic MPD
   *
   * @param {Object} attributes
   *        Inheritied MPD attributes
   * @return {{ start: number, end: number }}
   *         The start and end numbers for available segments
   */
  dynamic: function dynamic(attributes) {
    var NOW = attributes.NOW, clientOffset = attributes.clientOffset, availabilityStartTime2 = attributes.availabilityStartTime, _attributes$timescale2 = attributes.timescale, timescale2 = _attributes$timescale2 === void 0 ? 1 : _attributes$timescale2, duration5 = attributes.duration, _attributes$periodSta = attributes.periodStart, periodStart = _attributes$periodSta === void 0 ? 0 : _attributes$periodSta, _attributes$minimumUp = attributes.minimumUpdatePeriod, minimumUpdatePeriod2 = _attributes$minimumUp === void 0 ? 0 : _attributes$minimumUp, _attributes$timeShift = attributes.timeShiftBufferDepth, timeShiftBufferDepth2 = _attributes$timeShift === void 0 ? Infinity : _attributes$timeShift;
    var endNumber = parseEndNumber(attributes.endNumber);
    var now2 = (NOW + clientOffset) / 1e3;
    var periodStartWC = availabilityStartTime2 + periodStart;
    var periodEndWC = now2 + minimumUpdatePeriod2;
    var periodDuration = periodEndWC - periodStartWC;
    var segmentCount = Math.ceil(periodDuration * timescale2 / duration5);
    var availableStart = Math.floor((now2 - periodStartWC - timeShiftBufferDepth2) * timescale2 / duration5);
    var availableEnd = Math.floor((now2 - periodStartWC) * timescale2 / duration5);
    return {
      start: Math.max(0, availableStart),
      end: typeof endNumber === "number" ? endNumber : Math.min(segmentCount, availableEnd)
    };
  }
};
var toSegments = function toSegments2(attributes) {
  return function(number) {
    var duration5 = attributes.duration, _attributes$timescale3 = attributes.timescale, timescale2 = _attributes$timescale3 === void 0 ? 1 : _attributes$timescale3, periodStart = attributes.periodStart, _attributes$startNumb = attributes.startNumber, startNumber2 = _attributes$startNumb === void 0 ? 1 : _attributes$startNumb;
    return {
      number: startNumber2 + number,
      duration: duration5 / timescale2,
      timeline: periodStart,
      time: number * duration5
    };
  };
};
var parseByDuration = function parseByDuration2(attributes) {
  var type2 = attributes.type, duration5 = attributes.duration, _attributes$timescale4 = attributes.timescale, timescale2 = _attributes$timescale4 === void 0 ? 1 : _attributes$timescale4, periodDuration = attributes.periodDuration, sourceDuration = attributes.sourceDuration;
  var _segmentRange$type = segmentRange[type2](attributes), start2 = _segmentRange$type.start, end = _segmentRange$type.end;
  var segments = range(start2, end).map(toSegments(attributes));
  if (type2 === "static") {
    var index = segments.length - 1;
    var sectionDuration = typeof periodDuration === "number" ? periodDuration : sourceDuration;
    segments[index].duration = sectionDuration - duration5 / timescale2 * index;
  }
  return segments;
};
var segmentsFromBase = function segmentsFromBase2(attributes) {
  var baseUrl = attributes.baseUrl, _attributes$initializ = attributes.initialization, initialization = _attributes$initializ === void 0 ? {} : _attributes$initializ, sourceDuration = attributes.sourceDuration, _attributes$indexRang = attributes.indexRange, indexRange = _attributes$indexRang === void 0 ? "" : _attributes$indexRang, periodStart = attributes.periodStart, presentationTime = attributes.presentationTime, _attributes$number = attributes.number, number = _attributes$number === void 0 ? 0 : _attributes$number, duration5 = attributes.duration;
  if (!baseUrl) {
    throw new Error(errors.NO_BASE_URL);
  }
  var initSegment = urlTypeToSegment({
    baseUrl,
    source: initialization.sourceURL,
    range: initialization.range
  });
  var segment = urlTypeToSegment({
    baseUrl,
    source: baseUrl,
    indexRange
  });
  segment.map = initSegment;
  if (duration5) {
    var segmentTimeInfo = parseByDuration(attributes);
    if (segmentTimeInfo.length) {
      segment.duration = segmentTimeInfo[0].duration;
      segment.timeline = segmentTimeInfo[0].timeline;
    }
  } else if (sourceDuration) {
    segment.duration = sourceDuration;
    segment.timeline = periodStart;
  }
  segment.presentationTime = presentationTime || periodStart;
  segment.number = number;
  return [segment];
};
var addSidxSegmentsToPlaylist$1 = function addSidxSegmentsToPlaylist(playlist, sidx, baseUrl) {
  var initSegment = playlist.sidx.map ? playlist.sidx.map : null;
  var sourceDuration = playlist.sidx.duration;
  var timeline = playlist.timeline || 0;
  var sidxByteRange = playlist.sidx.byterange;
  var sidxEnd = sidxByteRange.offset + sidxByteRange.length;
  var timescale2 = sidx.timescale;
  var mediaReferences = sidx.references.filter(function(r2) {
    return r2.referenceType !== 1;
  });
  var segments = [];
  var type2 = playlist.endList ? "static" : "dynamic";
  var periodStart = playlist.sidx.timeline;
  var presentationTime = periodStart;
  var number = playlist.mediaSequence || 0;
  var startIndex;
  if (typeof sidx.firstOffset === "bigint") {
    startIndex = import_window5.default.BigInt(sidxEnd) + sidx.firstOffset;
  } else {
    startIndex = sidxEnd + sidx.firstOffset;
  }
  for (var i = 0; i < mediaReferences.length; i++) {
    var reference = sidx.references[i];
    var size = reference.referencedSize;
    var duration5 = reference.subsegmentDuration;
    var endIndex = void 0;
    if (typeof startIndex === "bigint") {
      endIndex = startIndex + import_window5.default.BigInt(size) - import_window5.default.BigInt(1);
    } else {
      endIndex = startIndex + size - 1;
    }
    var indexRange = startIndex + "-" + endIndex;
    var attributes = {
      baseUrl,
      timescale: timescale2,
      timeline,
      periodStart,
      presentationTime,
      number,
      duration: duration5,
      sourceDuration,
      indexRange,
      type: type2
    };
    var segment = segmentsFromBase(attributes)[0];
    if (initSegment) {
      segment.map = initSegment;
    }
    segments.push(segment);
    if (typeof startIndex === "bigint") {
      startIndex += import_window5.default.BigInt(size);
    } else {
      startIndex += size;
    }
    presentationTime += duration5 / timescale2;
    number++;
  }
  playlist.segments = segments;
  return playlist;
};
var SUPPORTED_MEDIA_TYPES = ["AUDIO", "SUBTITLES"];
var TIME_FUDGE = 1 / 60;
var getUniqueTimelineStarts = function getUniqueTimelineStarts2(timelineStarts) {
  return union(timelineStarts, function(_ref) {
    var timeline = _ref.timeline;
    return timeline;
  }).sort(function(a, b) {
    return a.timeline > b.timeline ? 1 : -1;
  });
};
var findPlaylistWithName = function findPlaylistWithName2(playlists, name) {
  for (var i = 0; i < playlists.length; i++) {
    if (playlists[i].attributes.NAME === name) {
      return playlists[i];
    }
  }
  return null;
};
var getMediaGroupPlaylists = function getMediaGroupPlaylists2(manifest) {
  var mediaGroupPlaylists = [];
  forEachMediaGroup(manifest, SUPPORTED_MEDIA_TYPES, function(properties, type2, group, label) {
    mediaGroupPlaylists = mediaGroupPlaylists.concat(properties.playlists || []);
  });
  return mediaGroupPlaylists;
};
var updateMediaSequenceForPlaylist = function updateMediaSequenceForPlaylist2(_ref2) {
  var playlist = _ref2.playlist, mediaSequence = _ref2.mediaSequence;
  playlist.mediaSequence = mediaSequence;
  playlist.segments.forEach(function(segment, index) {
    segment.number = playlist.mediaSequence + index;
  });
};
var updateSequenceNumbers = function updateSequenceNumbers2(_ref3) {
  var oldPlaylists = _ref3.oldPlaylists, newPlaylists = _ref3.newPlaylists, timelineStarts = _ref3.timelineStarts;
  newPlaylists.forEach(function(playlist) {
    playlist.discontinuitySequence = findIndex(timelineStarts, function(_ref4) {
      var timeline = _ref4.timeline;
      return timeline === playlist.timeline;
    });
    var oldPlaylist = findPlaylistWithName(oldPlaylists, playlist.attributes.NAME);
    if (!oldPlaylist) {
      return;
    }
    if (playlist.sidx) {
      return;
    }
    var firstNewSegment = playlist.segments[0];
    var oldMatchingSegmentIndex = findIndex(oldPlaylist.segments, function(oldSegment) {
      return Math.abs(oldSegment.presentationTime - firstNewSegment.presentationTime) < TIME_FUDGE;
    });
    if (oldMatchingSegmentIndex === -1) {
      updateMediaSequenceForPlaylist({
        playlist,
        mediaSequence: oldPlaylist.mediaSequence + oldPlaylist.segments.length
      });
      playlist.segments[0].discontinuity = true;
      playlist.discontinuityStarts.unshift(0);
      if (!oldPlaylist.segments.length && playlist.timeline > oldPlaylist.timeline || oldPlaylist.segments.length && playlist.timeline > oldPlaylist.segments[oldPlaylist.segments.length - 1].timeline) {
        playlist.discontinuitySequence--;
      }
      return;
    }
    var oldMatchingSegment = oldPlaylist.segments[oldMatchingSegmentIndex];
    if (oldMatchingSegment.discontinuity && !firstNewSegment.discontinuity) {
      firstNewSegment.discontinuity = true;
      playlist.discontinuityStarts.unshift(0);
      playlist.discontinuitySequence--;
    }
    updateMediaSequenceForPlaylist({
      playlist,
      mediaSequence: oldPlaylist.segments[oldMatchingSegmentIndex].number
    });
  });
};
var positionManifestOnTimeline = function positionManifestOnTimeline2(_ref5) {
  var oldManifest = _ref5.oldManifest, newManifest = _ref5.newManifest;
  var oldPlaylists = oldManifest.playlists.concat(getMediaGroupPlaylists(oldManifest));
  var newPlaylists = newManifest.playlists.concat(getMediaGroupPlaylists(newManifest));
  newManifest.timelineStarts = getUniqueTimelineStarts([oldManifest.timelineStarts, newManifest.timelineStarts]);
  updateSequenceNumbers({
    oldPlaylists,
    newPlaylists,
    timelineStarts: newManifest.timelineStarts
  });
  return newManifest;
};
var generateSidxKey = function generateSidxKey2(sidx) {
  return sidx && sidx.uri + "-" + byteRangeToString(sidx.byterange);
};
var mergeDiscontiguousPlaylists = function mergeDiscontiguousPlaylists2(playlists) {
  var mergedPlaylists = values(playlists.reduce(function(acc, playlist) {
    var name = playlist.attributes.id + (playlist.attributes.lang || "");
    if (!acc[name]) {
      acc[name] = playlist;
      acc[name].attributes.timelineStarts = [];
    } else {
      if (playlist.segments) {
        var _acc$name$segments;
        if (playlist.segments[0]) {
          playlist.segments[0].discontinuity = true;
        }
        (_acc$name$segments = acc[name].segments).push.apply(_acc$name$segments, playlist.segments);
      }
      if (playlist.attributes.contentProtection) {
        acc[name].attributes.contentProtection = playlist.attributes.contentProtection;
      }
    }
    acc[name].attributes.timelineStarts.push({
      // Although they represent the same number, it's important to have both to make it
      // compatible with HLS potentially having a similar attribute.
      start: playlist.attributes.periodStart,
      timeline: playlist.attributes.periodStart
    });
    return acc;
  }, {}));
  return mergedPlaylists.map(function(playlist) {
    playlist.discontinuityStarts = findIndexes(playlist.segments || [], "discontinuity");
    return playlist;
  });
};
var addSidxSegmentsToPlaylist2 = function addSidxSegmentsToPlaylist3(playlist, sidxMapping) {
  var sidxKey = generateSidxKey(playlist.sidx);
  var sidxMatch = sidxKey && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx;
  if (sidxMatch) {
    addSidxSegmentsToPlaylist$1(playlist, sidxMatch, playlist.sidx.resolvedUri);
  }
  return playlist;
};
var addSidxSegmentsToPlaylists = function addSidxSegmentsToPlaylists2(playlists, sidxMapping) {
  if (sidxMapping === void 0) {
    sidxMapping = {};
  }
  if (!Object.keys(sidxMapping).length) {
    return playlists;
  }
  for (var i in playlists) {
    playlists[i] = addSidxSegmentsToPlaylist2(playlists[i], sidxMapping);
  }
  return playlists;
};
var formatAudioPlaylist = function formatAudioPlaylist2(_ref, isAudioOnly3) {
  var _attributes;
  var attributes = _ref.attributes, segments = _ref.segments, sidx = _ref.sidx, mediaSequence = _ref.mediaSequence, discontinuitySequence = _ref.discontinuitySequence, discontinuityStarts = _ref.discontinuityStarts;
  var playlist = {
    attributes: (_attributes = {
      NAME: attributes.id,
      BANDWIDTH: attributes.bandwidth,
      CODECS: attributes.codecs
    }, _attributes["PROGRAM-ID"] = 1, _attributes),
    uri: "",
    endList: attributes.type === "static",
    timeline: attributes.periodStart,
    resolvedUri: "",
    targetDuration: attributes.duration,
    discontinuitySequence,
    discontinuityStarts,
    timelineStarts: attributes.timelineStarts,
    mediaSequence,
    segments
  };
  if (attributes.contentProtection) {
    playlist.contentProtection = attributes.contentProtection;
  }
  if (sidx) {
    playlist.sidx = sidx;
  }
  if (isAudioOnly3) {
    playlist.attributes.AUDIO = "audio";
    playlist.attributes.SUBTITLES = "subs";
  }
  return playlist;
};
var formatVttPlaylist = function formatVttPlaylist2(_ref2) {
  var _m3u8Attributes;
  var attributes = _ref2.attributes, segments = _ref2.segments, mediaSequence = _ref2.mediaSequence, discontinuityStarts = _ref2.discontinuityStarts, discontinuitySequence = _ref2.discontinuitySequence;
  if (typeof segments === "undefined") {
    segments = [{
      uri: attributes.baseUrl,
      timeline: attributes.periodStart,
      resolvedUri: attributes.baseUrl || "",
      duration: attributes.sourceDuration,
      number: 0
    }];
    attributes.duration = attributes.sourceDuration;
  }
  var m3u8Attributes = (_m3u8Attributes = {
    NAME: attributes.id,
    BANDWIDTH: attributes.bandwidth
  }, _m3u8Attributes["PROGRAM-ID"] = 1, _m3u8Attributes);
  if (attributes.codecs) {
    m3u8Attributes.CODECS = attributes.codecs;
  }
  return {
    attributes: m3u8Attributes,
    uri: "",
    endList: attributes.type === "static",
    timeline: attributes.periodStart,
    resolvedUri: attributes.baseUrl || "",
    targetDuration: attributes.duration,
    timelineStarts: attributes.timelineStarts,
    discontinuityStarts,
    discontinuitySequence,
    mediaSequence,
    segments
  };
};
var organizeAudioPlaylists = function organizeAudioPlaylists2(playlists, sidxMapping, isAudioOnly3) {
  if (sidxMapping === void 0) {
    sidxMapping = {};
  }
  if (isAudioOnly3 === void 0) {
    isAudioOnly3 = false;
  }
  var mainPlaylist;
  var formattedPlaylists = playlists.reduce(function(a, playlist) {
    var role = playlist.attributes.role && playlist.attributes.role.value || "";
    var language = playlist.attributes.lang || "";
    var label = playlist.attributes.label || "main";
    if (language && !playlist.attributes.label) {
      var roleLabel = role ? " (" + role + ")" : "";
      label = "" + playlist.attributes.lang + roleLabel;
    }
    if (!a[label]) {
      a[label] = {
        language,
        autoselect: true,
        default: role === "main",
        playlists: [],
        uri: ""
      };
    }
    var formatted = addSidxSegmentsToPlaylist2(formatAudioPlaylist(playlist, isAudioOnly3), sidxMapping);
    a[label].playlists.push(formatted);
    if (typeof mainPlaylist === "undefined" && role === "main") {
      mainPlaylist = playlist;
      mainPlaylist.default = true;
    }
    return a;
  }, {});
  if (!mainPlaylist) {
    var firstLabel = Object.keys(formattedPlaylists)[0];
    formattedPlaylists[firstLabel].default = true;
  }
  return formattedPlaylists;
};
var organizeVttPlaylists = function organizeVttPlaylists2(playlists, sidxMapping) {
  if (sidxMapping === void 0) {
    sidxMapping = {};
  }
  return playlists.reduce(function(a, playlist) {
    var label = playlist.attributes.lang || "text";
    if (!a[label]) {
      a[label] = {
        language: label,
        default: false,
        autoselect: false,
        playlists: [],
        uri: ""
      };
    }
    a[label].playlists.push(addSidxSegmentsToPlaylist2(formatVttPlaylist(playlist), sidxMapping));
    return a;
  }, {});
};
var organizeCaptionServices = function organizeCaptionServices2(captionServices) {
  return captionServices.reduce(function(svcObj, svc) {
    if (!svc) {
      return svcObj;
    }
    svc.forEach(function(service) {
      var channel = service.channel, language = service.language;
      svcObj[language] = {
        autoselect: false,
        default: false,
        instreamId: channel,
        language
      };
      if (service.hasOwnProperty("aspectRatio")) {
        svcObj[language].aspectRatio = service.aspectRatio;
      }
      if (service.hasOwnProperty("easyReader")) {
        svcObj[language].easyReader = service.easyReader;
      }
      if (service.hasOwnProperty("3D")) {
        svcObj[language]["3D"] = service["3D"];
      }
    });
    return svcObj;
  }, {});
};
var formatVideoPlaylist = function formatVideoPlaylist2(_ref3) {
  var _attributes2;
  var attributes = _ref3.attributes, segments = _ref3.segments, sidx = _ref3.sidx, discontinuityStarts = _ref3.discontinuityStarts;
  var playlist = {
    attributes: (_attributes2 = {
      NAME: attributes.id,
      AUDIO: "audio",
      SUBTITLES: "subs",
      RESOLUTION: {
        width: attributes.width,
        height: attributes.height
      },
      CODECS: attributes.codecs,
      BANDWIDTH: attributes.bandwidth
    }, _attributes2["PROGRAM-ID"] = 1, _attributes2),
    uri: "",
    endList: attributes.type === "static",
    timeline: attributes.periodStart,
    resolvedUri: "",
    targetDuration: attributes.duration,
    discontinuityStarts,
    timelineStarts: attributes.timelineStarts,
    segments
  };
  if (attributes.contentProtection) {
    playlist.contentProtection = attributes.contentProtection;
  }
  if (sidx) {
    playlist.sidx = sidx;
  }
  return playlist;
};
var videoOnly = function videoOnly2(_ref4) {
  var attributes = _ref4.attributes;
  return attributes.mimeType === "video/mp4" || attributes.mimeType === "video/webm" || attributes.contentType === "video";
};
var audioOnly = function audioOnly2(_ref5) {
  var attributes = _ref5.attributes;
  return attributes.mimeType === "audio/mp4" || attributes.mimeType === "audio/webm" || attributes.contentType === "audio";
};
var vttOnly = function vttOnly2(_ref6) {
  var attributes = _ref6.attributes;
  return attributes.mimeType === "text/vtt" || attributes.contentType === "text";
};
var addMediaSequenceValues = function addMediaSequenceValues2(playlists, timelineStarts) {
  playlists.forEach(function(playlist) {
    playlist.mediaSequence = 0;
    playlist.discontinuitySequence = findIndex(timelineStarts, function(_ref7) {
      var timeline = _ref7.timeline;
      return timeline === playlist.timeline;
    });
    if (!playlist.segments) {
      return;
    }
    playlist.segments.forEach(function(segment, index) {
      segment.number = index;
    });
  });
};
var flattenMediaGroupPlaylists = function flattenMediaGroupPlaylists2(mediaGroupObject) {
  if (!mediaGroupObject) {
    return [];
  }
  return Object.keys(mediaGroupObject).reduce(function(acc, label) {
    var labelContents = mediaGroupObject[label];
    return acc.concat(labelContents.playlists);
  }, []);
};
var toM3u8 = function toM3u82(_ref8) {
  var _mediaGroups;
  var dashPlaylists = _ref8.dashPlaylists, locations = _ref8.locations, _ref8$sidxMapping = _ref8.sidxMapping, sidxMapping = _ref8$sidxMapping === void 0 ? {} : _ref8$sidxMapping, previousManifest = _ref8.previousManifest;
  if (!dashPlaylists.length) {
    return {};
  }
  var _dashPlaylists$0$attr = dashPlaylists[0].attributes, duration5 = _dashPlaylists$0$attr.sourceDuration, type2 = _dashPlaylists$0$attr.type, suggestedPresentationDelay2 = _dashPlaylists$0$attr.suggestedPresentationDelay, minimumUpdatePeriod2 = _dashPlaylists$0$attr.minimumUpdatePeriod;
  var videoPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);
  var audioPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));
  var vttPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(vttOnly));
  var captions = dashPlaylists.map(function(playlist) {
    return playlist.attributes.captionServices;
  }).filter(Boolean);
  var manifest = {
    allowCache: true,
    discontinuityStarts: [],
    segments: [],
    endList: true,
    mediaGroups: (_mediaGroups = {
      AUDIO: {},
      VIDEO: {}
    }, _mediaGroups["CLOSED-CAPTIONS"] = {}, _mediaGroups.SUBTITLES = {}, _mediaGroups),
    uri: "",
    duration: duration5,
    playlists: addSidxSegmentsToPlaylists(videoPlaylists, sidxMapping)
  };
  if (minimumUpdatePeriod2 >= 0) {
    manifest.minimumUpdatePeriod = minimumUpdatePeriod2 * 1e3;
  }
  if (locations) {
    manifest.locations = locations;
  }
  if (type2 === "dynamic") {
    manifest.suggestedPresentationDelay = suggestedPresentationDelay2;
  }
  var isAudioOnly3 = manifest.playlists.length === 0;
  var organizedAudioGroup = audioPlaylists.length ? organizeAudioPlaylists(audioPlaylists, sidxMapping, isAudioOnly3) : null;
  var organizedVttGroup = vttPlaylists.length ? organizeVttPlaylists(vttPlaylists, sidxMapping) : null;
  var formattedPlaylists = videoPlaylists.concat(flattenMediaGroupPlaylists(organizedAudioGroup), flattenMediaGroupPlaylists(organizedVttGroup));
  var playlistTimelineStarts = formattedPlaylists.map(function(_ref9) {
    var timelineStarts = _ref9.timelineStarts;
    return timelineStarts;
  });
  manifest.timelineStarts = getUniqueTimelineStarts(playlistTimelineStarts);
  addMediaSequenceValues(formattedPlaylists, manifest.timelineStarts);
  if (organizedAudioGroup) {
    manifest.mediaGroups.AUDIO.audio = organizedAudioGroup;
  }
  if (organizedVttGroup) {
    manifest.mediaGroups.SUBTITLES.subs = organizedVttGroup;
  }
  if (captions.length) {
    manifest.mediaGroups["CLOSED-CAPTIONS"].cc = organizeCaptionServices(captions);
  }
  if (previousManifest) {
    return positionManifestOnTimeline({
      oldManifest: previousManifest,
      newManifest: manifest
    });
  }
  return manifest;
};
var getLiveRValue = function getLiveRValue2(attributes, time, duration5) {
  var NOW = attributes.NOW, clientOffset = attributes.clientOffset, availabilityStartTime2 = attributes.availabilityStartTime, _attributes$timescale = attributes.timescale, timescale2 = _attributes$timescale === void 0 ? 1 : _attributes$timescale, _attributes$periodSta = attributes.periodStart, periodStart = _attributes$periodSta === void 0 ? 0 : _attributes$periodSta, _attributes$minimumUp = attributes.minimumUpdatePeriod, minimumUpdatePeriod2 = _attributes$minimumUp === void 0 ? 0 : _attributes$minimumUp;
  var now2 = (NOW + clientOffset) / 1e3;
  var periodStartWC = availabilityStartTime2 + periodStart;
  var periodEndWC = now2 + minimumUpdatePeriod2;
  var periodDuration = periodEndWC - periodStartWC;
  return Math.ceil((periodDuration * timescale2 - time) / duration5);
};
var parseByTimeline = function parseByTimeline2(attributes, segmentTimeline) {
  var type2 = attributes.type, _attributes$minimumUp2 = attributes.minimumUpdatePeriod, minimumUpdatePeriod2 = _attributes$minimumUp2 === void 0 ? 0 : _attributes$minimumUp2, _attributes$media = attributes.media, media = _attributes$media === void 0 ? "" : _attributes$media, sourceDuration = attributes.sourceDuration, _attributes$timescale2 = attributes.timescale, timescale2 = _attributes$timescale2 === void 0 ? 1 : _attributes$timescale2, _attributes$startNumb = attributes.startNumber, startNumber2 = _attributes$startNumb === void 0 ? 1 : _attributes$startNumb, timeline = attributes.periodStart;
  var segments = [];
  var time = -1;
  for (var sIndex = 0; sIndex < segmentTimeline.length; sIndex++) {
    var S = segmentTimeline[sIndex];
    var duration5 = S.d;
    var repeat = S.r || 0;
    var segmentTime = S.t || 0;
    if (time < 0) {
      time = segmentTime;
    }
    if (segmentTime && segmentTime > time) {
      time = segmentTime;
    }
    var count = void 0;
    if (repeat < 0) {
      var nextS = sIndex + 1;
      if (nextS === segmentTimeline.length) {
        if (type2 === "dynamic" && minimumUpdatePeriod2 > 0 && media.indexOf("$Number$") > 0) {
          count = getLiveRValue(attributes, time, duration5);
        } else {
          count = (sourceDuration * timescale2 - time) / duration5;
        }
      } else {
        count = (segmentTimeline[nextS].t - time) / duration5;
      }
    } else {
      count = repeat + 1;
    }
    var end = startNumber2 + segments.length + count;
    var number = startNumber2 + segments.length;
    while (number < end) {
      segments.push({
        number,
        duration: duration5 / timescale2,
        time,
        timeline
      });
      time += duration5;
      number++;
    }
  }
  return segments;
};
var identifierPattern = /\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g;
var identifierReplacement = function identifierReplacement2(values3) {
  return function(match, identifier, format2, width2) {
    if (match === "$$") {
      return "$";
    }
    if (typeof values3[identifier] === "undefined") {
      return match;
    }
    var value = "" + values3[identifier];
    if (identifier === "RepresentationID") {
      return value;
    }
    if (!format2) {
      width2 = 1;
    } else {
      width2 = parseInt(width2, 10);
    }
    if (value.length >= width2) {
      return value;
    }
    return "" + new Array(width2 - value.length + 1).join("0") + value;
  };
};
var constructTemplateUrl = function constructTemplateUrl2(url, values3) {
  return url.replace(identifierPattern, identifierReplacement(values3));
};
var parseTemplateInfo = function parseTemplateInfo2(attributes, segmentTimeline) {
  if (!attributes.duration && !segmentTimeline) {
    return [{
      number: attributes.startNumber || 1,
      duration: attributes.sourceDuration,
      time: 0,
      timeline: attributes.periodStart
    }];
  }
  if (attributes.duration) {
    return parseByDuration(attributes);
  }
  return parseByTimeline(attributes, segmentTimeline);
};
var segmentsFromTemplate = function segmentsFromTemplate2(attributes, segmentTimeline) {
  var templateValues = {
    RepresentationID: attributes.id,
    Bandwidth: attributes.bandwidth || 0
  };
  var _attributes$initializ = attributes.initialization, initialization = _attributes$initializ === void 0 ? {
    sourceURL: "",
    range: ""
  } : _attributes$initializ;
  var mapSegment = urlTypeToSegment({
    baseUrl: attributes.baseUrl,
    source: constructTemplateUrl(initialization.sourceURL, templateValues),
    range: initialization.range
  });
  var segments = parseTemplateInfo(attributes, segmentTimeline);
  return segments.map(function(segment) {
    templateValues.Number = segment.number;
    templateValues.Time = segment.time;
    var uri = constructTemplateUrl(attributes.media || "", templateValues);
    var timescale2 = attributes.timescale || 1;
    var presentationTimeOffset2 = attributes.presentationTimeOffset || 0;
    var presentationTime = (
      // Even if the @t attribute is not specified for the segment, segment.time is
      // calculated in mpd-parser prior to this, so it's assumed to be available.
      attributes.periodStart + (segment.time - presentationTimeOffset2) / timescale2
    );
    var map = {
      uri,
      timeline: segment.timeline,
      duration: segment.duration,
      resolvedUri: resolve_url_default(attributes.baseUrl || "", uri),
      map: mapSegment,
      number: segment.number,
      presentationTime
    };
    return map;
  });
};
var SegmentURLToSegmentObject = function SegmentURLToSegmentObject2(attributes, segmentUrl) {
  var baseUrl = attributes.baseUrl, _attributes$initializ = attributes.initialization, initialization = _attributes$initializ === void 0 ? {} : _attributes$initializ;
  var initSegment = urlTypeToSegment({
    baseUrl,
    source: initialization.sourceURL,
    range: initialization.range
  });
  var segment = urlTypeToSegment({
    baseUrl,
    source: segmentUrl.media,
    range: segmentUrl.mediaRange
  });
  segment.map = initSegment;
  return segment;
};
var segmentsFromList = function segmentsFromList2(attributes, segmentTimeline) {
  var duration5 = attributes.duration, _attributes$segmentUr = attributes.segmentUrls, segmentUrls = _attributes$segmentUr === void 0 ? [] : _attributes$segmentUr, periodStart = attributes.periodStart;
  if (!duration5 && !segmentTimeline || duration5 && segmentTimeline) {
    throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);
  }
  var segmentUrlMap = segmentUrls.map(function(segmentUrlObject) {
    return SegmentURLToSegmentObject(attributes, segmentUrlObject);
  });
  var segmentTimeInfo;
  if (duration5) {
    segmentTimeInfo = parseByDuration(attributes);
  }
  if (segmentTimeline) {
    segmentTimeInfo = parseByTimeline(attributes, segmentTimeline);
  }
  var segments = segmentTimeInfo.map(function(segmentTime, index) {
    if (segmentUrlMap[index]) {
      var segment = segmentUrlMap[index];
      var timescale2 = attributes.timescale || 1;
      var presentationTimeOffset2 = attributes.presentationTimeOffset || 0;
      segment.timeline = segmentTime.timeline;
      segment.duration = segmentTime.duration;
      segment.number = segmentTime.number;
      segment.presentationTime = periodStart + (segmentTime.time - presentationTimeOffset2) / timescale2;
      return segment;
    }
  }).filter(function(segment) {
    return segment;
  });
  return segments;
};
var generateSegments = function generateSegments2(_ref) {
  var attributes = _ref.attributes, segmentInfo = _ref.segmentInfo;
  var segmentAttributes;
  var segmentsFn;
  if (segmentInfo.template) {
    segmentsFn = segmentsFromTemplate;
    segmentAttributes = merge(attributes, segmentInfo.template);
  } else if (segmentInfo.base) {
    segmentsFn = segmentsFromBase;
    segmentAttributes = merge(attributes, segmentInfo.base);
  } else if (segmentInfo.list) {
    segmentsFn = segmentsFromList;
    segmentAttributes = merge(attributes, segmentInfo.list);
  }
  var segmentsInfo = {
    attributes
  };
  if (!segmentsFn) {
    return segmentsInfo;
  }
  var segments = segmentsFn(segmentAttributes, segmentInfo.segmentTimeline);
  if (segmentAttributes.duration) {
    var _segmentAttributes = segmentAttributes, duration5 = _segmentAttributes.duration, _segmentAttributes$ti = _segmentAttributes.timescale, timescale2 = _segmentAttributes$ti === void 0 ? 1 : _segmentAttributes$ti;
    segmentAttributes.duration = duration5 / timescale2;
  } else if (segments.length) {
    segmentAttributes.duration = segments.reduce(function(max, segment) {
      return Math.max(max, Math.ceil(segment.duration));
    }, 0);
  } else {
    segmentAttributes.duration = 0;
  }
  segmentsInfo.attributes = segmentAttributes;
  segmentsInfo.segments = segments;
  if (segmentInfo.base && segmentAttributes.indexRange) {
    segmentsInfo.sidx = segments[0];
    segmentsInfo.segments = [];
  }
  return segmentsInfo;
};
var toPlaylists = function toPlaylists2(representations) {
  return representations.map(generateSegments);
};
var findChildren = function findChildren2(element, name) {
  return from(element.childNodes).filter(function(_ref) {
    var tagName = _ref.tagName;
    return tagName === name;
  });
};
var getContent = function getContent2(element) {
  return element.textContent.trim();
};
var parseDuration = function parseDuration2(str) {
  var SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
  var SECONDS_IN_MONTH = 30 * 24 * 60 * 60;
  var SECONDS_IN_DAY = 24 * 60 * 60;
  var SECONDS_IN_HOUR = 60 * 60;
  var SECONDS_IN_MIN = 60;
  var durationRegex = /P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/;
  var match = durationRegex.exec(str);
  if (!match) {
    return 0;
  }
  var _match$slice = match.slice(1), year = _match$slice[0], month = _match$slice[1], day = _match$slice[2], hour = _match$slice[3], minute = _match$slice[4], second = _match$slice[5];
  return parseFloat(year || 0) * SECONDS_IN_YEAR + parseFloat(month || 0) * SECONDS_IN_MONTH + parseFloat(day || 0) * SECONDS_IN_DAY + parseFloat(hour || 0) * SECONDS_IN_HOUR + parseFloat(minute || 0) * SECONDS_IN_MIN + parseFloat(second || 0);
};
var parseDate = function parseDate2(str) {
  var dateRegex = /^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/;
  if (dateRegex.test(str)) {
    str += "Z";
  }
  return Date.parse(str);
};
var parsers = {
  /**
   * Specifies the duration of the entire Media Presentation. Format is a duration string
   * as specified in ISO 8601
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The duration in seconds
   */
  mediaPresentationDuration: function mediaPresentationDuration(value) {
    return parseDuration(value);
  },
  /**
   * Specifies the Segment availability start time for all Segments referred to in this
   * MPD. For a dynamic manifest, it specifies the anchor for the earliest availability
   * time. Format is a date string as specified in ISO 8601
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The date as seconds from unix epoch
   */
  availabilityStartTime: function availabilityStartTime(value) {
    return parseDate(value) / 1e3;
  },
  /**
   * Specifies the smallest period between potential changes to the MPD. Format is a
   * duration string as specified in ISO 8601
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The duration in seconds
   */
  minimumUpdatePeriod: function minimumUpdatePeriod(value) {
    return parseDuration(value);
  },
  /**
   * Specifies the suggested presentation delay. Format is a
   * duration string as specified in ISO 8601
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The duration in seconds
   */
  suggestedPresentationDelay: function suggestedPresentationDelay(value) {
    return parseDuration(value);
  },
  /**
   * specifices the type of mpd. Can be either "static" or "dynamic"
   *
   * @param {string} value
   *        value of attribute as a string
   *
   * @return {string}
   *         The type as a string
   */
  type: function type(value) {
    return value;
  },
  /**
   * Specifies the duration of the smallest time shifting buffer for any Representation
   * in the MPD. Format is a duration string as specified in ISO 8601
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The duration in seconds
   */
  timeShiftBufferDepth: function timeShiftBufferDepth(value) {
    return parseDuration(value);
  },
  /**
   * Specifies the PeriodStart time of the Period relative to the availabilityStarttime.
   * Format is a duration string as specified in ISO 8601
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The duration in seconds
   */
  start: function start(value) {
    return parseDuration(value);
  },
  /**
   * Specifies the width of the visual presentation
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed width
   */
  width: function width(value) {
    return parseInt(value, 10);
  },
  /**
   * Specifies the height of the visual presentation
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed height
   */
  height: function height(value) {
    return parseInt(value, 10);
  },
  /**
   * Specifies the bitrate of the representation
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed bandwidth
   */
  bandwidth: function bandwidth(value) {
    return parseInt(value, 10);
  },
  /**
   * Specifies the number of the first Media Segment in this Representation in the Period
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed number
   */
  startNumber: function startNumber(value) {
    return parseInt(value, 10);
  },
  /**
   * Specifies the timescale in units per seconds
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed timescale
   */
  timescale: function timescale(value) {
    return parseInt(value, 10);
  },
  /**
   * Specifies the presentationTimeOffset.
   *
   * @param {string} value
   *        value of the attribute as a string
   *
   * @return {number}
   *         The parsed presentationTimeOffset
   */
  presentationTimeOffset: function presentationTimeOffset(value) {
    return parseInt(value, 10);
  },
  /**
   * Specifies the constant approximate Segment duration
   * NOTE: The <Period> element also contains an @duration attribute. This duration
   *       specifies the duration of the Period. This attribute is currently not
   *       supported by the rest of the parser, however we still check for it to prevent
   *       errors.
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed duration
   */
  duration: function duration(value) {
    var parsedValue = parseInt(value, 10);
    if (isNaN(parsedValue)) {
      return parseDuration(value);
    }
    return parsedValue;
  },
  /**
   * Specifies the Segment duration, in units of the value of the @timescale.
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed duration
   */
  d: function d(value) {
    return parseInt(value, 10);
  },
  /**
   * Specifies the MPD start time, in @timescale units, the first Segment in the series
   * starts relative to the beginning of the Period
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed time
   */
  t: function t(value) {
    return parseInt(value, 10);
  },
  /**
   * Specifies the repeat count of the number of following contiguous Segments with the
   * same duration expressed by the value of @d
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed number
   */
  r: function r(value) {
    return parseInt(value, 10);
  },
  /**
   * Default parser for all other attributes. Acts as a no-op and just returns the value
   * as a string
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {string}
   *         Unparsed value
   */
  DEFAULT: function DEFAULT(value) {
    return value;
  }
};
var parseAttributes3 = function parseAttributes4(el) {
  if (!(el && el.attributes)) {
    return {};
  }
  return from(el.attributes).reduce(function(a, e) {
    var parseFn = parsers[e.name] || parsers.DEFAULT;
    a[e.name] = parseFn(e.value);
    return a;
  }, {});
};
var keySystemsMap = {
  "urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b": "org.w3.clearkey",
  "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed": "com.widevine.alpha",
  "urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95": "com.microsoft.playready",
  "urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb": "com.adobe.primetime"
};
var buildBaseUrls = function buildBaseUrls2(referenceUrls, baseUrlElements) {
  if (!baseUrlElements.length) {
    return referenceUrls;
  }
  return flatten(referenceUrls.map(function(reference) {
    return baseUrlElements.map(function(baseUrlElement) {
      return resolve_url_default(reference, getContent(baseUrlElement));
    });
  }));
};
var getSegmentInformation = function getSegmentInformation2(adaptationSet) {
  var segmentTemplate = findChildren(adaptationSet, "SegmentTemplate")[0];
  var segmentList = findChildren(adaptationSet, "SegmentList")[0];
  var segmentUrls = segmentList && findChildren(segmentList, "SegmentURL").map(function(s) {
    return merge({
      tag: "SegmentURL"
    }, parseAttributes3(s));
  });
  var segmentBase = findChildren(adaptationSet, "SegmentBase")[0];
  var segmentTimelineParentNode = segmentList || segmentTemplate;
  var segmentTimeline = segmentTimelineParentNode && findChildren(segmentTimelineParentNode, "SegmentTimeline")[0];
  var segmentInitializationParentNode = segmentList || segmentBase || segmentTemplate;
  var segmentInitialization = segmentInitializationParentNode && findChildren(segmentInitializationParentNode, "Initialization")[0];
  var template = segmentTemplate && parseAttributes3(segmentTemplate);
  if (template && segmentInitialization) {
    template.initialization = segmentInitialization && parseAttributes3(segmentInitialization);
  } else if (template && template.initialization) {
    template.initialization = {
      sourceURL: template.initialization
    };
  }
  var segmentInfo = {
    template,
    segmentTimeline: segmentTimeline && findChildren(segmentTimeline, "S").map(function(s) {
      return parseAttributes3(s);
    }),
    list: segmentList && merge(parseAttributes3(segmentList), {
      segmentUrls,
      initialization: parseAttributes3(segmentInitialization)
    }),
    base: segmentBase && merge(parseAttributes3(segmentBase), {
      initialization: parseAttributes3(segmentInitialization)
    })
  };
  Object.keys(segmentInfo).forEach(function(key) {
    if (!segmentInfo[key]) {
      delete segmentInfo[key];
    }
  });
  return segmentInfo;
};
var inheritBaseUrls = function inheritBaseUrls2(adaptationSetAttributes, adaptationSetBaseUrls, adaptationSetSegmentInfo) {
  return function(representation) {
    var repBaseUrlElements = findChildren(representation, "BaseURL");
    var repBaseUrls = buildBaseUrls(adaptationSetBaseUrls, repBaseUrlElements);
    var attributes = merge(adaptationSetAttributes, parseAttributes3(representation));
    var representationSegmentInfo = getSegmentInformation(representation);
    return repBaseUrls.map(function(baseUrl) {
      return {
        segmentInfo: merge(adaptationSetSegmentInfo, representationSegmentInfo),
        attributes: merge(attributes, {
          baseUrl
        })
      };
    });
  };
};
var generateKeySystemInformation = function generateKeySystemInformation2(contentProtectionNodes) {
  return contentProtectionNodes.reduce(function(acc, node) {
    var attributes = parseAttributes3(node);
    if (attributes.schemeIdUri) {
      attributes.schemeIdUri = attributes.schemeIdUri.toLowerCase();
    }
    var keySystem = keySystemsMap[attributes.schemeIdUri];
    if (keySystem) {
      acc[keySystem] = {
        attributes
      };
      var psshNode = findChildren(node, "cenc:pssh")[0];
      if (psshNode) {
        var pssh = getContent(psshNode);
        acc[keySystem].pssh = pssh && decodeB64ToUint8Array(pssh);
      }
    }
    return acc;
  }, {});
};
var parseCaptionServiceMetadata = function parseCaptionServiceMetadata2(service) {
  if (service.schemeIdUri === "urn:scte:dash:cc:cea-608:2015") {
    var values3 = typeof service.value !== "string" ? [] : service.value.split(";");
    return values3.map(function(value) {
      var channel;
      var language;
      language = value;
      if (/^CC\d=/.test(value)) {
        var _value$split = value.split("=");
        channel = _value$split[0];
        language = _value$split[1];
      } else if (/^CC\d$/.test(value)) {
        channel = value;
      }
      return {
        channel,
        language
      };
    });
  } else if (service.schemeIdUri === "urn:scte:dash:cc:cea-708:2015") {
    var _values = typeof service.value !== "string" ? [] : service.value.split(";");
    return _values.map(function(value) {
      var flags = {
        // service or channel number 1-63
        "channel": void 0,
        // language is a 3ALPHA per ISO 639.2/B
        // field is required
        "language": void 0,
        // BIT 1/0 or ?
        // default value is 1, meaning 16:9 aspect ratio, 0 is 4:3, ? is unknown
        "aspectRatio": 1,
        // BIT 1/0
        // easy reader flag indicated the text is tailed to the needs of beginning readers
        // default 0, or off
        "easyReader": 0,
        // BIT 1/0
        // If 3d metadata is present (CEA-708.1) then 1
        // default 0
        "3D": 0
      };
      if (/=/.test(value)) {
        var _value$split2 = value.split("="), channel = _value$split2[0], _value$split2$ = _value$split2[1], opts = _value$split2$ === void 0 ? "" : _value$split2$;
        flags.channel = channel;
        flags.language = value;
        opts.split(",").forEach(function(opt) {
          var _opt$split = opt.split(":"), name = _opt$split[0], val = _opt$split[1];
          if (name === "lang") {
            flags.language = val;
          } else if (name === "er") {
            flags.easyReader = Number(val);
          } else if (name === "war") {
            flags.aspectRatio = Number(val);
          } else if (name === "3D") {
            flags["3D"] = Number(val);
          }
        });
      } else {
        flags.language = value;
      }
      if (flags.channel) {
        flags.channel = "SERVICE" + flags.channel;
      }
      return flags;
    });
  }
};
var toRepresentations = function toRepresentations2(periodAttributes, periodBaseUrls, periodSegmentInfo) {
  return function(adaptationSet) {
    var adaptationSetAttributes = parseAttributes3(adaptationSet);
    var adaptationSetBaseUrls = buildBaseUrls(periodBaseUrls, findChildren(adaptationSet, "BaseURL"));
    var role = findChildren(adaptationSet, "Role")[0];
    var roleAttributes = {
      role: parseAttributes3(role)
    };
    var attrs = merge(periodAttributes, adaptationSetAttributes, roleAttributes);
    var accessibility = findChildren(adaptationSet, "Accessibility")[0];
    var captionServices = parseCaptionServiceMetadata(parseAttributes3(accessibility));
    if (captionServices) {
      attrs = merge(attrs, {
        captionServices
      });
    }
    var label = findChildren(adaptationSet, "Label")[0];
    if (label && label.childNodes.length) {
      var labelVal = label.childNodes[0].nodeValue.trim();
      attrs = merge(attrs, {
        label: labelVal
      });
    }
    var contentProtection = generateKeySystemInformation(findChildren(adaptationSet, "ContentProtection"));
    if (Object.keys(contentProtection).length) {
      attrs = merge(attrs, {
        contentProtection
      });
    }
    var segmentInfo = getSegmentInformation(adaptationSet);
    var representations = findChildren(adaptationSet, "Representation");
    var adaptationSetSegmentInfo = merge(periodSegmentInfo, segmentInfo);
    return flatten(representations.map(inheritBaseUrls(attrs, adaptationSetBaseUrls, adaptationSetSegmentInfo)));
  };
};
var toAdaptationSets = function toAdaptationSets2(mpdAttributes, mpdBaseUrls) {
  return function(period, index) {
    var periodBaseUrls = buildBaseUrls(mpdBaseUrls, findChildren(period.node, "BaseURL"));
    var periodAttributes = merge(mpdAttributes, {
      periodStart: period.attributes.start
    });
    if (typeof period.attributes.duration === "number") {
      periodAttributes.periodDuration = period.attributes.duration;
    }
    var adaptationSets = findChildren(period.node, "AdaptationSet");
    var periodSegmentInfo = getSegmentInformation(period.node);
    return flatten(adaptationSets.map(toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo)));
  };
};
var getPeriodStart = function getPeriodStart2(_ref) {
  var attributes = _ref.attributes, priorPeriodAttributes = _ref.priorPeriodAttributes, mpdType = _ref.mpdType;
  if (typeof attributes.start === "number") {
    return attributes.start;
  }
  if (priorPeriodAttributes && typeof priorPeriodAttributes.start === "number" && typeof priorPeriodAttributes.duration === "number") {
    return priorPeriodAttributes.start + priorPeriodAttributes.duration;
  }
  if (!priorPeriodAttributes && mpdType === "static") {
    return 0;
  }
  return null;
};
var inheritAttributes = function inheritAttributes2(mpd, options) {
  if (options === void 0) {
    options = {};
  }
  var _options = options, _options$manifestUri = _options.manifestUri, manifestUri = _options$manifestUri === void 0 ? "" : _options$manifestUri, _options$NOW = _options.NOW, NOW = _options$NOW === void 0 ? Date.now() : _options$NOW, _options$clientOffset = _options.clientOffset, clientOffset = _options$clientOffset === void 0 ? 0 : _options$clientOffset;
  var periodNodes = findChildren(mpd, "Period");
  if (!periodNodes.length) {
    throw new Error(errors.INVALID_NUMBER_OF_PERIOD);
  }
  var locations = findChildren(mpd, "Location");
  var mpdAttributes = parseAttributes3(mpd);
  var mpdBaseUrls = buildBaseUrls([manifestUri], findChildren(mpd, "BaseURL"));
  mpdAttributes.type = mpdAttributes.type || "static";
  mpdAttributes.sourceDuration = mpdAttributes.mediaPresentationDuration || 0;
  mpdAttributes.NOW = NOW;
  mpdAttributes.clientOffset = clientOffset;
  if (locations.length) {
    mpdAttributes.locations = locations.map(getContent);
  }
  var periods = [];
  periodNodes.forEach(function(node, index) {
    var attributes = parseAttributes3(node);
    var priorPeriod = periods[index - 1];
    attributes.start = getPeriodStart({
      attributes,
      priorPeriodAttributes: priorPeriod ? priorPeriod.attributes : null,
      mpdType: mpdAttributes.type
    });
    periods.push({
      node,
      attributes
    });
  });
  return {
    locations: mpdAttributes.locations,
    representationInfo: flatten(periods.map(toAdaptationSets(mpdAttributes, mpdBaseUrls)))
  };
};
var stringToMpdXml = function stringToMpdXml2(manifestString) {
  if (manifestString === "") {
    throw new Error(errors.DASH_EMPTY_MANIFEST);
  }
  var parser6 = new import_xmldom.DOMParser();
  var xml;
  var mpd;
  try {
    xml = parser6.parseFromString(manifestString, "application/xml");
    mpd = xml && xml.documentElement.tagName === "MPD" ? xml.documentElement : null;
  } catch (e) {
  }
  if (!mpd || mpd && mpd.getElementsByTagName("parsererror").length > 0) {
    throw new Error(errors.DASH_INVALID_XML);
  }
  return mpd;
};
var parseUTCTimingScheme = function parseUTCTimingScheme2(mpd) {
  var UTCTimingNode = findChildren(mpd, "UTCTiming")[0];
  if (!UTCTimingNode) {
    return null;
  }
  var attributes = parseAttributes3(UTCTimingNode);
  switch (attributes.schemeIdUri) {
    case "urn:mpeg:dash:utc:http-head:2014":
    case "urn:mpeg:dash:utc:http-head:2012":
      attributes.method = "HEAD";
      break;
    case "urn:mpeg:dash:utc:http-xsdate:2014":
    case "urn:mpeg:dash:utc:http-iso:2014":
    case "urn:mpeg:dash:utc:http-xsdate:2012":
    case "urn:mpeg:dash:utc:http-iso:2012":
      attributes.method = "GET";
      break;
    case "urn:mpeg:dash:utc:direct:2014":
    case "urn:mpeg:dash:utc:direct:2012":
      attributes.method = "DIRECT";
      attributes.value = Date.parse(attributes.value);
      break;
    case "urn:mpeg:dash:utc:http-ntp:2014":
    case "urn:mpeg:dash:utc:ntp:2014":
    case "urn:mpeg:dash:utc:sntp:2014":
    default:
      throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);
  }
  return attributes;
};
var parse = function parse2(manifestString, options) {
  if (options === void 0) {
    options = {};
  }
  var parsedManifestInfo = inheritAttributes(stringToMpdXml(manifestString), options);
  var playlists = toPlaylists(parsedManifestInfo.representationInfo);
  return toM3u8({
    dashPlaylists: playlists,
    locations: parsedManifestInfo.locations,
    sidxMapping: options.sidxMapping,
    previousManifest: options.previousManifest
  });
};
var parseUTCTiming = function parseUTCTiming2(manifestString) {
  return parseUTCTimingScheme(stringToMpdXml(manifestString));
};

// node_modules/.pnpm/video.js@7.20.3/node_modules/video.js/dist/video.es.js
var import_parse_sidx = __toESM(require_parse_sidx());

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/id3-helpers.js
var ID3 = toUint82([73, 68, 51]);
var getId3Size = function getId3Size2(bytes, offset) {
  if (offset === void 0) {
    offset = 0;
  }
  bytes = toUint82(bytes);
  var flags = bytes[offset + 5];
  var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
  var footerPresent = (flags & 16) >> 4;
  if (footerPresent) {
    return returnSize + 20;
  }
  return returnSize + 10;
};
var getId3Offset = function getId3Offset2(bytes, offset) {
  if (offset === void 0) {
    offset = 0;
  }
  bytes = toUint82(bytes);
  if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
    offset
  })) {
    return offset;
  }
  offset += getId3Size(bytes, offset);
  return getId3Offset2(bytes, offset);
};

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/opus-helpers.js
var OPUS_HEAD = new Uint8Array([
  // O, p, u, s
  79,
  112,
  117,
  115,
  // H, e, a, d
  72,
  101,
  97,
  100
]);

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/mp4-helpers.js
var normalizePath = function normalizePath2(path) {
  if (typeof path === "string") {
    return stringToBytes(path);
  }
  if (typeof path === "number") {
    return path;
  }
  return path;
};
var normalizePaths = function normalizePaths2(paths) {
  if (!Array.isArray(paths)) {
    return [normalizePath(paths)];
  }
  return paths.map(function(p) {
    return normalizePath(p);
  });
};
var DESCRIPTORS;
var parseDescriptors = function parseDescriptors2(bytes) {
  bytes = toUint82(bytes);
  var results = [];
  var i = 0;
  while (bytes.length > i) {
    var tag = bytes[i];
    var size = 0;
    var headerSize = 0;
    headerSize++;
    var byte = bytes[headerSize];
    headerSize++;
    while (byte & 128) {
      size = (byte & 127) << 7;
      byte = bytes[headerSize];
      headerSize++;
    }
    size += byte & 127;
    for (var z = 0; z < DESCRIPTORS.length; z++) {
      var _DESCRIPTORS$z = DESCRIPTORS[z], id = _DESCRIPTORS$z.id, parser6 = _DESCRIPTORS$z.parser;
      if (tag === id) {
        results.push(parser6(bytes.subarray(headerSize, headerSize + size)));
        break;
      }
    }
    i += size + headerSize;
  }
  return results;
};
DESCRIPTORS = [{
  id: 3,
  parser: function parser(bytes) {
    var desc = {
      tag: 3,
      id: bytes[0] << 8 | bytes[1],
      flags: bytes[2],
      size: 3,
      dependsOnEsId: 0,
      ocrEsId: 0,
      descriptors: [],
      url: ""
    };
    if (desc.flags & 128) {
      desc.dependsOnEsId = bytes[desc.size] << 8 | bytes[desc.size + 1];
      desc.size += 2;
    }
    if (desc.flags & 64) {
      var len = bytes[desc.size];
      desc.url = bytesToString(bytes.subarray(desc.size + 1, desc.size + 1 + len));
      desc.size += len;
    }
    if (desc.flags & 32) {
      desc.ocrEsId = bytes[desc.size] << 8 | bytes[desc.size + 1];
      desc.size += 2;
    }
    desc.descriptors = parseDescriptors(bytes.subarray(desc.size)) || [];
    return desc;
  }
}, {
  id: 4,
  parser: function parser2(bytes) {
    var desc = {
      tag: 4,
      oti: bytes[0],
      streamType: bytes[1],
      bufferSize: bytes[2] << 16 | bytes[3] << 8 | bytes[4],
      maxBitrate: bytes[5] << 24 | bytes[6] << 16 | bytes[7] << 8 | bytes[8],
      avgBitrate: bytes[9] << 24 | bytes[10] << 16 | bytes[11] << 8 | bytes[12],
      descriptors: parseDescriptors(bytes.subarray(13))
    };
    return desc;
  }
}, {
  id: 5,
  parser: function parser3(bytes) {
    return {
      tag: 5,
      bytes
    };
  }
}, {
  id: 6,
  parser: function parser4(bytes) {
    return {
      tag: 6,
      bytes
    };
  }
}];
var findBox2 = function findBox3(bytes, paths, complete) {
  if (complete === void 0) {
    complete = false;
  }
  paths = normalizePaths(paths);
  bytes = toUint82(bytes);
  var results = [];
  if (!paths.length) {
    return results;
  }
  var i = 0;
  while (i < bytes.length) {
    var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
    var type2 = bytes.subarray(i + 4, i + 8);
    if (size === 0) {
      break;
    }
    var end = i + size;
    if (end > bytes.length) {
      if (complete) {
        break;
      }
      end = bytes.length;
    }
    var data = bytes.subarray(i + 8, end);
    if (bytesMatch(type2, paths[0])) {
      if (paths.length === 1) {
        results.push(data);
      } else {
        results.push.apply(results, findBox3(data, paths.slice(1), complete));
      }
    }
    i = end;
  }
  return results;
};

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/ebml-helpers.js
var EBML_TAGS = {
  EBML: toUint82([26, 69, 223, 163]),
  DocType: toUint82([66, 130]),
  Segment: toUint82([24, 83, 128, 103]),
  SegmentInfo: toUint82([21, 73, 169, 102]),
  Tracks: toUint82([22, 84, 174, 107]),
  Track: toUint82([174]),
  TrackNumber: toUint82([215]),
  DefaultDuration: toUint82([35, 227, 131]),
  TrackEntry: toUint82([174]),
  TrackType: toUint82([131]),
  FlagDefault: toUint82([136]),
  CodecID: toUint82([134]),
  CodecPrivate: toUint82([99, 162]),
  VideoTrack: toUint82([224]),
  AudioTrack: toUint82([225]),
  // Not used yet, but will be used for live webm/mkv
  // see https://www.matroska.org/technical/basics.html#block-structure
  // see https://www.matroska.org/technical/basics.html#simpleblock-structure
  Cluster: toUint82([31, 67, 182, 117]),
  Timestamp: toUint82([231]),
  TimestampScale: toUint82([42, 215, 177]),
  BlockGroup: toUint82([160]),
  BlockDuration: toUint82([155]),
  Block: toUint82([161]),
  SimpleBlock: toUint82([163])
};
var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
var getLength = function getLength2(byte) {
  var len = 1;
  for (var i = 0; i < LENGTH_TABLE.length; i++) {
    if (byte & LENGTH_TABLE[i]) {
      break;
    }
    len++;
  }
  return len;
};
var getvint = function getvint2(bytes, offset, removeLength, signed) {
  if (removeLength === void 0) {
    removeLength = true;
  }
  if (signed === void 0) {
    signed = false;
  }
  var length = getLength(bytes[offset]);
  var valueBytes = bytes.subarray(offset, offset + length);
  if (removeLength) {
    valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
    valueBytes[0] ^= LENGTH_TABLE[length - 1];
  }
  return {
    length,
    value: bytesToNumber(valueBytes, {
      signed
    }),
    bytes: valueBytes
  };
};
var normalizePath3 = function normalizePath4(path) {
  if (typeof path === "string") {
    return path.match(/.{1,2}/g).map(function(p) {
      return normalizePath4(p);
    });
  }
  if (typeof path === "number") {
    return numberToBytes(path);
  }
  return path;
};
var normalizePaths3 = function normalizePaths4(paths) {
  if (!Array.isArray(paths)) {
    return [normalizePath3(paths)];
  }
  return paths.map(function(p) {
    return normalizePath3(p);
  });
};
var getInfinityDataSize = function getInfinityDataSize2(id, bytes, offset) {
  if (offset >= bytes.length) {
    return bytes.length;
  }
  var innerid = getvint(bytes, offset, false);
  if (bytesMatch(id.bytes, innerid.bytes)) {
    return offset;
  }
  var dataHeader = getvint(bytes, offset + innerid.length);
  return getInfinityDataSize2(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
};
var findEbml = function findEbml2(bytes, paths) {
  paths = normalizePaths3(paths);
  bytes = toUint82(bytes);
  var results = [];
  if (!paths.length) {
    return results;
  }
  var i = 0;
  while (i < bytes.length) {
    var id = getvint(bytes, i, false);
    var dataHeader = getvint(bytes, i + id.length);
    var dataStart = i + id.length + dataHeader.length;
    if (dataHeader.value === 127) {
      dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
      if (dataHeader.value !== bytes.length) {
        dataHeader.value -= dataStart;
      }
    }
    var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
    var data = bytes.subarray(dataStart, dataEnd);
    if (bytesMatch(paths[0], id.bytes)) {
      if (paths.length === 1) {
        results.push(data);
      } else {
        results = results.concat(findEbml2(data, paths.slice(1)));
      }
    }
    var totalLength = id.length + dataHeader.length + data.length;
    i += totalLength;
  }
  return results;
};

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/nal-helpers.js
var NAL_TYPE_ONE = toUint82([0, 0, 0, 1]);
var NAL_TYPE_TWO = toUint82([0, 0, 1]);
var EMULATION_PREVENTION = toUint82([0, 0, 3]);
var discardEmulationPreventionBytes = function discardEmulationPreventionBytes2(bytes) {
  var positions = [];
  var i = 1;
  while (i < bytes.length - 2) {
    if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
      positions.push(i + 2);
      i++;
    }
    i++;
  }
  if (positions.length === 0) {
    return bytes;
  }
  var newLength = bytes.length - positions.length;
  var newData = new Uint8Array(newLength);
  var sourceIndex = 0;
  for (i = 0; i < newLength; sourceIndex++, i++) {
    if (sourceIndex === positions[0]) {
      sourceIndex++;
      positions.shift();
    }
    newData[i] = bytes[sourceIndex];
  }
  return newData;
};
var findNal = function findNal2(bytes, dataType, types, nalLimit) {
  if (nalLimit === void 0) {
    nalLimit = Infinity;
  }
  bytes = toUint82(bytes);
  types = [].concat(types);
  var i = 0;
  var nalStart;
  var nalsFound = 0;
  while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
    var nalOffset = void 0;
    if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
      nalOffset = 4;
    } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
      nalOffset = 3;
    }
    if (!nalOffset) {
      i++;
      continue;
    }
    nalsFound++;
    if (nalStart) {
      return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
    }
    var nalType = void 0;
    if (dataType === "h264") {
      nalType = bytes[i + nalOffset] & 31;
    } else if (dataType === "h265") {
      nalType = bytes[i + nalOffset] >> 1 & 63;
    }
    if (types.indexOf(nalType) !== -1) {
      nalStart = i + nalOffset;
    }
    i += nalOffset + (dataType === "h264" ? 1 : 2);
  }
  return bytes.subarray(0, 0);
};
var findH264Nal = function findH264Nal2(bytes, type2, nalLimit) {
  return findNal(bytes, "h264", type2, nalLimit);
};
var findH265Nal = function findH265Nal2(bytes, type2, nalLimit) {
  return findNal(bytes, "h265", type2, nalLimit);
};

// node_modules/.pnpm/@videojs+vhs-utils@3.0.5/node_modules/@videojs/vhs-utils/es/containers.js
var CONSTANTS = {
  // "webm" string literal in hex
  "webm": toUint82([119, 101, 98, 109]),
  // "matroska" string literal in hex
  "matroska": toUint82([109, 97, 116, 114, 111, 115, 107, 97]),
  // "fLaC" string literal in hex
  "flac": toUint82([102, 76, 97, 67]),
  // "OggS" string literal in hex
  "ogg": toUint82([79, 103, 103, 83]),
  // ac-3 sync byte, also works for ec-3 as that is simply a codec
  // of ac-3
  "ac3": toUint82([11, 119]),
  // "RIFF" string literal in hex used for wav and avi
  "riff": toUint82([82, 73, 70, 70]),
  // "AVI" string literal in hex
  "avi": toUint82([65, 86, 73]),
  // "WAVE" string literal in hex
  "wav": toUint82([87, 65, 86, 69]),
  // "ftyp3g" string literal in hex
  "3gp": toUint82([102, 116, 121, 112, 51, 103]),
  // "ftyp" string literal in hex
  "mp4": toUint82([102, 116, 121, 112]),
  // "styp" string literal in hex
  "fmp4": toUint82([115, 116, 121, 112]),
  // "ftypqt" string literal in hex
  "mov": toUint82([102, 116, 121, 112, 113, 116]),
  // moov string literal in hex
  "moov": toUint82([109, 111, 111, 118]),
  // moof string literal in hex
  "moof": toUint82([109, 111, 111, 102])
};
var _isLikely = {
  aac: function aac(bytes) {
    var offset = getId3Offset(bytes);
    return bytesMatch(bytes, [255, 16], {
      offset,
      mask: [255, 22]
    });
  },
  mp3: function mp3(bytes) {
    var offset = getId3Offset(bytes);
    return bytesMatch(bytes, [255, 2], {
      offset,
      mask: [255, 6]
    });
  },
  webm: function webm(bytes) {
    var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0];
    return bytesMatch(docType, CONSTANTS.webm);
  },
  mkv: function mkv(bytes) {
    var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0];
    return bytesMatch(docType, CONSTANTS.matroska);
  },
  mp4: function mp4(bytes) {
    if (_isLikely["3gp"](bytes) || _isLikely.mov(bytes)) {
      return false;
    }
    if (bytesMatch(bytes, CONSTANTS.mp4, {
      offset: 4
    }) || bytesMatch(bytes, CONSTANTS.fmp4, {
      offset: 4
    })) {
      return true;
    }
    if (bytesMatch(bytes, CONSTANTS.moof, {
      offset: 4
    }) || bytesMatch(bytes, CONSTANTS.moov, {
      offset: 4
    })) {
      return true;
    }
  },
  mov: function mov(bytes) {
    return bytesMatch(bytes, CONSTANTS.mov, {
      offset: 4
    });
  },
  "3gp": function gp(bytes) {
    return bytesMatch(bytes, CONSTANTS["3gp"], {
      offset: 4
    });
  },
  ac3: function ac3(bytes) {
    var offset = getId3Offset(bytes);
    return bytesMatch(bytes, CONSTANTS.ac3, {
      offset
    });
  },
  ts: function ts(bytes) {
    if (bytes.length < 189 && bytes.length >= 1) {
      return bytes[0] === 71;
    }
    var i = 0;
    while (i + 188 < bytes.length && i < 188) {
      if (bytes[i] === 71 && bytes[i + 188] === 71) {
        return true;
      }
      i += 1;
    }
    return false;
  },
  flac: function flac(bytes) {
    var offset = getId3Offset(bytes);
    return bytesMatch(bytes, CONSTANTS.flac, {
      offset
    });
  },
  ogg: function ogg(bytes) {
    return bytesMatch(bytes, CONSTANTS.ogg);
  },
  avi: function avi(bytes) {
    return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
      offset: 8
    });
  },
  wav: function wav(bytes) {
    return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
      offset: 8
    });
  },
  "h264": function h264(bytes) {
    return findH264Nal(bytes, 7, 3).length;
  },
  "h265": function h265(bytes) {
    return findH265Nal(bytes, [32, 33], 3).length;
  }
};
var isLikelyTypes = Object.keys(_isLikely).filter(function(t2) {
  return t2 !== "ts" && t2 !== "h264" && t2 !== "h265";
}).concat(["ts", "h264", "h265"]);
isLikelyTypes.forEach(function(type2) {
  var isLikelyFn = _isLikely[type2];
  _isLikely[type2] = function(bytes) {
    return isLikelyFn(toUint82(bytes));
  };
});
var isLikely = _isLikely;
var detectContainerForBytes = function detectContainerForBytes2(bytes) {
  bytes = toUint82(bytes);
  for (var i = 0; i < isLikelyTypes.length; i++) {
    var type2 = isLikelyTypes[i];
    if (isLikely[type2](bytes)) {
      return type2;
    }
  }
  return "";
};
var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment2(bytes) {
  return findBox2(bytes, ["moof"]).length > 0;
};

// node_modules/.pnpm/video.js@7.20.3/node_modules/video.js/dist/video.es.js
var import_clock = __toESM(require_clock());
var version$5 = "7.20.3";
var hooks_ = {};
var hooks = function hooks2(type2, fn) {
  hooks_[type2] = hooks_[type2] || [];
  if (fn) {
    hooks_[type2] = hooks_[type2].concat(fn);
  }
  return hooks_[type2];
};
var hook = function hook2(type2, fn) {
  hooks(type2, fn);
};
var removeHook = function removeHook2(type2, fn) {
  var index = hooks(type2).indexOf(fn);
  if (index <= -1) {
    return false;
  }
  hooks_[type2] = hooks_[type2].slice();
  hooks_[type2].splice(index, 1);
  return true;
};
var hookOnce = function hookOnce2(type2, fn) {
  hooks(type2, [].concat(fn).map(function(original) {
    var wrapper = function wrapper2() {
      removeHook(type2, wrapper2);
      return original.apply(void 0, arguments);
    };
    return wrapper;
  }));
};
var FullscreenApi = {
  prefixed: true
};
var apiMap = [
  ["requestFullscreen", "exitFullscreen", "fullscreenElement", "fullscreenEnabled", "fullscreenchange", "fullscreenerror", "fullscreen"],
  // WebKit
  ["webkitRequestFullscreen", "webkitExitFullscreen", "webkitFullscreenElement", "webkitFullscreenEnabled", "webkitfullscreenchange", "webkitfullscreenerror", "-webkit-full-screen"],
  // Mozilla
  ["mozRequestFullScreen", "mozCancelFullScreen", "mozFullScreenElement", "mozFullScreenEnabled", "mozfullscreenchange", "mozfullscreenerror", "-moz-full-screen"],
  // Microsoft
  ["msRequestFullscreen", "msExitFullscreen", "msFullscreenElement", "msFullscreenEnabled", "MSFullscreenChange", "MSFullscreenError", "-ms-fullscreen"]
];
var specApi = apiMap[0];
var browserApi;
for (i = 0; i < apiMap.length; i++) {
  if (apiMap[i][1] in import_document.default) {
    browserApi = apiMap[i];
    break;
  }
}
var i;
if (browserApi) {
  for (_i = 0; _i < browserApi.length; _i++) {
    FullscreenApi[specApi[_i]] = browserApi[_i];
  }
  FullscreenApi.prefixed = browserApi[0] !== specApi[0];
}
var _i;
var history = [];
var LogByTypeFactory = function LogByTypeFactory2(name, log2) {
  return function(type2, level, args) {
    var lvl = log2.levels[level];
    var lvlRegExp = new RegExp("^(" + lvl + ")$");
    if (type2 !== "log") {
      args.unshift(type2.toUpperCase() + ":");
    }
    args.unshift(name + ":");
    if (history) {
      history.push([].concat(args));
      var splice = history.length - 1e3;
      history.splice(0, splice > 0 ? splice : 0);
    }
    if (!import_window6.default.console) {
      return;
    }
    var fn = import_window6.default.console[type2];
    if (!fn && type2 === "debug") {
      fn = import_window6.default.console.info || import_window6.default.console.log;
    }
    if (!fn || !lvl || !lvlRegExp.test(type2)) {
      return;
    }
    fn[Array.isArray(args) ? "apply" : "call"](import_window6.default.console, args);
  };
};
function createLogger$1(name) {
  var level = "info";
  var logByType;
  var log2 = function log3() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    logByType("log", level, args);
  };
  logByType = LogByTypeFactory(name, log2);
  log2.createLogger = function(subname) {
    return createLogger$1(name + ": " + subname);
  };
  log2.levels = {
    all: "debug|log|warn|error",
    off: "",
    debug: "debug|log|warn|error",
    info: "log|warn|error",
    warn: "warn|error",
    error: "error",
    DEFAULT: level
  };
  log2.level = function(lvl) {
    if (typeof lvl === "string") {
      if (!log2.levels.hasOwnProperty(lvl)) {
        throw new Error('"' + lvl + '" in not a valid log level');
      }
      level = lvl;
    }
    return level;
  };
  log2.history = function() {
    return history ? [].concat(history) : [];
  };
  log2.history.filter = function(fname) {
    return (history || []).filter(function(historyItem) {
      return new RegExp(".*" + fname + ".*").test(historyItem[0]);
    });
  };
  log2.history.clear = function() {
    if (history) {
      history.length = 0;
    }
  };
  log2.history.disable = function() {
    if (history !== null) {
      history.length = 0;
      history = null;
    }
  };
  log2.history.enable = function() {
    if (history === null) {
      history = [];
    }
  };
  log2.error = function() {
    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }
    return logByType("error", level, args);
  };
  log2.warn = function() {
    for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
      args[_key3] = arguments[_key3];
    }
    return logByType("warn", level, args);
  };
  log2.debug = function() {
    for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
      args[_key4] = arguments[_key4];
    }
    return logByType("debug", level, args);
  };
  return log2;
}
var log$1 = createLogger$1("VIDEOJS");
var createLogger2 = log$1.createLogger;
var toString = Object.prototype.toString;
var keys = function keys2(object) {
  return isObject3(object) ? Object.keys(object) : [];
};
function each(object, fn) {
  keys(object).forEach(function(key) {
    return fn(object[key], key);
  });
}
function reduce(object, fn, initial) {
  if (initial === void 0) {
    initial = 0;
  }
  return keys(object).reduce(function(accum, key) {
    return fn(accum, object[key], key);
  }, initial);
}
function assign(target) {
  for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    sources[_key - 1] = arguments[_key];
  }
  if (Object.assign) {
    return _extends2.apply(void 0, [target].concat(sources));
  }
  sources.forEach(function(source) {
    if (!source) {
      return;
    }
    each(source, function(value, key) {
      target[key] = value;
    });
  });
  return target;
}
function isObject3(value) {
  return !!value && typeof value === "object";
}
function isPlain(value) {
  return isObject3(value) && toString.call(value) === "[object Object]" && value.constructor === Object;
}
function computedStyle(el, prop) {
  if (!el || !prop) {
    return "";
  }
  if (typeof import_window6.default.getComputedStyle === "function") {
    var computedStyleValue;
    try {
      computedStyleValue = import_window6.default.getComputedStyle(el);
    } catch (e) {
      return "";
    }
    return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : "";
  }
  return "";
}
var USER_AGENT = import_window6.default.navigator && import_window6.default.navigator.userAgent || "";
var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT);
var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null;
var IS_IPOD = /iPod/i.test(USER_AGENT);
var IOS_VERSION = function() {
  var match = USER_AGENT.match(/OS (\d+)_/i);
  if (match && match[1]) {
    return match[1];
  }
  return null;
}();
var IS_ANDROID = /Android/i.test(USER_AGENT);
var ANDROID_VERSION = function() {
  var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
  if (!match) {
    return null;
  }
  var major = match[1] && parseFloat(match[1]);
  var minor = match[2] && parseFloat(match[2]);
  if (major && minor) {
    return parseFloat(match[1] + "." + match[2]);
  } else if (major) {
    return major;
  }
  return null;
}();
var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537;
var IS_FIREFOX = /Firefox/i.test(USER_AGENT);
var IS_EDGE = /Edg/i.test(USER_AGENT);
var IS_CHROME = !IS_EDGE && (/Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT));
var CHROME_VERSION = function() {
  var match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
  if (match && match[2]) {
    return parseFloat(match[2]);
  }
  return null;
}();
var IE_VERSION = function() {
  var result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT);
  var version6 = result && parseFloat(result[1]);
  if (!version6 && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {
    version6 = 11;
  }
  return version6;
}();
var IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
var IS_WINDOWS = /Windows/i.test(USER_AGENT);
var TOUCH_ENABLED = Boolean(isReal() && ("ontouchstart" in import_window6.default || import_window6.default.navigator.maxTouchPoints || import_window6.default.DocumentTouch && import_window6.default.document instanceof import_window6.default.DocumentTouch));
var IS_IPAD = /iPad/i.test(USER_AGENT) || IS_SAFARI && TOUCH_ENABLED && !/iPhone/i.test(USER_AGENT);
var IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;
var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
var IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
var browser = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  IS_IPOD,
  IOS_VERSION,
  IS_ANDROID,
  ANDROID_VERSION,
  IS_NATIVE_ANDROID,
  IS_FIREFOX,
  IS_EDGE,
  IS_CHROME,
  CHROME_VERSION,
  IE_VERSION,
  IS_SAFARI,
  IS_WINDOWS,
  TOUCH_ENABLED,
  IS_IPAD,
  IS_IPHONE,
  IS_IOS,
  IS_ANY_SAFARI
});
function isNonBlankString(str) {
  return typeof str === "string" && Boolean(str.trim());
}
function throwIfWhitespace(str) {
  if (str.indexOf(" ") >= 0) {
    throw new Error("class has illegal whitespace characters");
  }
}
function classRegExp(className) {
  return new RegExp("(^|\\s)" + className + "($|\\s)");
}
function isReal() {
  return import_document.default === import_window6.default.document;
}
function isEl(value) {
  return isObject3(value) && value.nodeType === 1;
}
function isInFrame() {
  try {
    return import_window6.default.parent !== import_window6.default.self;
  } catch (x) {
    return true;
  }
}
function createQuerier(method) {
  return function(selector, context) {
    if (!isNonBlankString(selector)) {
      return import_document.default[method](null);
    }
    if (isNonBlankString(context)) {
      context = import_document.default.querySelector(context);
    }
    var ctx = isEl(context) ? context : import_document.default;
    return ctx[method] && ctx[method](selector);
  };
}
function createEl(tagName, properties, attributes, content) {
  if (tagName === void 0) {
    tagName = "div";
  }
  if (properties === void 0) {
    properties = {};
  }
  if (attributes === void 0) {
    attributes = {};
  }
  var el = import_document.default.createElement(tagName);
  Object.getOwnPropertyNames(properties).forEach(function(propName) {
    var val = properties[propName];
    if (propName.indexOf("aria-") !== -1 || propName === "role" || propName === "type") {
      log$1.warn("Setting attributes in the second argument of createEl()\nhas been deprecated. Use the third argument instead.\n" + ("createEl(type, properties, attributes). Attempting to set " + propName + " to " + val + "."));
      el.setAttribute(propName, val);
    } else if (propName === "textContent") {
      textContent(el, val);
    } else if (el[propName] !== val || propName === "tabIndex") {
      el[propName] = val;
    }
  });
  Object.getOwnPropertyNames(attributes).forEach(function(attrName) {
    el.setAttribute(attrName, attributes[attrName]);
  });
  if (content) {
    appendContent(el, content);
  }
  return el;
}
function textContent(el, text) {
  if (typeof el.textContent === "undefined") {
    el.innerText = text;
  } else {
    el.textContent = text;
  }
  return el;
}
function prependTo(child, parent) {
  if (parent.firstChild) {
    parent.insertBefore(child, parent.firstChild);
  } else {
    parent.appendChild(child);
  }
}
function hasClass(element, classToCheck) {
  throwIfWhitespace(classToCheck);
  if (element.classList) {
    return element.classList.contains(classToCheck);
  }
  return classRegExp(classToCheck).test(element.className);
}
function addClass(element, classToAdd) {
  if (element.classList) {
    element.classList.add(classToAdd);
  } else if (!hasClass(element, classToAdd)) {
    element.className = (element.className + " " + classToAdd).trim();
  }
  return element;
}
function removeClass(element, classToRemove) {
  if (!element) {
    log$1.warn("removeClass was called with an element that doesn't exist");
    return null;
  }
  if (element.classList) {
    element.classList.remove(classToRemove);
  } else {
    throwIfWhitespace(classToRemove);
    element.className = element.className.split(/\s+/).filter(function(c) {
      return c !== classToRemove;
    }).join(" ");
  }
  return element;
}
function toggleClass(element, classToToggle, predicate) {
  var has = hasClass(element, classToToggle);
  if (typeof predicate === "function") {
    predicate = predicate(element, classToToggle);
  }
  if (typeof predicate !== "boolean") {
    predicate = !has;
  }
  if (predicate === has) {
    return;
  }
  if (predicate) {
    addClass(element, classToToggle);
  } else {
    removeClass(element, classToToggle);
  }
  return element;
}
function setAttributes(el, attributes) {
  Object.getOwnPropertyNames(attributes).forEach(function(attrName) {
    var attrValue = attributes[attrName];
    if (attrValue === null || typeof attrValue === "undefined" || attrValue === false) {
      el.removeAttribute(attrName);
    } else {
      el.setAttribute(attrName, attrValue === true ? "" : attrValue);
    }
  });
}
function getAttributes(tag) {
  var obj = {};
  var knownBooleans = ",autoplay,controls,playsinline,loop,muted,default,defaultMuted,";
  if (tag && tag.attributes && tag.attributes.length > 0) {
    var attrs = tag.attributes;
    for (var i = attrs.length - 1; i >= 0; i--) {
      var attrName = attrs[i].name;
      var attrVal = attrs[i].value;
      if (typeof tag[attrName] === "boolean" || knownBooleans.indexOf("," + attrName + ",") !== -1) {
        attrVal = attrVal !== null ? true : false;
      }
      obj[attrName] = attrVal;
    }
  }
  return obj;
}
function getAttribute(el, attribute) {
  return el.getAttribute(attribute);
}
function setAttribute(el, attribute, value) {
  el.setAttribute(attribute, value);
}
function removeAttribute(el, attribute) {
  el.removeAttribute(attribute);
}
function blockTextSelection() {
  import_document.default.body.focus();
  import_document.default.onselectstart = function() {
    return false;
  };
}
function unblockTextSelection() {
  import_document.default.onselectstart = function() {
    return true;
  };
}
function getBoundingClientRect(el) {
  if (el && el.getBoundingClientRect && el.parentNode) {
    var rect = el.getBoundingClientRect();
    var result = {};
    ["bottom", "height", "left", "right", "top", "width"].forEach(function(k) {
      if (rect[k] !== void 0) {
        result[k] = rect[k];
      }
    });
    if (!result.height) {
      result.height = parseFloat(computedStyle(el, "height"));
    }
    if (!result.width) {
      result.width = parseFloat(computedStyle(el, "width"));
    }
    return result;
  }
}
function findPosition(el) {
  if (!el || el && !el.offsetParent) {
    return {
      left: 0,
      top: 0,
      width: 0,
      height: 0
    };
  }
  var width2 = el.offsetWidth;
  var height2 = el.offsetHeight;
  var left = 0;
  var top = 0;
  while (el.offsetParent && el !== import_document.default[FullscreenApi.fullscreenElement]) {
    left += el.offsetLeft;
    top += el.offsetTop;
    el = el.offsetParent;
  }
  return {
    left,
    top,
    width: width2,
    height: height2
  };
}
function getPointerPosition(el, event) {
  var translated = {
    x: 0,
    y: 0
  };
  if (IS_IOS) {
    var item = el;
    while (item && item.nodeName.toLowerCase() !== "html") {
      var transform3 = computedStyle(item, "transform");
      if (/^matrix/.test(transform3)) {
        var values3 = transform3.slice(7, -1).split(/,\s/).map(Number);
        translated.x += values3[4];
        translated.y += values3[5];
      } else if (/^matrix3d/.test(transform3)) {
        var _values = transform3.slice(9, -1).split(/,\s/).map(Number);
        translated.x += _values[12];
        translated.y += _values[13];
      }
      item = item.parentNode;
    }
  }
  var position = {};
  var boxTarget = findPosition(event.target);
  var box = findPosition(el);
  var boxW = box.width;
  var boxH = box.height;
  var offsetY = event.offsetY - (box.top - boxTarget.top);
  var offsetX = event.offsetX - (box.left - boxTarget.left);
  if (event.changedTouches) {
    offsetX = event.changedTouches[0].pageX - box.left;
    offsetY = event.changedTouches[0].pageY + box.top;
    if (IS_IOS) {
      offsetX -= translated.x;
      offsetY -= translated.y;
    }
  }
  position.y = 1 - Math.max(0, Math.min(1, offsetY / boxH));
  position.x = Math.max(0, Math.min(1, offsetX / boxW));
  return position;
}
function isTextNode(value) {
  return isObject3(value) && value.nodeType === 3;
}
function emptyEl(el) {
  while (el.firstChild) {
    el.removeChild(el.firstChild);
  }
  return el;
}
function normalizeContent(content) {
  if (typeof content === "function") {
    content = content();
  }
  return (Array.isArray(content) ? content : [content]).map(function(value) {
    if (typeof value === "function") {
      value = value();
    }
    if (isEl(value) || isTextNode(value)) {
      return value;
    }
    if (typeof value === "string" && /\S/.test(value)) {
      return import_document.default.createTextNode(value);
    }
  }).filter(function(value) {
    return value;
  });
}
function appendContent(el, content) {
  normalizeContent(content).forEach(function(node) {
    return el.appendChild(node);
  });
  return el;
}
function insertContent(el, content) {
  return appendContent(emptyEl(el), content);
}
function isSingleLeftClick(event) {
  if (event.button === void 0 && event.buttons === void 0) {
    return true;
  }
  if (event.button === 0 && event.buttons === void 0) {
    return true;
  }
  if (event.type === "mouseup" && event.button === 0 && event.buttons === 0) {
    return true;
  }
  if (event.button !== 0 || event.buttons !== 1) {
    return false;
  }
  return true;
}
var $ = createQuerier("querySelector");
var $$ = createQuerier("querySelectorAll");
var Dom = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  isReal,
  isEl,
  isInFrame,
  createEl,
  textContent,
  prependTo,
  hasClass,
  addClass,
  removeClass,
  toggleClass,
  setAttributes,
  getAttributes,
  getAttribute,
  setAttribute,
  removeAttribute,
  blockTextSelection,
  unblockTextSelection,
  getBoundingClientRect,
  findPosition,
  getPointerPosition,
  isTextNode,
  emptyEl,
  normalizeContent,
  appendContent,
  insertContent,
  isSingleLeftClick,
  $,
  $$
});
var _windowLoaded = false;
var videojs$1;
var autoSetup = function autoSetup2() {
  if (videojs$1.options.autoSetup === false) {
    return;
  }
  var vids = Array.prototype.slice.call(import_document.default.getElementsByTagName("video"));
  var audios = Array.prototype.slice.call(import_document.default.getElementsByTagName("audio"));
  var divs = Array.prototype.slice.call(import_document.default.getElementsByTagName("video-js"));
  var mediaEls = vids.concat(audios, divs);
  if (mediaEls && mediaEls.length > 0) {
    for (var i = 0, e = mediaEls.length; i < e; i++) {
      var mediaEl = mediaEls[i];
      if (mediaEl && mediaEl.getAttribute) {
        if (mediaEl.player === void 0) {
          var options = mediaEl.getAttribute("data-setup");
          if (options !== null) {
            videojs$1(mediaEl);
          }
        }
      } else {
        autoSetupTimeout(1);
        break;
      }
    }
  } else if (!_windowLoaded) {
    autoSetupTimeout(1);
  }
};
function autoSetupTimeout(wait, vjs) {
  if (!isReal()) {
    return;
  }
  if (vjs) {
    videojs$1 = vjs;
  }
  import_window6.default.setTimeout(autoSetup, wait);
}
function setWindowLoaded() {
  _windowLoaded = true;
  import_window6.default.removeEventListener("load", setWindowLoaded);
}
if (isReal()) {
  if (import_document.default.readyState === "complete") {
    setWindowLoaded();
  } else {
    import_window6.default.addEventListener("load", setWindowLoaded);
  }
}
var createStyleElement = function createStyleElement2(className) {
  var style = import_document.default.createElement("style");
  style.className = className;
  return style;
};
var setTextContent = function setTextContent2(el, content) {
  if (el.styleSheet) {
    el.styleSheet.cssText = content;
  } else {
    el.textContent = content;
  }
};
var _initialGuid = 3;
var _guid = _initialGuid;
function newGUID() {
  return _guid++;
}
var FakeWeakMap;
if (!import_window6.default.WeakMap) {
  FakeWeakMap = /* @__PURE__ */ function() {
    function FakeWeakMap2() {
      this.vdata = "vdata" + Math.floor(import_window6.default.performance && import_window6.default.performance.now() || Date.now());
      this.data = {};
    }
    var _proto = FakeWeakMap2.prototype;
    _proto.set = function set4(key, value) {
      var access = key[this.vdata] || newGUID();
      if (!key[this.vdata]) {
        key[this.vdata] = access;
      }
      this.data[access] = value;
      return this;
    };
    _proto.get = function get7(key) {
      var access = key[this.vdata];
      if (access) {
        return this.data[access];
      }
      log$1("We have no data for this element", key);
      return void 0;
    };
    _proto.has = function has(key) {
      var access = key[this.vdata];
      return access in this.data;
    };
    _proto["delete"] = function _delete(key) {
      var access = key[this.vdata];
      if (access) {
        delete this.data[access];
        delete key[this.vdata];
      }
    };
    return FakeWeakMap2;
  }();
}
var DomData = import_window6.default.WeakMap ? /* @__PURE__ */ new WeakMap() : new FakeWeakMap();
function _cleanUpEvents(elem, type2) {
  if (!DomData.has(elem)) {
    return;
  }
  var data = DomData.get(elem);
  if (data.handlers[type2].length === 0) {
    delete data.handlers[type2];
    if (elem.removeEventListener) {
      elem.removeEventListener(type2, data.dispatcher, false);
    } else if (elem.detachEvent) {
      elem.detachEvent("on" + type2, data.dispatcher);
    }
  }
  if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
    delete data.handlers;
    delete data.dispatcher;
    delete data.disabled;
  }
  if (Object.getOwnPropertyNames(data).length === 0) {
    DomData["delete"](elem);
  }
}
function _handleMultipleEvents(fn, elem, types, callback2) {
  types.forEach(function(type2) {
    fn(elem, type2, callback2);
  });
}
function fixEvent(event) {
  if (event.fixed_) {
    return event;
  }
  function returnTrue() {
    return true;
  }
  function returnFalse() {
    return false;
  }
  if (!event || !event.isPropagationStopped || !event.isImmediatePropagationStopped) {
    var old = event || import_window6.default.event;
    event = {};
    for (var key in old) {
      if (key !== "layerX" && key !== "layerY" && key !== "keyLocation" && key !== "webkitMovementX" && key !== "webkitMovementY" && key !== "path") {
        if (!(key === "returnValue" && old.preventDefault)) {
          event[key] = old[key];
        }
      }
    }
    if (!event.target) {
      event.target = event.srcElement || import_document.default;
    }
    if (!event.relatedTarget) {
      event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
    }
    event.preventDefault = function() {
      if (old.preventDefault) {
        old.preventDefault();
      }
      event.returnValue = false;
      old.returnValue = false;
      event.defaultPrevented = true;
    };
    event.defaultPrevented = false;
    event.stopPropagation = function() {
      if (old.stopPropagation) {
        old.stopPropagation();
      }
      event.cancelBubble = true;
      old.cancelBubble = true;
      event.isPropagationStopped = returnTrue;
    };
    event.isPropagationStopped = returnFalse;
    event.stopImmediatePropagation = function() {
      if (old.stopImmediatePropagation) {
        old.stopImmediatePropagation();
      }
      event.isImmediatePropagationStopped = returnTrue;
      event.stopPropagation();
    };
    event.isImmediatePropagationStopped = returnFalse;
    if (event.clientX !== null && event.clientX !== void 0) {
      var doc = import_document.default.documentElement;
      var body = import_document.default.body;
      event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
      event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
    }
    event.which = event.charCode || event.keyCode;
    if (event.button !== null && event.button !== void 0) {
      event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
    }
  }
  event.fixed_ = true;
  return event;
}
var _supportsPassive;
var supportsPassive = function supportsPassive2() {
  if (typeof _supportsPassive !== "boolean") {
    _supportsPassive = false;
    try {
      var opts = Object.defineProperty({}, "passive", {
        get: function get7() {
          _supportsPassive = true;
        }
      });
      import_window6.default.addEventListener("test", null, opts);
      import_window6.default.removeEventListener("test", null, opts);
    } catch (e) {
    }
  }
  return _supportsPassive;
};
var passiveEvents = ["touchstart", "touchmove"];
function on(elem, type2, fn) {
  if (Array.isArray(type2)) {
    return _handleMultipleEvents(on, elem, type2, fn);
  }
  if (!DomData.has(elem)) {
    DomData.set(elem, {});
  }
  var data = DomData.get(elem);
  if (!data.handlers) {
    data.handlers = {};
  }
  if (!data.handlers[type2]) {
    data.handlers[type2] = [];
  }
  if (!fn.guid) {
    fn.guid = newGUID();
  }
  data.handlers[type2].push(fn);
  if (!data.dispatcher) {
    data.disabled = false;
    data.dispatcher = function(event, hash2) {
      if (data.disabled) {
        return;
      }
      event = fixEvent(event);
      var handlers = data.handlers[event.type];
      if (handlers) {
        var handlersCopy = handlers.slice(0);
        for (var m = 0, n = handlersCopy.length; m < n; m++) {
          if (event.isImmediatePropagationStopped()) {
            break;
          } else {
            try {
              handlersCopy[m].call(elem, event, hash2);
            } catch (e) {
              log$1.error(e);
            }
          }
        }
      }
    };
  }
  if (data.handlers[type2].length === 1) {
    if (elem.addEventListener) {
      var options = false;
      if (supportsPassive() && passiveEvents.indexOf(type2) > -1) {
        options = {
          passive: true
        };
      }
      elem.addEventListener(type2, data.dispatcher, options);
    } else if (elem.attachEvent) {
      elem.attachEvent("on" + type2, data.dispatcher);
    }
  }
}
function off(elem, type2, fn) {
  if (!DomData.has(elem)) {
    return;
  }
  var data = DomData.get(elem);
  if (!data.handlers) {
    return;
  }
  if (Array.isArray(type2)) {
    return _handleMultipleEvents(off, elem, type2, fn);
  }
  var removeType = function removeType2(el, t3) {
    data.handlers[t3] = [];
    _cleanUpEvents(el, t3);
  };
  if (type2 === void 0) {
    for (var t2 in data.handlers) {
      if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t2)) {
        removeType(elem, t2);
      }
    }
    return;
  }
  var handlers = data.handlers[type2];
  if (!handlers) {
    return;
  }
  if (!fn) {
    removeType(elem, type2);
    return;
  }
  if (fn.guid) {
    for (var n = 0; n < handlers.length; n++) {
      if (handlers[n].guid === fn.guid) {
        handlers.splice(n--, 1);
      }
    }
  }
  _cleanUpEvents(elem, type2);
}
function trigger(elem, event, hash2) {
  var elemData = DomData.has(elem) ? DomData.get(elem) : {};
  var parent = elem.parentNode || elem.ownerDocument;
  if (typeof event === "string") {
    event = {
      type: event,
      target: elem
    };
  } else if (!event.target) {
    event.target = elem;
  }
  event = fixEvent(event);
  if (elemData.dispatcher) {
    elemData.dispatcher.call(elem, event, hash2);
  }
  if (parent && !event.isPropagationStopped() && event.bubbles === true) {
    trigger.call(null, parent, event, hash2);
  } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {
    if (!DomData.has(event.target)) {
      DomData.set(event.target, {});
    }
    var targetData = DomData.get(event.target);
    if (event.target[event.type]) {
      targetData.disabled = true;
      if (typeof event.target[event.type] === "function") {
        event.target[event.type]();
      }
      targetData.disabled = false;
    }
  }
  return !event.defaultPrevented;
}
function one(elem, type2, fn) {
  if (Array.isArray(type2)) {
    return _handleMultipleEvents(one, elem, type2, fn);
  }
  var func = function func2() {
    off(elem, type2, func2);
    fn.apply(this, arguments);
  };
  func.guid = fn.guid = fn.guid || newGUID();
  on(elem, type2, func);
}
function any(elem, type2, fn) {
  var func = function func2() {
    off(elem, type2, func2);
    fn.apply(this, arguments);
  };
  func.guid = fn.guid = fn.guid || newGUID();
  on(elem, type2, func);
}
var Events2 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  fixEvent,
  on,
  off,
  trigger,
  one,
  any
});
var UPDATE_REFRESH_INTERVAL = 30;
var bind = function bind2(context, fn, uid) {
  if (!fn.guid) {
    fn.guid = newGUID();
  }
  var bound = fn.bind(context);
  bound.guid = uid ? uid + "_" + fn.guid : fn.guid;
  return bound;
};
var throttle = function throttle2(fn, wait) {
  var last = import_window6.default.performance.now();
  var throttled = function throttled2() {
    var now2 = import_window6.default.performance.now();
    if (now2 - last >= wait) {
      fn.apply(void 0, arguments);
      last = now2;
    }
  };
  return throttled;
};
var debounce = function debounce2(func, wait, immediate, context) {
  if (context === void 0) {
    context = import_window6.default;
  }
  var timeout;
  var cancel = function cancel2() {
    context.clearTimeout(timeout);
    timeout = null;
  };
  var debounced = function debounced2() {
    var self2 = this;
    var args = arguments;
    var _later = function later() {
      timeout = null;
      _later = null;
      if (!immediate) {
        func.apply(self2, args);
      }
    };
    if (!timeout && immediate) {
      func.apply(self2, args);
    }
    context.clearTimeout(timeout);
    timeout = context.setTimeout(_later, wait);
  };
  debounced.cancel = cancel;
  return debounced;
};
var EventTarget$2 = function EventTarget() {
};
EventTarget$2.prototype.allowedEvents_ = {};
EventTarget$2.prototype.on = function(type2, fn) {
  var ael = this.addEventListener;
  this.addEventListener = function() {
  };
  on(this, type2, fn);
  this.addEventListener = ael;
};
EventTarget$2.prototype.addEventListener = EventTarget$2.prototype.on;
EventTarget$2.prototype.off = function(type2, fn) {
  off(this, type2, fn);
};
EventTarget$2.prototype.removeEventListener = EventTarget$2.prototype.off;
EventTarget$2.prototype.one = function(type2, fn) {
  var ael = this.addEventListener;
  this.addEventListener = function() {
  };
  one(this, type2, fn);
  this.addEventListener = ael;
};
EventTarget$2.prototype.any = function(type2, fn) {
  var ael = this.addEventListener;
  this.addEventListener = function() {
  };
  any(this, type2, fn);
  this.addEventListener = ael;
};
EventTarget$2.prototype.trigger = function(event) {
  var type2 = event.type || event;
  if (typeof event === "string") {
    event = {
      type: type2
    };
  }
  event = fixEvent(event);
  if (this.allowedEvents_[type2] && this["on" + type2]) {
    this["on" + type2](event);
  }
  trigger(this, event);
};
EventTarget$2.prototype.dispatchEvent = EventTarget$2.prototype.trigger;
var EVENT_MAP;
EventTarget$2.prototype.queueTrigger = function(event) {
  var _this = this;
  if (!EVENT_MAP) {
    EVENT_MAP = /* @__PURE__ */ new Map();
  }
  var type2 = event.type || event;
  var map = EVENT_MAP.get(this);
  if (!map) {
    map = /* @__PURE__ */ new Map();
    EVENT_MAP.set(this, map);
  }
  var oldTimeout = map.get(type2);
  map["delete"](type2);
  import_window6.default.clearTimeout(oldTimeout);
  var timeout = import_window6.default.setTimeout(function() {
    if (map.size === 0) {
      map = null;
      EVENT_MAP["delete"](_this);
    }
    _this.trigger(event);
  }, 0);
  map.set(type2, timeout);
};
var objName = function objName2(obj) {
  if (typeof obj.name === "function") {
    return obj.name();
  }
  if (typeof obj.name === "string") {
    return obj.name;
  }
  if (obj.name_) {
    return obj.name_;
  }
  if (obj.constructor && obj.constructor.name) {
    return obj.constructor.name;
  }
  return typeof obj;
};
var isEvented = function isEvented2(object) {
  return object instanceof EventTarget$2 || !!object.eventBusEl_ && ["on", "one", "off", "trigger"].every(function(k) {
    return typeof object[k] === "function";
  });
};
var addEventedCallback = function addEventedCallback2(target, callback2) {
  if (isEvented(target)) {
    callback2();
  } else {
    if (!target.eventedCallbacks) {
      target.eventedCallbacks = [];
    }
    target.eventedCallbacks.push(callback2);
  }
};
var isValidEventType = function isValidEventType2(type2) {
  return (
    // The regex here verifies that the `type` contains at least one non-
    // whitespace character.
    typeof type2 === "string" && /\S/.test(type2) || Array.isArray(type2) && !!type2.length
  );
};
var validateTarget = function validateTarget2(target, obj, fnName) {
  if (!target || !target.nodeName && !isEvented(target)) {
    throw new Error("Invalid target for " + objName(obj) + "#" + fnName + "; must be a DOM node or evented object.");
  }
};
var validateEventType = function validateEventType2(type2, obj, fnName) {
  if (!isValidEventType(type2)) {
    throw new Error("Invalid event type for " + objName(obj) + "#" + fnName + "; must be a non-empty string or array.");
  }
};
var validateListener = function validateListener2(listener, obj, fnName) {
  if (typeof listener !== "function") {
    throw new Error("Invalid listener for " + objName(obj) + "#" + fnName + "; must be a function.");
  }
};
var normalizeListenArgs = function normalizeListenArgs2(self2, args, fnName) {
  var isTargetingSelf = args.length < 3 || args[0] === self2 || args[0] === self2.eventBusEl_;
  var target;
  var type2;
  var listener;
  if (isTargetingSelf) {
    target = self2.eventBusEl_;
    if (args.length >= 3) {
      args.shift();
    }
    type2 = args[0];
    listener = args[1];
  } else {
    target = args[0];
    type2 = args[1];
    listener = args[2];
  }
  validateTarget(target, self2, fnName);
  validateEventType(type2, self2, fnName);
  validateListener(listener, self2, fnName);
  listener = bind(self2, listener);
  return {
    isTargetingSelf,
    target,
    type: type2,
    listener
  };
};
var listen = function listen2(target, method, type2, listener) {
  validateTarget(target, target, method);
  if (target.nodeName) {
    Events2[method](target, type2, listener);
  } else {
    target[method](type2, listener);
  }
};
var EventedMixin = {
  /**
   * Add a listener to an event (or events) on this object or another evented
   * object.
   *
   * @param  {string|Array|Element|Object} targetOrType
   *         If this is a string or array, it represents the event type(s)
   *         that will trigger the listener.
   *
   *         Another evented object can be passed here instead, which will
   *         cause the listener to listen for events on _that_ object.
   *
   *         In either case, the listener's `this` value will be bound to
   *         this object.
   *
   * @param  {string|Array|Function} typeOrListener
   *         If the first argument was a string or array, this should be the
   *         listener function. Otherwise, this is a string or array of event
   *         type(s).
   *
   * @param  {Function} [listener]
   *         If the first argument was another evented object, this will be
   *         the listener function.
   */
  on: function on2() {
    var _this = this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    var _normalizeListenArgs = normalizeListenArgs(this, args, "on"), isTargetingSelf = _normalizeListenArgs.isTargetingSelf, target = _normalizeListenArgs.target, type2 = _normalizeListenArgs.type, listener = _normalizeListenArgs.listener;
    listen(target, "on", type2, listener);
    if (!isTargetingSelf) {
      var removeListenerOnDispose = function removeListenerOnDispose2() {
        return _this.off(target, type2, listener);
      };
      removeListenerOnDispose.guid = listener.guid;
      var removeRemoverOnTargetDispose = function removeRemoverOnTargetDispose2() {
        return _this.off("dispose", removeListenerOnDispose);
      };
      removeRemoverOnTargetDispose.guid = listener.guid;
      listen(this, "on", "dispose", removeListenerOnDispose);
      listen(target, "on", "dispose", removeRemoverOnTargetDispose);
    }
  },
  /**
   * Add a listener to an event (or events) on this object or another evented
   * object. The listener will be called once per event and then removed.
   *
   * @param  {string|Array|Element|Object} targetOrType
   *         If this is a string or array, it represents the event type(s)
   *         that will trigger the listener.
   *
   *         Another evented object can be passed here instead, which will
   *         cause the listener to listen for events on _that_ object.
   *
   *         In either case, the listener's `this` value will be bound to
   *         this object.
   *
   * @param  {string|Array|Function} typeOrListener
   *         If the first argument was a string or array, this should be the
   *         listener function. Otherwise, this is a string or array of event
   *         type(s).
   *
   * @param  {Function} [listener]
   *         If the first argument was another evented object, this will be
   *         the listener function.
   */
  one: function one2() {
    var _this2 = this;
    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }
    var _normalizeListenArgs2 = normalizeListenArgs(this, args, "one"), isTargetingSelf = _normalizeListenArgs2.isTargetingSelf, target = _normalizeListenArgs2.target, type2 = _normalizeListenArgs2.type, listener = _normalizeListenArgs2.listener;
    if (isTargetingSelf) {
      listen(target, "one", type2, listener);
    } else {
      var wrapper = function wrapper2() {
        _this2.off(target, type2, wrapper2);
        for (var _len3 = arguments.length, largs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
          largs[_key3] = arguments[_key3];
        }
        listener.apply(null, largs);
      };
      wrapper.guid = listener.guid;
      listen(target, "one", type2, wrapper);
    }
  },
  /**
   * Add a listener to an event (or events) on this object or another evented
   * object. The listener will only be called once for the first event that is triggered
   * then removed.
   *
   * @param  {string|Array|Element|Object} targetOrType
   *         If this is a string or array, it represents the event type(s)
   *         that will trigger the listener.
   *
   *         Another evented object can be passed here instead, which will
   *         cause the listener to listen for events on _that_ object.
   *
   *         In either case, the listener's `this` value will be bound to
   *         this object.
   *
   * @param  {string|Array|Function} typeOrListener
   *         If the first argument was a string or array, this should be the
   *         listener function. Otherwise, this is a string or array of event
   *         type(s).
   *
   * @param  {Function} [listener]
   *         If the first argument was another evented object, this will be
   *         the listener function.
   */
  any: function any2() {
    var _this3 = this;
    for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
      args[_key4] = arguments[_key4];
    }
    var _normalizeListenArgs3 = normalizeListenArgs(this, args, "any"), isTargetingSelf = _normalizeListenArgs3.isTargetingSelf, target = _normalizeListenArgs3.target, type2 = _normalizeListenArgs3.type, listener = _normalizeListenArgs3.listener;
    if (isTargetingSelf) {
      listen(target, "any", type2, listener);
    } else {
      var wrapper = function wrapper2() {
        _this3.off(target, type2, wrapper2);
        for (var _len5 = arguments.length, largs = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
          largs[_key5] = arguments[_key5];
        }
        listener.apply(null, largs);
      };
      wrapper.guid = listener.guid;
      listen(target, "any", type2, wrapper);
    }
  },
  /**
   * Removes listener(s) from event(s) on an evented object.
   *
   * @param  {string|Array|Element|Object} [targetOrType]
   *         If this is a string or array, it represents the event type(s).
   *
   *         Another evented object can be passed here instead, in which case
   *         ALL 3 arguments are _required_.
   *
   * @param  {string|Array|Function} [typeOrListener]
   *         If the first argument was a string or array, this may be the
   *         listener function. Otherwise, this is a string or array of event
   *         type(s).
   *
   * @param  {Function} [listener]
   *         If the first argument was another evented object, this will be
   *         the listener function; otherwise, _all_ listeners bound to the
   *         event type(s) will be removed.
   */
  off: function off$1(targetOrType, typeOrListener, listener) {
    if (!targetOrType || isValidEventType(targetOrType)) {
      off(this.eventBusEl_, targetOrType, typeOrListener);
    } else {
      var target = targetOrType;
      var type2 = typeOrListener;
      validateTarget(target, this, "off");
      validateEventType(type2, this, "off");
      validateListener(listener, this, "off");
      listener = bind(this, listener);
      this.off("dispose", listener);
      if (target.nodeName) {
        off(target, type2, listener);
        off(target, "dispose", listener);
      } else if (isEvented(target)) {
        target.off(type2, listener);
        target.off("dispose", listener);
      }
    }
  },
  /**
   * Fire an event on this evented object, causing its listeners to be called.
   *
   * @param   {string|Object} event
   *          An event type or an object with a type property.
   *
   * @param   {Object} [hash]
   *          An additional object to pass along to listeners.
   *
   * @return {boolean}
   *          Whether or not the default behavior was prevented.
   */
  trigger: function trigger$1(event, hash2) {
    validateTarget(this.eventBusEl_, this, "trigger");
    var type2 = event && typeof event !== "string" ? event.type : event;
    if (!isValidEventType(type2)) {
      var error = "Invalid event type for " + objName(this) + "#trigger; must be a non-empty string or object with a type key that has a non-empty value.";
      if (event) {
        (this.log || log$1).error(error);
      } else {
        throw new Error(error);
      }
    }
    return trigger(this.eventBusEl_, event, hash2);
  }
};
function evented(target, options) {
  if (options === void 0) {
    options = {};
  }
  var _options = options, eventBusKey = _options.eventBusKey;
  if (eventBusKey) {
    if (!target[eventBusKey].nodeName) {
      throw new Error('The eventBusKey "' + eventBusKey + '" does not refer to an element.');
    }
    target.eventBusEl_ = target[eventBusKey];
  } else {
    target.eventBusEl_ = createEl("span", {
      className: "vjs-event-bus"
    });
  }
  assign(target, EventedMixin);
  if (target.eventedCallbacks) {
    target.eventedCallbacks.forEach(function(callback2) {
      callback2();
    });
  }
  target.on("dispose", function() {
    target.off();
    [target, target.el_, target.eventBusEl_].forEach(function(val) {
      if (val && DomData.has(val)) {
        DomData["delete"](val);
      }
    });
    import_window6.default.setTimeout(function() {
      target.eventBusEl_ = null;
    }, 0);
  });
  return target;
}
var StatefulMixin = {
  /**
   * A hash containing arbitrary keys and values representing the state of
   * the object.
   *
   * @type {Object}
   */
  state: {},
  /**
   * Set the state of an object by mutating its
   * {@link module:stateful~StatefulMixin.state|state} object in place.
   *
   * @fires   module:stateful~StatefulMixin#statechanged
   * @param   {Object|Function} stateUpdates
   *          A new set of properties to shallow-merge into the plugin state.
   *          Can be a plain object or a function returning a plain object.
   *
   * @return {Object|undefined}
   *          An object containing changes that occurred. If no changes
   *          occurred, returns `undefined`.
   */
  setState: function setState(stateUpdates) {
    var _this = this;
    if (typeof stateUpdates === "function") {
      stateUpdates = stateUpdates();
    }
    var changes;
    each(stateUpdates, function(value, key) {
      if (_this.state[key] !== value) {
        changes = changes || {};
        changes[key] = {
          from: _this.state[key],
          to: value
        };
      }
      _this.state[key] = value;
    });
    if (changes && isEvented(this)) {
      this.trigger({
        changes,
        type: "statechanged"
      });
    }
    return changes;
  }
};
function stateful(target, defaultState) {
  assign(target, StatefulMixin);
  target.state = assign({}, target.state, defaultState);
  if (typeof target.handleStateChanged === "function" && isEvented(target)) {
    target.on("statechanged", target.handleStateChanged);
  }
  return target;
}
var toLowerCase = function toLowerCase2(string) {
  if (typeof string !== "string") {
    return string;
  }
  return string.replace(/./, function(w) {
    return w.toLowerCase();
  });
};
var toTitleCase$1 = function toTitleCase(string) {
  if (typeof string !== "string") {
    return string;
  }
  return string.replace(/./, function(w) {
    return w.toUpperCase();
  });
};
var titleCaseEquals = function titleCaseEquals2(str1, str2) {
  return toTitleCase$1(str1) === toTitleCase$1(str2);
};
function mergeOptions$3() {
  var result = {};
  for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) {
    sources[_key] = arguments[_key];
  }
  sources.forEach(function(source) {
    if (!source) {
      return;
    }
    each(source, function(value, key) {
      if (!isPlain(value)) {
        result[key] = value;
        return;
      }
      if (!isPlain(result[key])) {
        result[key] = {};
      }
      result[key] = mergeOptions$3(result[key], value);
    });
  });
  return result;
}
var MapSham = /* @__PURE__ */ function() {
  function MapSham2() {
    this.map_ = {};
  }
  var _proto = MapSham2.prototype;
  _proto.has = function has(key) {
    return key in this.map_;
  };
  _proto["delete"] = function _delete(key) {
    var has = this.has(key);
    delete this.map_[key];
    return has;
  };
  _proto.set = function set4(key, value) {
    this.map_[key] = value;
    return this;
  };
  _proto.forEach = function forEach(callback2, thisArg) {
    for (var key in this.map_) {
      callback2.call(thisArg, this.map_[key], key, this);
    }
  };
  return MapSham2;
}();
var Map$1 = import_window6.default.Map ? import_window6.default.Map : MapSham;
var SetSham = /* @__PURE__ */ function() {
  function SetSham2() {
    this.set_ = {};
  }
  var _proto = SetSham2.prototype;
  _proto.has = function has(key) {
    return key in this.set_;
  };
  _proto["delete"] = function _delete(key) {
    var has = this.has(key);
    delete this.set_[key];
    return has;
  };
  _proto.add = function add(key) {
    this.set_[key] = 1;
    return this;
  };
  _proto.forEach = function forEach(callback2, thisArg) {
    for (var key in this.set_) {
      callback2.call(thisArg, key, key, this);
    }
  };
  return SetSham2;
}();
var Set$1 = import_window6.default.Set ? import_window6.default.Set : SetSham;
var Component$1 = /* @__PURE__ */ function() {
  function Component4(player, options, ready) {
    var _this = this;
    if (!player && this.play) {
      this.player_ = player = this;
    } else {
      this.player_ = player;
    }
    this.isDisposed_ = false;
    this.parentComponent_ = null;
    this.options_ = mergeOptions$3({}, this.options_);
    options = this.options_ = mergeOptions$3(this.options_, options);
    this.id_ = options.id || options.el && options.el.id;
    if (!this.id_) {
      var id = player && player.id && player.id() || "no_player";
      this.id_ = id + "_component_" + newGUID();
    }
    this.name_ = options.name || null;
    if (options.el) {
      this.el_ = options.el;
    } else if (options.createEl !== false) {
      this.el_ = this.createEl();
    }
    if (options.className && this.el_) {
      options.className.split(" ").forEach(function(c) {
        return _this.addClass(c);
      });
    }
    if (options.evented !== false) {
      evented(this, {
        eventBusKey: this.el_ ? "el_" : null
      });
      this.handleLanguagechange = this.handleLanguagechange.bind(this);
      this.on(this.player_, "languagechange", this.handleLanguagechange);
    }
    stateful(this, this.constructor.defaultState);
    this.children_ = [];
    this.childIndex_ = {};
    this.childNameIndex_ = {};
    this.setTimeoutIds_ = new Set$1();
    this.setIntervalIds_ = new Set$1();
    this.rafIds_ = new Set$1();
    this.namedRafs_ = new Map$1();
    this.clearingTimersOnDispose_ = false;
    if (options.initChildren !== false) {
      this.initChildren();
    }
    this.ready(ready);
    if (options.reportTouchActivity !== false) {
      this.enableTouchActivity();
    }
  }
  var _proto = Component4.prototype;
  _proto.dispose = function dispose(options) {
    if (options === void 0) {
      options = {};
    }
    if (this.isDisposed_) {
      return;
    }
    if (this.readyQueue_) {
      this.readyQueue_.length = 0;
    }
    this.trigger({
      type: "dispose",
      bubbles: false
    });
    this.isDisposed_ = true;
    if (this.children_) {
      for (var i = this.children_.length - 1; i >= 0; i--) {
        if (this.children_[i].dispose) {
          this.children_[i].dispose();
        }
      }
    }
    this.children_ = null;
    this.childIndex_ = null;
    this.childNameIndex_ = null;
    this.parentComponent_ = null;
    if (this.el_) {
      if (this.el_.parentNode) {
        if (options.restoreEl) {
          this.el_.parentNode.replaceChild(options.restoreEl, this.el_);
        } else {
          this.el_.parentNode.removeChild(this.el_);
        }
      }
      this.el_ = null;
    }
    this.player_ = null;
  };
  _proto.isDisposed = function isDisposed() {
    return Boolean(this.isDisposed_);
  };
  _proto.player = function player() {
    return this.player_;
  };
  _proto.options = function options(obj) {
    if (!obj) {
      return this.options_;
    }
    this.options_ = mergeOptions$3(this.options_, obj);
    return this.options_;
  };
  _proto.el = function el() {
    return this.el_;
  };
  _proto.createEl = function createEl$1(tagName, properties, attributes) {
    return createEl(tagName, properties, attributes);
  };
  _proto.localize = function localize(string, tokens, defaultValue) {
    if (defaultValue === void 0) {
      defaultValue = string;
    }
    var code = this.player_.language && this.player_.language();
    var languages = this.player_.languages && this.player_.languages();
    var language = languages && languages[code];
    var primaryCode = code && code.split("-")[0];
    var primaryLang = languages && languages[primaryCode];
    var localizedString = defaultValue;
    if (language && language[string]) {
      localizedString = language[string];
    } else if (primaryLang && primaryLang[string]) {
      localizedString = primaryLang[string];
    }
    if (tokens) {
      localizedString = localizedString.replace(/\{(\d+)\}/g, function(match, index) {
        var value = tokens[index - 1];
        var ret = value;
        if (typeof value === "undefined") {
          ret = match;
        }
        return ret;
      });
    }
    return localizedString;
  };
  _proto.handleLanguagechange = function handleLanguagechange() {
  };
  _proto.contentEl = function contentEl() {
    return this.contentEl_ || this.el_;
  };
  _proto.id = function id() {
    return this.id_;
  };
  _proto.name = function name() {
    return this.name_;
  };
  _proto.children = function children() {
    return this.children_;
  };
  _proto.getChildById = function getChildById(id) {
    return this.childIndex_[id];
  };
  _proto.getChild = function getChild(name) {
    if (!name) {
      return;
    }
    return this.childNameIndex_[name];
  };
  _proto.getDescendant = function getDescendant() {
    for (var _len = arguments.length, names = new Array(_len), _key = 0; _key < _len; _key++) {
      names[_key] = arguments[_key];
    }
    names = names.reduce(function(acc, n) {
      return acc.concat(n);
    }, []);
    var currentChild = this;
    for (var i = 0; i < names.length; i++) {
      currentChild = currentChild.getChild(names[i]);
      if (!currentChild || !currentChild.getChild) {
        return;
      }
    }
    return currentChild;
  };
  _proto.addChild = function addChild(child, options, index) {
    if (options === void 0) {
      options = {};
    }
    if (index === void 0) {
      index = this.children_.length;
    }
    var component;
    var componentName;
    if (typeof child === "string") {
      componentName = toTitleCase$1(child);
      var componentClassName = options.componentClass || componentName;
      options.name = componentName;
      var ComponentClass = Component4.getComponent(componentClassName);
      if (!ComponentClass) {
        throw new Error("Component " + componentClassName + " does not exist");
      }
      if (typeof ComponentClass !== "function") {
        return null;
      }
      component = new ComponentClass(this.player_ || this, options);
    } else {
      component = child;
    }
    if (component.parentComponent_) {
      component.parentComponent_.removeChild(component);
    }
    this.children_.splice(index, 0, component);
    component.parentComponent_ = this;
    if (typeof component.id === "function") {
      this.childIndex_[component.id()] = component;
    }
    componentName = componentName || component.name && toTitleCase$1(component.name());
    if (componentName) {
      this.childNameIndex_[componentName] = component;
      this.childNameIndex_[toLowerCase(componentName)] = component;
    }
    if (typeof component.el === "function" && component.el()) {
      var refNode = null;
      if (this.children_[index + 1]) {
        if (this.children_[index + 1].el_) {
          refNode = this.children_[index + 1].el_;
        } else if (isEl(this.children_[index + 1])) {
          refNode = this.children_[index + 1];
        }
      }
      this.contentEl().insertBefore(component.el(), refNode);
    }
    return component;
  };
  _proto.removeChild = function removeChild(component) {
    if (typeof component === "string") {
      component = this.getChild(component);
    }
    if (!component || !this.children_) {
      return;
    }
    var childFound = false;
    for (var i = this.children_.length - 1; i >= 0; i--) {
      if (this.children_[i] === component) {
        childFound = true;
        this.children_.splice(i, 1);
        break;
      }
    }
    if (!childFound) {
      return;
    }
    component.parentComponent_ = null;
    this.childIndex_[component.id()] = null;
    this.childNameIndex_[toTitleCase$1(component.name())] = null;
    this.childNameIndex_[toLowerCase(component.name())] = null;
    var compEl = component.el();
    if (compEl && compEl.parentNode === this.contentEl()) {
      this.contentEl().removeChild(component.el());
    }
  };
  _proto.initChildren = function initChildren() {
    var _this2 = this;
    var children = this.options_.children;
    if (children) {
      var parentOptions = this.options_;
      var handleAdd = function handleAdd2(child) {
        var name = child.name;
        var opts = child.opts;
        if (parentOptions[name] !== void 0) {
          opts = parentOptions[name];
        }
        if (opts === false) {
          return;
        }
        if (opts === true) {
          opts = {};
        }
        opts.playerOptions = _this2.options_.playerOptions;
        var newChild = _this2.addChild(name, opts);
        if (newChild) {
          _this2[name] = newChild;
        }
      };
      var workingChildren;
      var Tech2 = Component4.getComponent("Tech");
      if (Array.isArray(children)) {
        workingChildren = children;
      } else {
        workingChildren = Object.keys(children);
      }
      workingChildren.concat(Object.keys(this.options_).filter(function(child) {
        return !workingChildren.some(function(wchild) {
          if (typeof wchild === "string") {
            return child === wchild;
          }
          return child === wchild.name;
        });
      })).map(function(child) {
        var name;
        var opts;
        if (typeof child === "string") {
          name = child;
          opts = children[name] || _this2.options_[name] || {};
        } else {
          name = child.name;
          opts = child;
        }
        return {
          name,
          opts
        };
      }).filter(function(child) {
        var c = Component4.getComponent(child.opts.componentClass || toTitleCase$1(child.name));
        return c && !Tech2.isTech(c);
      }).forEach(handleAdd);
    }
  };
  _proto.buildCSSClass = function buildCSSClass() {
    return "";
  };
  _proto.ready = function ready(fn, sync) {
    if (sync === void 0) {
      sync = false;
    }
    if (!fn) {
      return;
    }
    if (!this.isReady_) {
      this.readyQueue_ = this.readyQueue_ || [];
      this.readyQueue_.push(fn);
      return;
    }
    if (sync) {
      fn.call(this);
    } else {
      this.setTimeout(fn, 1);
    }
  };
  _proto.triggerReady = function triggerReady() {
    this.isReady_ = true;
    this.setTimeout(function() {
      var readyQueue = this.readyQueue_;
      this.readyQueue_ = [];
      if (readyQueue && readyQueue.length > 0) {
        readyQueue.forEach(function(fn) {
          fn.call(this);
        }, this);
      }
      this.trigger("ready");
    }, 1);
  };
  _proto.$ = function $$1(selector, context) {
    return $(selector, context || this.contentEl());
  };
  _proto.$$ = function $$$1(selector, context) {
    return $$(selector, context || this.contentEl());
  };
  _proto.hasClass = function hasClass$1(classToCheck) {
    return hasClass(this.el_, classToCheck);
  };
  _proto.addClass = function addClass$1(classToAdd) {
    addClass(this.el_, classToAdd);
  };
  _proto.removeClass = function removeClass$1(classToRemove) {
    removeClass(this.el_, classToRemove);
  };
  _proto.toggleClass = function toggleClass$1(classToToggle, predicate) {
    toggleClass(this.el_, classToToggle, predicate);
  };
  _proto.show = function show() {
    this.removeClass("vjs-hidden");
  };
  _proto.hide = function hide() {
    this.addClass("vjs-hidden");
  };
  _proto.lockShowing = function lockShowing() {
    this.addClass("vjs-lock-showing");
  };
  _proto.unlockShowing = function unlockShowing() {
    this.removeClass("vjs-lock-showing");
  };
  _proto.getAttribute = function getAttribute$1(attribute) {
    return getAttribute(this.el_, attribute);
  };
  _proto.setAttribute = function setAttribute$1(attribute, value) {
    setAttribute(this.el_, attribute, value);
  };
  _proto.removeAttribute = function removeAttribute$1(attribute) {
    removeAttribute(this.el_, attribute);
  };
  _proto.width = function width2(num, skipListeners) {
    return this.dimension("width", num, skipListeners);
  };
  _proto.height = function height2(num, skipListeners) {
    return this.dimension("height", num, skipListeners);
  };
  _proto.dimensions = function dimensions(width2, height2) {
    this.width(width2, true);
    this.height(height2);
  };
  _proto.dimension = function dimension(widthOrHeight, num, skipListeners) {
    if (num !== void 0) {
      if (num === null || num !== num) {
        num = 0;
      }
      if (("" + num).indexOf("%") !== -1 || ("" + num).indexOf("px") !== -1) {
        this.el_.style[widthOrHeight] = num;
      } else if (num === "auto") {
        this.el_.style[widthOrHeight] = "";
      } else {
        this.el_.style[widthOrHeight] = num + "px";
      }
      if (!skipListeners) {
        this.trigger("componentresize");
      }
      return;
    }
    if (!this.el_) {
      return 0;
    }
    var val = this.el_.style[widthOrHeight];
    var pxIndex = val.indexOf("px");
    if (pxIndex !== -1) {
      return parseInt(val.slice(0, pxIndex), 10);
    }
    return parseInt(this.el_["offset" + toTitleCase$1(widthOrHeight)], 10);
  };
  _proto.currentDimension = function currentDimension(widthOrHeight) {
    var computedWidthOrHeight = 0;
    if (widthOrHeight !== "width" && widthOrHeight !== "height") {
      throw new Error("currentDimension only accepts width or height value");
    }
    computedWidthOrHeight = computedStyle(this.el_, widthOrHeight);
    computedWidthOrHeight = parseFloat(computedWidthOrHeight);
    if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) {
      var rule = "offset" + toTitleCase$1(widthOrHeight);
      computedWidthOrHeight = this.el_[rule];
    }
    return computedWidthOrHeight;
  };
  _proto.currentDimensions = function currentDimensions() {
    return {
      width: this.currentDimension("width"),
      height: this.currentDimension("height")
    };
  };
  _proto.currentWidth = function currentWidth() {
    return this.currentDimension("width");
  };
  _proto.currentHeight = function currentHeight() {
    return this.currentDimension("height");
  };
  _proto.focus = function focus() {
    this.el_.focus();
  };
  _proto.blur = function blur() {
    this.el_.blur();
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    if (this.player_) {
      if (!import_keycode.default.isEventKey(event, "Tab")) {
        event.stopPropagation();
      }
      this.player_.handleKeyDown(event);
    }
  };
  _proto.handleKeyPress = function handleKeyPress(event) {
    this.handleKeyDown(event);
  };
  _proto.emitTapEvents = function emitTapEvents() {
    var touchStart = 0;
    var firstTouch = null;
    var tapMovementThreshold = 10;
    var touchTimeThreshold = 200;
    var couldBeTap;
    this.on("touchstart", function(event) {
      if (event.touches.length === 1) {
        firstTouch = {
          pageX: event.touches[0].pageX,
          pageY: event.touches[0].pageY
        };
        touchStart = import_window6.default.performance.now();
        couldBeTap = true;
      }
    });
    this.on("touchmove", function(event) {
      if (event.touches.length > 1) {
        couldBeTap = false;
      } else if (firstTouch) {
        var xdiff = event.touches[0].pageX - firstTouch.pageX;
        var ydiff = event.touches[0].pageY - firstTouch.pageY;
        var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
        if (touchDistance > tapMovementThreshold) {
          couldBeTap = false;
        }
      }
    });
    var noTap = function noTap2() {
      couldBeTap = false;
    };
    this.on("touchleave", noTap);
    this.on("touchcancel", noTap);
    this.on("touchend", function(event) {
      firstTouch = null;
      if (couldBeTap === true) {
        var touchTime = import_window6.default.performance.now() - touchStart;
        if (touchTime < touchTimeThreshold) {
          event.preventDefault();
          this.trigger("tap");
        }
      }
    });
  };
  _proto.enableTouchActivity = function enableTouchActivity() {
    if (!this.player() || !this.player().reportUserActivity) {
      return;
    }
    var report = bind(this.player(), this.player().reportUserActivity);
    var touchHolding;
    this.on("touchstart", function() {
      report();
      this.clearInterval(touchHolding);
      touchHolding = this.setInterval(report, 250);
    });
    var touchEnd = function touchEnd2(event) {
      report();
      this.clearInterval(touchHolding);
    };
    this.on("touchmove", report);
    this.on("touchend", touchEnd);
    this.on("touchcancel", touchEnd);
  };
  _proto.setTimeout = function setTimeout2(fn, timeout) {
    var _this3 = this;
    var timeoutId;
    fn = bind(this, fn);
    this.clearTimersOnDispose_();
    timeoutId = import_window6.default.setTimeout(function() {
      if (_this3.setTimeoutIds_.has(timeoutId)) {
        _this3.setTimeoutIds_["delete"](timeoutId);
      }
      fn();
    }, timeout);
    this.setTimeoutIds_.add(timeoutId);
    return timeoutId;
  };
  _proto.clearTimeout = function clearTimeout2(timeoutId) {
    if (this.setTimeoutIds_.has(timeoutId)) {
      this.setTimeoutIds_["delete"](timeoutId);
      import_window6.default.clearTimeout(timeoutId);
    }
    return timeoutId;
  };
  _proto.setInterval = function setInterval2(fn, interval) {
    fn = bind(this, fn);
    this.clearTimersOnDispose_();
    var intervalId = import_window6.default.setInterval(fn, interval);
    this.setIntervalIds_.add(intervalId);
    return intervalId;
  };
  _proto.clearInterval = function clearInterval2(intervalId) {
    if (this.setIntervalIds_.has(intervalId)) {
      this.setIntervalIds_["delete"](intervalId);
      import_window6.default.clearInterval(intervalId);
    }
    return intervalId;
  };
  _proto.requestAnimationFrame = function requestAnimationFrame2(fn) {
    var _this4 = this;
    if (!this.supportsRaf_) {
      return this.setTimeout(fn, 1e3 / 60);
    }
    this.clearTimersOnDispose_();
    var id;
    fn = bind(this, fn);
    id = import_window6.default.requestAnimationFrame(function() {
      if (_this4.rafIds_.has(id)) {
        _this4.rafIds_["delete"](id);
      }
      fn();
    });
    this.rafIds_.add(id);
    return id;
  };
  _proto.requestNamedAnimationFrame = function requestNamedAnimationFrame(name, fn) {
    var _this5 = this;
    if (this.namedRafs_.has(name)) {
      return;
    }
    this.clearTimersOnDispose_();
    fn = bind(this, fn);
    var id = this.requestAnimationFrame(function() {
      fn();
      if (_this5.namedRafs_.has(name)) {
        _this5.namedRafs_["delete"](name);
      }
    });
    this.namedRafs_.set(name, id);
    return name;
  };
  _proto.cancelNamedAnimationFrame = function cancelNamedAnimationFrame(name) {
    if (!this.namedRafs_.has(name)) {
      return;
    }
    this.cancelAnimationFrame(this.namedRafs_.get(name));
    this.namedRafs_["delete"](name);
  };
  _proto.cancelAnimationFrame = function cancelAnimationFrame2(id) {
    if (!this.supportsRaf_) {
      return this.clearTimeout(id);
    }
    if (this.rafIds_.has(id)) {
      this.rafIds_["delete"](id);
      import_window6.default.cancelAnimationFrame(id);
    }
    return id;
  };
  _proto.clearTimersOnDispose_ = function clearTimersOnDispose_() {
    var _this6 = this;
    if (this.clearingTimersOnDispose_) {
      return;
    }
    this.clearingTimersOnDispose_ = true;
    this.one("dispose", function() {
      [["namedRafs_", "cancelNamedAnimationFrame"], ["rafIds_", "cancelAnimationFrame"], ["setTimeoutIds_", "clearTimeout"], ["setIntervalIds_", "clearInterval"]].forEach(function(_ref) {
        var idName = _ref[0], cancelName = _ref[1];
        _this6[idName].forEach(function(val, key) {
          return _this6[cancelName](key);
        });
      });
      _this6.clearingTimersOnDispose_ = false;
    });
  };
  Component4.registerComponent = function registerComponent(name, ComponentToRegister) {
    if (typeof name !== "string" || !name) {
      throw new Error('Illegal component name, "' + name + '"; must be a non-empty string.');
    }
    var Tech2 = Component4.getComponent("Tech");
    var isTech = Tech2 && Tech2.isTech(ComponentToRegister);
    var isComp = Component4 === ComponentToRegister || Component4.prototype.isPrototypeOf(ComponentToRegister.prototype);
    if (isTech || !isComp) {
      var reason;
      if (isTech) {
        reason = "techs must be registered using Tech.registerTech()";
      } else {
        reason = "must be a Component subclass";
      }
      throw new Error('Illegal component, "' + name + '"; ' + reason + ".");
    }
    name = toTitleCase$1(name);
    if (!Component4.components_) {
      Component4.components_ = {};
    }
    var Player2 = Component4.getComponent("Player");
    if (name === "Player" && Player2 && Player2.players) {
      var players = Player2.players;
      var playerNames = Object.keys(players);
      if (players && playerNames.length > 0 && playerNames.map(function(pname) {
        return players[pname];
      }).every(Boolean)) {
        throw new Error("Can not register Player component after player has been created.");
      }
    }
    Component4.components_[name] = ComponentToRegister;
    Component4.components_[toLowerCase(name)] = ComponentToRegister;
    return ComponentToRegister;
  };
  Component4.getComponent = function getComponent(name) {
    if (!name || !Component4.components_) {
      return;
    }
    return Component4.components_[name];
  };
  return Component4;
}();
Component$1.prototype.supportsRaf_ = typeof import_window6.default.requestAnimationFrame === "function" && typeof import_window6.default.cancelAnimationFrame === "function";
Component$1.registerComponent("Component", Component$1);
function rangeCheck(fnName, index, maxIndex) {
  if (typeof index !== "number" || index < 0 || index > maxIndex) {
    throw new Error("Failed to execute '" + fnName + "' on 'TimeRanges': The index provided (" + index + ") is non-numeric or out of bounds (0-" + maxIndex + ").");
  }
}
function getRange(fnName, valueIndex, ranges, rangeIndex) {
  rangeCheck(fnName, rangeIndex, ranges.length - 1);
  return ranges[rangeIndex][valueIndex];
}
function createTimeRangesObj(ranges) {
  var timeRangesObj;
  if (ranges === void 0 || ranges.length === 0) {
    timeRangesObj = {
      length: 0,
      start: function start2() {
        throw new Error("This TimeRanges object is empty");
      },
      end: function end() {
        throw new Error("This TimeRanges object is empty");
      }
    };
  } else {
    timeRangesObj = {
      length: ranges.length,
      start: getRange.bind(null, "start", 0, ranges),
      end: getRange.bind(null, "end", 1, ranges)
    };
  }
  if (import_window6.default.Symbol && import_window6.default.Symbol.iterator) {
    timeRangesObj[import_window6.default.Symbol.iterator] = function() {
      return (ranges || []).values();
    };
  }
  return timeRangesObj;
}
function createTimeRanges(start2, end) {
  if (Array.isArray(start2)) {
    return createTimeRangesObj(start2);
  } else if (start2 === void 0 || end === void 0) {
    return createTimeRangesObj();
  }
  return createTimeRangesObj([[start2, end]]);
}
function bufferedPercent(buffered, duration5) {
  var bufferedDuration = 0;
  var start2;
  var end;
  if (!duration5) {
    return 0;
  }
  if (!buffered || !buffered.length) {
    buffered = createTimeRanges(0, 0);
  }
  for (var i = 0; i < buffered.length; i++) {
    start2 = buffered.start(i);
    end = buffered.end(i);
    if (end > duration5) {
      end = duration5;
    }
    bufferedDuration += end - start2;
  }
  return bufferedDuration / duration5;
}
function MediaError(value) {
  if (value instanceof MediaError) {
    return value;
  }
  if (typeof value === "number") {
    this.code = value;
  } else if (typeof value === "string") {
    this.message = value;
  } else if (isObject3(value)) {
    if (typeof value.code === "number") {
      this.code = value.code;
    }
    assign(this, value);
  }
  if (!this.message) {
    this.message = MediaError.defaultMessages[this.code] || "";
  }
}
MediaError.prototype.code = 0;
MediaError.prototype.message = "";
MediaError.prototype.status = null;
MediaError.errorTypes = ["MEDIA_ERR_CUSTOM", "MEDIA_ERR_ABORTED", "MEDIA_ERR_NETWORK", "MEDIA_ERR_DECODE", "MEDIA_ERR_SRC_NOT_SUPPORTED", "MEDIA_ERR_ENCRYPTED"];
MediaError.defaultMessages = {
  1: "You aborted the media playback",
  2: "A network error caused the media download to fail part-way.",
  3: "The media playback was aborted due to a corruption problem or because the media used features your browser did not support.",
  4: "The media could not be loaded, either because the server or network failed or because the format is not supported.",
  5: "The media is encrypted and we do not have the keys to decrypt it."
};
for (errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
  MediaError[MediaError.errorTypes[errNum]] = errNum;
  MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
}
var errNum;
function isPromise2(value) {
  return value !== void 0 && value !== null && typeof value.then === "function";
}
function silencePromise(value) {
  if (isPromise2(value)) {
    value.then(null, function(e) {
    });
  }
}
var trackToJson_ = function trackToJson_2(track) {
  var ret = ["kind", "label", "language", "id", "inBandMetadataTrackDispatchType", "mode", "src"].reduce(function(acc, prop, i) {
    if (track[prop]) {
      acc[prop] = track[prop];
    }
    return acc;
  }, {
    cues: track.cues && Array.prototype.map.call(track.cues, function(cue) {
      return {
        startTime: cue.startTime,
        endTime: cue.endTime,
        text: cue.text,
        id: cue.id
      };
    })
  });
  return ret;
};
var textTracksToJson = function textTracksToJson2(tech) {
  var trackEls = tech.$$("track");
  var trackObjs = Array.prototype.map.call(trackEls, function(t2) {
    return t2.track;
  });
  var tracks = Array.prototype.map.call(trackEls, function(trackEl) {
    var json = trackToJson_(trackEl.track);
    if (trackEl.src) {
      json.src = trackEl.src;
    }
    return json;
  });
  return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function(track) {
    return trackObjs.indexOf(track) === -1;
  }).map(trackToJson_));
};
var jsonToTextTracks = function jsonToTextTracks2(json, tech) {
  json.forEach(function(track) {
    var addedTrack = tech.addRemoteTextTrack(track).track;
    if (!track.src && track.cues) {
      track.cues.forEach(function(cue) {
        return addedTrack.addCue(cue);
      });
    }
  });
  return tech.textTracks();
};
var textTrackConverter = {
  textTracksToJson,
  jsonToTextTracks,
  trackToJson_
};
var MODAL_CLASS_NAME = "vjs-modal-dialog";
var ModalDialog = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(ModalDialog2, _Component);
  function ModalDialog2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    _this.handleKeyDown_ = function(e) {
      return _this.handleKeyDown(e);
    };
    _this.close_ = function(e) {
      return _this.close(e);
    };
    _this.opened_ = _this.hasBeenOpened_ = _this.hasBeenFilled_ = false;
    _this.closeable(!_this.options_.uncloseable);
    _this.content(_this.options_.content);
    _this.contentEl_ = createEl("div", {
      className: MODAL_CLASS_NAME + "-content"
    }, {
      role: "document"
    });
    _this.descEl_ = createEl("p", {
      className: MODAL_CLASS_NAME + "-description vjs-control-text",
      id: _this.el().getAttribute("aria-describedby")
    });
    textContent(_this.descEl_, _this.description());
    _this.el_.appendChild(_this.descEl_);
    _this.el_.appendChild(_this.contentEl_);
    return _this;
  }
  var _proto = ModalDialog2.prototype;
  _proto.createEl = function createEl2() {
    return _Component.prototype.createEl.call(this, "div", {
      className: this.buildCSSClass(),
      tabIndex: -1
    }, {
      "aria-describedby": this.id() + "_description",
      "aria-hidden": "true",
      "aria-label": this.label(),
      "role": "dialog"
    });
  };
  _proto.dispose = function dispose() {
    this.contentEl_ = null;
    this.descEl_ = null;
    this.previouslyActiveEl_ = null;
    _Component.prototype.dispose.call(this);
  };
  _proto.buildCSSClass = function buildCSSClass() {
    return MODAL_CLASS_NAME + " vjs-hidden " + _Component.prototype.buildCSSClass.call(this);
  };
  _proto.label = function label() {
    return this.localize(this.options_.label || "Modal Window");
  };
  _proto.description = function description() {
    var desc = this.options_.description || this.localize("This is a modal window.");
    if (this.closeable()) {
      desc += " " + this.localize("This modal can be closed by pressing the Escape key or activating the close button.");
    }
    return desc;
  };
  _proto.open = function open() {
    if (!this.opened_) {
      var player = this.player();
      this.trigger("beforemodalopen");
      this.opened_ = true;
      if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
        this.fill();
      }
      this.wasPlaying_ = !player.paused();
      if (this.options_.pauseOnOpen && this.wasPlaying_) {
        player.pause();
      }
      this.on("keydown", this.handleKeyDown_);
      this.hadControls_ = player.controls();
      player.controls(false);
      this.show();
      this.conditionalFocus_();
      this.el().setAttribute("aria-hidden", "false");
      this.trigger("modalopen");
      this.hasBeenOpened_ = true;
    }
  };
  _proto.opened = function opened(value) {
    if (typeof value === "boolean") {
      this[value ? "open" : "close"]();
    }
    return this.opened_;
  };
  _proto.close = function close() {
    if (!this.opened_) {
      return;
    }
    var player = this.player();
    this.trigger("beforemodalclose");
    this.opened_ = false;
    if (this.wasPlaying_ && this.options_.pauseOnOpen) {
      player.play();
    }
    this.off("keydown", this.handleKeyDown_);
    if (this.hadControls_) {
      player.controls(true);
    }
    this.hide();
    this.el().setAttribute("aria-hidden", "true");
    this.trigger("modalclose");
    this.conditionalBlur_();
    if (this.options_.temporary) {
      this.dispose();
    }
  };
  _proto.closeable = function closeable(value) {
    if (typeof value === "boolean") {
      var closeable2 = this.closeable_ = !!value;
      var close = this.getChild("closeButton");
      if (closeable2 && !close) {
        var temp = this.contentEl_;
        this.contentEl_ = this.el_;
        close = this.addChild("closeButton", {
          controlText: "Close Modal Dialog"
        });
        this.contentEl_ = temp;
        this.on(close, "close", this.close_);
      }
      if (!closeable2 && close) {
        this.off(close, "close", this.close_);
        this.removeChild(close);
        close.dispose();
      }
    }
    return this.closeable_;
  };
  _proto.fill = function fill() {
    this.fillWith(this.content());
  };
  _proto.fillWith = function fillWith(content) {
    var contentEl = this.contentEl();
    var parentEl = contentEl.parentNode;
    var nextSiblingEl = contentEl.nextSibling;
    this.trigger("beforemodalfill");
    this.hasBeenFilled_ = true;
    parentEl.removeChild(contentEl);
    this.empty();
    insertContent(contentEl, content);
    this.trigger("modalfill");
    if (nextSiblingEl) {
      parentEl.insertBefore(contentEl, nextSiblingEl);
    } else {
      parentEl.appendChild(contentEl);
    }
    var closeButton = this.getChild("closeButton");
    if (closeButton) {
      parentEl.appendChild(closeButton.el_);
    }
  };
  _proto.empty = function empty() {
    this.trigger("beforemodalempty");
    emptyEl(this.contentEl());
    this.trigger("modalempty");
  };
  _proto.content = function content(value) {
    if (typeof value !== "undefined") {
      this.content_ = value;
    }
    return this.content_;
  };
  _proto.conditionalFocus_ = function conditionalFocus_() {
    var activeEl = import_document.default.activeElement;
    var playerEl = this.player_.el_;
    this.previouslyActiveEl_ = null;
    if (playerEl.contains(activeEl) || playerEl === activeEl) {
      this.previouslyActiveEl_ = activeEl;
      this.focus();
    }
  };
  _proto.conditionalBlur_ = function conditionalBlur_() {
    if (this.previouslyActiveEl_) {
      this.previouslyActiveEl_.focus();
      this.previouslyActiveEl_ = null;
    }
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    event.stopPropagation();
    if (import_keycode.default.isEventKey(event, "Escape") && this.closeable()) {
      event.preventDefault();
      this.close();
      return;
    }
    if (!import_keycode.default.isEventKey(event, "Tab")) {
      return;
    }
    var focusableEls = this.focusableEls_();
    var activeEl = this.el_.querySelector(":focus");
    var focusIndex;
    for (var i = 0; i < focusableEls.length; i++) {
      if (activeEl === focusableEls[i]) {
        focusIndex = i;
        break;
      }
    }
    if (import_document.default.activeElement === this.el_) {
      focusIndex = 0;
    }
    if (event.shiftKey && focusIndex === 0) {
      focusableEls[focusableEls.length - 1].focus();
      event.preventDefault();
    } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {
      focusableEls[0].focus();
      event.preventDefault();
    }
  };
  _proto.focusableEls_ = function focusableEls_() {
    var allChildren = this.el_.querySelectorAll("*");
    return Array.prototype.filter.call(allChildren, function(child) {
      return (child instanceof import_window6.default.HTMLAnchorElement || child instanceof import_window6.default.HTMLAreaElement) && child.hasAttribute("href") || (child instanceof import_window6.default.HTMLInputElement || child instanceof import_window6.default.HTMLSelectElement || child instanceof import_window6.default.HTMLTextAreaElement || child instanceof import_window6.default.HTMLButtonElement) && !child.hasAttribute("disabled") || child instanceof import_window6.default.HTMLIFrameElement || child instanceof import_window6.default.HTMLObjectElement || child instanceof import_window6.default.HTMLEmbedElement || child.hasAttribute("tabindex") && child.getAttribute("tabindex") !== -1 || child.hasAttribute("contenteditable");
    });
  };
  return ModalDialog2;
}(Component$1);
ModalDialog.prototype.options_ = {
  pauseOnOpen: true,
  temporary: true
};
Component$1.registerComponent("ModalDialog", ModalDialog);
var TrackList = /* @__PURE__ */ function(_EventTarget) {
  _inheritsLoose(TrackList2, _EventTarget);
  function TrackList2(tracks) {
    var _this;
    if (tracks === void 0) {
      tracks = [];
    }
    _this = _EventTarget.call(this) || this;
    _this.tracks_ = [];
    Object.defineProperty(_assertThisInitialized(_this), "length", {
      get: function get7() {
        return this.tracks_.length;
      }
    });
    for (var i = 0; i < tracks.length; i++) {
      _this.addTrack(tracks[i]);
    }
    return _this;
  }
  var _proto = TrackList2.prototype;
  _proto.addTrack = function addTrack(track) {
    var _this2 = this;
    var index = this.tracks_.length;
    if (!("" + index in this)) {
      Object.defineProperty(this, index, {
        get: function get7() {
          return this.tracks_[index];
        }
      });
    }
    if (this.tracks_.indexOf(track) === -1) {
      this.tracks_.push(track);
      this.trigger({
        track,
        type: "addtrack",
        target: this
      });
    }
    track.labelchange_ = function() {
      _this2.trigger({
        track,
        type: "labelchange",
        target: _this2
      });
    };
    if (isEvented(track)) {
      track.addEventListener("labelchange", track.labelchange_);
    }
  };
  _proto.removeTrack = function removeTrack(rtrack) {
    var track;
    for (var i = 0, l = this.length; i < l; i++) {
      if (this[i] === rtrack) {
        track = this[i];
        if (track.off) {
          track.off();
        }
        this.tracks_.splice(i, 1);
        break;
      }
    }
    if (!track) {
      return;
    }
    this.trigger({
      track,
      type: "removetrack",
      target: this
    });
  };
  _proto.getTrackById = function getTrackById(id) {
    var result = null;
    for (var i = 0, l = this.length; i < l; i++) {
      var track = this[i];
      if (track.id === id) {
        result = track;
        break;
      }
    }
    return result;
  };
  return TrackList2;
}(EventTarget$2);
TrackList.prototype.allowedEvents_ = {
  change: "change",
  addtrack: "addtrack",
  removetrack: "removetrack",
  labelchange: "labelchange"
};
for (event in TrackList.prototype.allowedEvents_) {
  TrackList.prototype["on" + event] = null;
}
var event;
var disableOthers$1 = function disableOthers(list, track) {
  for (var i = 0; i < list.length; i++) {
    if (!Object.keys(list[i]).length || track.id === list[i].id) {
      continue;
    }
    list[i].enabled = false;
  }
};
var AudioTrackList = /* @__PURE__ */ function(_TrackList) {
  _inheritsLoose(AudioTrackList2, _TrackList);
  function AudioTrackList2(tracks) {
    var _this;
    if (tracks === void 0) {
      tracks = [];
    }
    for (var i = tracks.length - 1; i >= 0; i--) {
      if (tracks[i].enabled) {
        disableOthers$1(tracks, tracks[i]);
        break;
      }
    }
    _this = _TrackList.call(this, tracks) || this;
    _this.changing_ = false;
    return _this;
  }
  var _proto = AudioTrackList2.prototype;
  _proto.addTrack = function addTrack(track) {
    var _this2 = this;
    if (track.enabled) {
      disableOthers$1(this, track);
    }
    _TrackList.prototype.addTrack.call(this, track);
    if (!track.addEventListener) {
      return;
    }
    track.enabledChange_ = function() {
      if (_this2.changing_) {
        return;
      }
      _this2.changing_ = true;
      disableOthers$1(_this2, track);
      _this2.changing_ = false;
      _this2.trigger("change");
    };
    track.addEventListener("enabledchange", track.enabledChange_);
  };
  _proto.removeTrack = function removeTrack(rtrack) {
    _TrackList.prototype.removeTrack.call(this, rtrack);
    if (rtrack.removeEventListener && rtrack.enabledChange_) {
      rtrack.removeEventListener("enabledchange", rtrack.enabledChange_);
      rtrack.enabledChange_ = null;
    }
  };
  return AudioTrackList2;
}(TrackList);
var disableOthers2 = function disableOthers3(list, track) {
  for (var i = 0; i < list.length; i++) {
    if (!Object.keys(list[i]).length || track.id === list[i].id) {
      continue;
    }
    list[i].selected = false;
  }
};
var VideoTrackList = /* @__PURE__ */ function(_TrackList) {
  _inheritsLoose(VideoTrackList2, _TrackList);
  function VideoTrackList2(tracks) {
    var _this;
    if (tracks === void 0) {
      tracks = [];
    }
    for (var i = tracks.length - 1; i >= 0; i--) {
      if (tracks[i].selected) {
        disableOthers2(tracks, tracks[i]);
        break;
      }
    }
    _this = _TrackList.call(this, tracks) || this;
    _this.changing_ = false;
    Object.defineProperty(_assertThisInitialized(_this), "selectedIndex", {
      get: function get7() {
        for (var _i = 0; _i < this.length; _i++) {
          if (this[_i].selected) {
            return _i;
          }
        }
        return -1;
      },
      set: function set4() {
      }
    });
    return _this;
  }
  var _proto = VideoTrackList2.prototype;
  _proto.addTrack = function addTrack(track) {
    var _this2 = this;
    if (track.selected) {
      disableOthers2(this, track);
    }
    _TrackList.prototype.addTrack.call(this, track);
    if (!track.addEventListener) {
      return;
    }
    track.selectedChange_ = function() {
      if (_this2.changing_) {
        return;
      }
      _this2.changing_ = true;
      disableOthers2(_this2, track);
      _this2.changing_ = false;
      _this2.trigger("change");
    };
    track.addEventListener("selectedchange", track.selectedChange_);
  };
  _proto.removeTrack = function removeTrack(rtrack) {
    _TrackList.prototype.removeTrack.call(this, rtrack);
    if (rtrack.removeEventListener && rtrack.selectedChange_) {
      rtrack.removeEventListener("selectedchange", rtrack.selectedChange_);
      rtrack.selectedChange_ = null;
    }
  };
  return VideoTrackList2;
}(TrackList);
var TextTrackList = /* @__PURE__ */ function(_TrackList) {
  _inheritsLoose(TextTrackList2, _TrackList);
  function TextTrackList2() {
    return _TrackList.apply(this, arguments) || this;
  }
  var _proto = TextTrackList2.prototype;
  _proto.addTrack = function addTrack(track) {
    var _this = this;
    _TrackList.prototype.addTrack.call(this, track);
    if (!this.queueChange_) {
      this.queueChange_ = function() {
        return _this.queueTrigger("change");
      };
    }
    if (!this.triggerSelectedlanguagechange) {
      this.triggerSelectedlanguagechange_ = function() {
        return _this.trigger("selectedlanguagechange");
      };
    }
    track.addEventListener("modechange", this.queueChange_);
    var nonLanguageTextTrackKind = ["metadata", "chapters"];
    if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {
      track.addEventListener("modechange", this.triggerSelectedlanguagechange_);
    }
  };
  _proto.removeTrack = function removeTrack(rtrack) {
    _TrackList.prototype.removeTrack.call(this, rtrack);
    if (rtrack.removeEventListener) {
      if (this.queueChange_) {
        rtrack.removeEventListener("modechange", this.queueChange_);
      }
      if (this.selectedlanguagechange_) {
        rtrack.removeEventListener("modechange", this.triggerSelectedlanguagechange_);
      }
    }
  };
  return TextTrackList2;
}(TrackList);
var HtmlTrackElementList = /* @__PURE__ */ function() {
  function HtmlTrackElementList2(trackElements) {
    if (trackElements === void 0) {
      trackElements = [];
    }
    this.trackElements_ = [];
    Object.defineProperty(this, "length", {
      get: function get7() {
        return this.trackElements_.length;
      }
    });
    for (var i = 0, length = trackElements.length; i < length; i++) {
      this.addTrackElement_(trackElements[i]);
    }
  }
  var _proto = HtmlTrackElementList2.prototype;
  _proto.addTrackElement_ = function addTrackElement_(trackElement) {
    var index = this.trackElements_.length;
    if (!("" + index in this)) {
      Object.defineProperty(this, index, {
        get: function get7() {
          return this.trackElements_[index];
        }
      });
    }
    if (this.trackElements_.indexOf(trackElement) === -1) {
      this.trackElements_.push(trackElement);
    }
  };
  _proto.getTrackElementByTrack_ = function getTrackElementByTrack_(track) {
    var trackElement_;
    for (var i = 0, length = this.trackElements_.length; i < length; i++) {
      if (track === this.trackElements_[i].track) {
        trackElement_ = this.trackElements_[i];
        break;
      }
    }
    return trackElement_;
  };
  _proto.removeTrackElement_ = function removeTrackElement_(trackElement) {
    for (var i = 0, length = this.trackElements_.length; i < length; i++) {
      if (trackElement === this.trackElements_[i]) {
        if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === "function") {
          this.trackElements_[i].track.off();
        }
        if (typeof this.trackElements_[i].off === "function") {
          this.trackElements_[i].off();
        }
        this.trackElements_.splice(i, 1);
        break;
      }
    }
  };
  return HtmlTrackElementList2;
}();
var TextTrackCueList = /* @__PURE__ */ function() {
  function TextTrackCueList2(cues) {
    TextTrackCueList2.prototype.setCues_.call(this, cues);
    Object.defineProperty(this, "length", {
      get: function get7() {
        return this.length_;
      }
    });
  }
  var _proto = TextTrackCueList2.prototype;
  _proto.setCues_ = function setCues_(cues) {
    var oldLength = this.length || 0;
    var i = 0;
    var l = cues.length;
    this.cues_ = cues;
    this.length_ = cues.length;
    var defineProp = function defineProp2(index) {
      if (!("" + index in this)) {
        Object.defineProperty(this, "" + index, {
          get: function get7() {
            return this.cues_[index];
          }
        });
      }
    };
    if (oldLength < l) {
      i = oldLength;
      for (; i < l; i++) {
        defineProp.call(this, i);
      }
    }
  };
  _proto.getCueById = function getCueById(id) {
    var result = null;
    for (var i = 0, l = this.length; i < l; i++) {
      var cue = this[i];
      if (cue.id === id) {
        result = cue;
        break;
      }
    }
    return result;
  };
  return TextTrackCueList2;
}();
var VideoTrackKind = {
  alternative: "alternative",
  captions: "captions",
  main: "main",
  sign: "sign",
  subtitles: "subtitles",
  commentary: "commentary"
};
var AudioTrackKind = {
  "alternative": "alternative",
  "descriptions": "descriptions",
  "main": "main",
  "main-desc": "main-desc",
  "translation": "translation",
  "commentary": "commentary"
};
var TextTrackKind = {
  subtitles: "subtitles",
  captions: "captions",
  descriptions: "descriptions",
  chapters: "chapters",
  metadata: "metadata"
};
var TextTrackMode = {
  disabled: "disabled",
  hidden: "hidden",
  showing: "showing"
};
var Track = /* @__PURE__ */ function(_EventTarget) {
  _inheritsLoose(Track2, _EventTarget);
  function Track2(options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    _this = _EventTarget.call(this) || this;
    var trackProps = {
      id: options.id || "vjs_track_" + newGUID(),
      kind: options.kind || "",
      language: options.language || ""
    };
    var label = options.label || "";
    var _loop = function _loop2(key2) {
      Object.defineProperty(_assertThisInitialized(_this), key2, {
        get: function get7() {
          return trackProps[key2];
        },
        set: function set4() {
        }
      });
    };
    for (var key in trackProps) {
      _loop(key);
    }
    Object.defineProperty(_assertThisInitialized(_this), "label", {
      get: function get7() {
        return label;
      },
      set: function set4(newLabel) {
        if (newLabel !== label) {
          label = newLabel;
          this.trigger("labelchange");
        }
      }
    });
    return _this;
  }
  return Track2;
}(EventTarget$2);
var parseUrl = function parseUrl2(url) {
  var props = ["protocol", "hostname", "port", "pathname", "search", "hash", "host"];
  var a = import_document.default.createElement("a");
  a.href = url;
  var details = {};
  for (var i = 0; i < props.length; i++) {
    details[props[i]] = a[props[i]];
  }
  if (details.protocol === "http:") {
    details.host = details.host.replace(/:80$/, "");
  }
  if (details.protocol === "https:") {
    details.host = details.host.replace(/:443$/, "");
  }
  if (!details.protocol) {
    details.protocol = import_window6.default.location.protocol;
  }
  if (!details.host) {
    details.host = import_window6.default.location.host;
  }
  return details;
};
var getAbsoluteURL = function getAbsoluteURL2(url) {
  if (!url.match(/^https?:\/\//)) {
    var a = import_document.default.createElement("a");
    a.href = url;
    url = a.href;
  }
  return url;
};
var getFileExtension = function getFileExtension2(path) {
  if (typeof path === "string") {
    var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;
    var pathParts = splitPathRe.exec(path);
    if (pathParts) {
      return pathParts.pop().toLowerCase();
    }
  }
  return "";
};
var isCrossOrigin = function isCrossOrigin2(url, winLoc) {
  if (winLoc === void 0) {
    winLoc = import_window6.default.location;
  }
  var urlInfo = parseUrl(url);
  var srcProtocol = urlInfo.protocol === ":" ? winLoc.protocol : urlInfo.protocol;
  var crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host;
  return crossOrigin;
};
var Url = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  parseUrl,
  getAbsoluteURL,
  getFileExtension,
  isCrossOrigin
});
var parseCues = function parseCues2(srcContent, track) {
  var parser6 = new import_window6.default.WebVTT.Parser(import_window6.default, import_window6.default.vttjs, import_window6.default.WebVTT.StringDecoder());
  var errors2 = [];
  parser6.oncue = function(cue) {
    track.addCue(cue);
  };
  parser6.onparsingerror = function(error) {
    errors2.push(error);
  };
  parser6.onflush = function() {
    track.trigger({
      type: "loadeddata",
      target: track
    });
  };
  parser6.parse(srcContent);
  if (errors2.length > 0) {
    if (import_window6.default.console && import_window6.default.console.groupCollapsed) {
      import_window6.default.console.groupCollapsed("Text Track parsing errors for " + track.src);
    }
    errors2.forEach(function(error) {
      return log$1.error(error);
    });
    if (import_window6.default.console && import_window6.default.console.groupEnd) {
      import_window6.default.console.groupEnd();
    }
  }
  parser6.flush();
};
var loadTrack = function loadTrack2(src, track) {
  var opts = {
    uri: src
  };
  var crossOrigin = isCrossOrigin(src);
  if (crossOrigin) {
    opts.cors = crossOrigin;
  }
  var withCredentials = track.tech_.crossOrigin() === "use-credentials";
  if (withCredentials) {
    opts.withCredentials = withCredentials;
  }
  (0, import_xhr.default)(opts, bind(this, function(err, response, responseBody) {
    if (err) {
      return log$1.error(err, response);
    }
    track.loaded_ = true;
    if (typeof import_window6.default.WebVTT !== "function") {
      if (track.tech_) {
        track.tech_.any(["vttjsloaded", "vttjserror"], function(event) {
          if (event.type === "vttjserror") {
            log$1.error("vttjs failed to load, stopping trying to process " + track.src);
            return;
          }
          return parseCues(responseBody, track);
        });
      }
    } else {
      parseCues(responseBody, track);
    }
  }));
};
var TextTrack = /* @__PURE__ */ function(_Track) {
  _inheritsLoose(TextTrack2, _Track);
  function TextTrack2(options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    if (!options.tech) {
      throw new Error("A tech was not provided.");
    }
    var settings = mergeOptions$3(options, {
      kind: TextTrackKind[options.kind] || "subtitles",
      language: options.language || options.srclang || ""
    });
    var mode = TextTrackMode[settings.mode] || "disabled";
    var default_ = settings["default"];
    if (settings.kind === "metadata" || settings.kind === "chapters") {
      mode = "hidden";
    }
    _this = _Track.call(this, settings) || this;
    _this.tech_ = settings.tech;
    _this.cues_ = [];
    _this.activeCues_ = [];
    _this.preload_ = _this.tech_.preloadTextTracks !== false;
    var cues = new TextTrackCueList(_this.cues_);
    var activeCues = new TextTrackCueList(_this.activeCues_);
    var changed = false;
    _this.timeupdateHandler = bind(_assertThisInitialized(_this), function(event) {
      if (event === void 0) {
        event = {};
      }
      if (this.tech_.isDisposed()) {
        return;
      }
      if (!this.tech_.isReady_) {
        if (event.type !== "timeupdate") {
          this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
        }
        return;
      }
      this.activeCues = this.activeCues;
      if (changed) {
        this.trigger("cuechange");
        changed = false;
      }
      if (event.type !== "timeupdate") {
        this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
      }
    });
    var disposeHandler = function disposeHandler2() {
      _this.stopTracking();
    };
    _this.tech_.one("dispose", disposeHandler);
    if (mode !== "disabled") {
      _this.startTracking();
    }
    Object.defineProperties(_assertThisInitialized(_this), {
      /**
       * @memberof TextTrack
       * @member {boolean} default
       *         If this track was set to be on or off by default. Cannot be changed after
       *         creation.
       * @instance
       *
       * @readonly
       */
      "default": {
        get: function get7() {
          return default_;
        },
        set: function set4() {
        }
      },
      /**
       * @memberof TextTrack
       * @member {string} mode
       *         Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will
       *         not be set if setting to an invalid mode.
       * @instance
       *
       * @fires TextTrack#modechange
       */
      mode: {
        get: function get7() {
          return mode;
        },
        set: function set4(newMode) {
          if (!TextTrackMode[newMode]) {
            return;
          }
          if (mode === newMode) {
            return;
          }
          mode = newMode;
          if (!this.preload_ && mode !== "disabled" && this.cues.length === 0) {
            loadTrack(this.src, this);
          }
          this.stopTracking();
          if (mode !== "disabled") {
            this.startTracking();
          }
          this.trigger("modechange");
        }
      },
      /**
       * @memberof TextTrack
       * @member {TextTrackCueList} cues
       *         The text track cue list for this TextTrack.
       * @instance
       */
      cues: {
        get: function get7() {
          if (!this.loaded_) {
            return null;
          }
          return cues;
        },
        set: function set4() {
        }
      },
      /**
       * @memberof TextTrack
       * @member {TextTrackCueList} activeCues
       *         The list text track cues that are currently active for this TextTrack.
       * @instance
       */
      activeCues: {
        get: function get7() {
          if (!this.loaded_) {
            return null;
          }
          if (this.cues.length === 0) {
            return activeCues;
          }
          var ct = this.tech_.currentTime();
          var active = [];
          for (var i = 0, l = this.cues.length; i < l; i++) {
            var cue = this.cues[i];
            if (cue.startTime <= ct && cue.endTime >= ct) {
              active.push(cue);
            } else if (cue.startTime === cue.endTime && cue.startTime <= ct && cue.startTime + 0.5 >= ct) {
              active.push(cue);
            }
          }
          changed = false;
          if (active.length !== this.activeCues_.length) {
            changed = true;
          } else {
            for (var _i = 0; _i < active.length; _i++) {
              if (this.activeCues_.indexOf(active[_i]) === -1) {
                changed = true;
              }
            }
          }
          this.activeCues_ = active;
          activeCues.setCues_(this.activeCues_);
          return activeCues;
        },
        // /!\ Keep this setter empty (see the timeupdate handler above)
        set: function set4() {
        }
      }
    });
    if (settings.src) {
      _this.src = settings.src;
      if (!_this.preload_) {
        _this.loaded_ = true;
      }
      if (_this.preload_ || settings.kind !== "subtitles" && settings.kind !== "captions") {
        loadTrack(_this.src, _assertThisInitialized(_this));
      }
    } else {
      _this.loaded_ = true;
    }
    return _this;
  }
  var _proto = TextTrack2.prototype;
  _proto.startTracking = function startTracking() {
    this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
    this.tech_.on("timeupdate", this.timeupdateHandler);
  };
  _proto.stopTracking = function stopTracking() {
    if (this.rvf_) {
      this.tech_.cancelVideoFrameCallback(this.rvf_);
      this.rvf_ = void 0;
    }
    this.tech_.off("timeupdate", this.timeupdateHandler);
  };
  _proto.addCue = function addCue(originalCue) {
    var cue = originalCue;
    if (import_window6.default.vttjs && !(originalCue instanceof import_window6.default.vttjs.VTTCue)) {
      cue = new import_window6.default.vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);
      for (var prop in originalCue) {
        if (!(prop in cue)) {
          cue[prop] = originalCue[prop];
        }
      }
      cue.id = originalCue.id;
      cue.originalCue_ = originalCue;
    }
    var tracks = this.tech_.textTracks();
    for (var i = 0; i < tracks.length; i++) {
      if (tracks[i] !== this) {
        tracks[i].removeCue(cue);
      }
    }
    this.cues_.push(cue);
    this.cues.setCues_(this.cues_);
  };
  _proto.removeCue = function removeCue(_removeCue) {
    var i = this.cues_.length;
    while (i--) {
      var cue = this.cues_[i];
      if (cue === _removeCue || cue.originalCue_ && cue.originalCue_ === _removeCue) {
        this.cues_.splice(i, 1);
        this.cues.setCues_(this.cues_);
        break;
      }
    }
  };
  return TextTrack2;
}(Track);
TextTrack.prototype.allowedEvents_ = {
  cuechange: "cuechange"
};
var AudioTrack = /* @__PURE__ */ function(_Track) {
  _inheritsLoose(AudioTrack2, _Track);
  function AudioTrack2(options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    var settings = mergeOptions$3(options, {
      kind: AudioTrackKind[options.kind] || ""
    });
    _this = _Track.call(this, settings) || this;
    var enabled = false;
    Object.defineProperty(_assertThisInitialized(_this), "enabled", {
      get: function get7() {
        return enabled;
      },
      set: function set4(newEnabled) {
        if (typeof newEnabled !== "boolean" || newEnabled === enabled) {
          return;
        }
        enabled = newEnabled;
        this.trigger("enabledchange");
      }
    });
    if (settings.enabled) {
      _this.enabled = settings.enabled;
    }
    _this.loaded_ = true;
    return _this;
  }
  return AudioTrack2;
}(Track);
var VideoTrack = /* @__PURE__ */ function(_Track) {
  _inheritsLoose(VideoTrack2, _Track);
  function VideoTrack2(options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    var settings = mergeOptions$3(options, {
      kind: VideoTrackKind[options.kind] || ""
    });
    _this = _Track.call(this, settings) || this;
    var selected = false;
    Object.defineProperty(_assertThisInitialized(_this), "selected", {
      get: function get7() {
        return selected;
      },
      set: function set4(newSelected) {
        if (typeof newSelected !== "boolean" || newSelected === selected) {
          return;
        }
        selected = newSelected;
        this.trigger("selectedchange");
      }
    });
    if (settings.selected) {
      _this.selected = settings.selected;
    }
    return _this;
  }
  return VideoTrack2;
}(Track);
var NONE = 0;
var LOADING = 1;
var LOADED = 2;
var ERROR = 3;
var HTMLTrackElement = /* @__PURE__ */ function(_EventTarget) {
  _inheritsLoose(HTMLTrackElement2, _EventTarget);
  function HTMLTrackElement2(options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    _this = _EventTarget.call(this) || this;
    var readyState;
    var track = new TextTrack(options);
    _this.kind = track.kind;
    _this.src = track.src;
    _this.srclang = track.language;
    _this.label = track.label;
    _this["default"] = track["default"];
    Object.defineProperties(_assertThisInitialized(_this), {
      /**
       * @memberof HTMLTrackElement
       * @member {HTMLTrackElement~ReadyState} readyState
       *         The current ready state of the track element.
       * @instance
       */
      readyState: {
        get: function get7() {
          return readyState;
        }
      },
      /**
       * @memberof HTMLTrackElement
       * @member {TextTrack} track
       *         The underlying TextTrack object.
       * @instance
       *
       */
      track: {
        get: function get7() {
          return track;
        }
      }
    });
    readyState = NONE;
    track.addEventListener("loadeddata", function() {
      readyState = LOADED;
      _this.trigger({
        type: "load",
        target: _assertThisInitialized(_this)
      });
    });
    return _this;
  }
  return HTMLTrackElement2;
}(EventTarget$2);
HTMLTrackElement.prototype.allowedEvents_ = {
  load: "load"
};
HTMLTrackElement.NONE = NONE;
HTMLTrackElement.LOADING = LOADING;
HTMLTrackElement.LOADED = LOADED;
HTMLTrackElement.ERROR = ERROR;
var NORMAL = {
  audio: {
    ListClass: AudioTrackList,
    TrackClass: AudioTrack,
    capitalName: "Audio"
  },
  video: {
    ListClass: VideoTrackList,
    TrackClass: VideoTrack,
    capitalName: "Video"
  },
  text: {
    ListClass: TextTrackList,
    TrackClass: TextTrack,
    capitalName: "Text"
  }
};
Object.keys(NORMAL).forEach(function(type2) {
  NORMAL[type2].getterName = type2 + "Tracks";
  NORMAL[type2].privateName = type2 + "Tracks_";
});
var REMOTE = {
  remoteText: {
    ListClass: TextTrackList,
    TrackClass: TextTrack,
    capitalName: "RemoteText",
    getterName: "remoteTextTracks",
    privateName: "remoteTextTracks_"
  },
  remoteTextEl: {
    ListClass: HtmlTrackElementList,
    TrackClass: HTMLTrackElement,
    capitalName: "RemoteTextTrackEls",
    getterName: "remoteTextTrackEls",
    privateName: "remoteTextTrackEls_"
  }
};
var ALL = _extends2({}, NORMAL, REMOTE);
REMOTE.names = Object.keys(REMOTE);
NORMAL.names = Object.keys(NORMAL);
ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
function createTrackHelper(self2, kind, label, language, options) {
  if (options === void 0) {
    options = {};
  }
  var tracks = self2.textTracks();
  options.kind = kind;
  if (label) {
    options.label = label;
  }
  if (language) {
    options.language = language;
  }
  options.tech = self2;
  var track = new ALL.text.TrackClass(options);
  tracks.addTrack(track);
  return track;
}
var Tech = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(Tech2, _Component);
  function Tech2(options, ready) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    if (ready === void 0) {
      ready = function ready2() {
      };
    }
    options.reportTouchActivity = false;
    _this = _Component.call(this, null, options, ready) || this;
    _this.onDurationChange_ = function(e) {
      return _this.onDurationChange(e);
    };
    _this.trackProgress_ = function(e) {
      return _this.trackProgress(e);
    };
    _this.trackCurrentTime_ = function(e) {
      return _this.trackCurrentTime(e);
    };
    _this.stopTrackingCurrentTime_ = function(e) {
      return _this.stopTrackingCurrentTime(e);
    };
    _this.disposeSourceHandler_ = function(e) {
      return _this.disposeSourceHandler(e);
    };
    _this.queuedHanders_ = /* @__PURE__ */ new Set();
    _this.hasStarted_ = false;
    _this.on("playing", function() {
      this.hasStarted_ = true;
    });
    _this.on("loadstart", function() {
      this.hasStarted_ = false;
    });
    ALL.names.forEach(function(name) {
      var props = ALL[name];
      if (options && options[props.getterName]) {
        _this[props.privateName] = options[props.getterName];
      }
    });
    if (!_this.featuresProgressEvents) {
      _this.manualProgressOn();
    }
    if (!_this.featuresTimeupdateEvents) {
      _this.manualTimeUpdatesOn();
    }
    ["Text", "Audio", "Video"].forEach(function(track) {
      if (options["native" + track + "Tracks"] === false) {
        _this["featuresNative" + track + "Tracks"] = false;
      }
    });
    if (options.nativeCaptions === false || options.nativeTextTracks === false) {
      _this.featuresNativeTextTracks = false;
    } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
      _this.featuresNativeTextTracks = true;
    }
    if (!_this.featuresNativeTextTracks) {
      _this.emulateTextTracks();
    }
    _this.preloadTextTracks = options.preloadTextTracks !== false;
    _this.autoRemoteTextTracks_ = new ALL.text.ListClass();
    _this.initTrackListeners();
    if (!options.nativeControlsForTouch) {
      _this.emitTapEvents();
    }
    if (_this.constructor) {
      _this.name_ = _this.constructor.name || "Unknown Tech";
    }
    return _this;
  }
  var _proto = Tech2.prototype;
  _proto.triggerSourceset = function triggerSourceset(src) {
    var _this2 = this;
    if (!this.isReady_) {
      this.one("ready", function() {
        return _this2.setTimeout(function() {
          return _this2.triggerSourceset(src);
        }, 1);
      });
    }
    this.trigger({
      src,
      type: "sourceset"
    });
  };
  _proto.manualProgressOn = function manualProgressOn() {
    this.on("durationchange", this.onDurationChange_);
    this.manualProgress = true;
    this.one("ready", this.trackProgress_);
  };
  _proto.manualProgressOff = function manualProgressOff() {
    this.manualProgress = false;
    this.stopTrackingProgress();
    this.off("durationchange", this.onDurationChange_);
  };
  _proto.trackProgress = function trackProgress(event) {
    this.stopTrackingProgress();
    this.progressInterval = this.setInterval(bind(this, function() {
      var numBufferedPercent = this.bufferedPercent();
      if (this.bufferedPercent_ !== numBufferedPercent) {
        this.trigger("progress");
      }
      this.bufferedPercent_ = numBufferedPercent;
      if (numBufferedPercent === 1) {
        this.stopTrackingProgress();
      }
    }), 500);
  };
  _proto.onDurationChange = function onDurationChange(event) {
    this.duration_ = this.duration();
  };
  _proto.buffered = function buffered() {
    return createTimeRanges(0, 0);
  };
  _proto.bufferedPercent = function bufferedPercent$1() {
    return bufferedPercent(this.buffered(), this.duration_);
  };
  _proto.stopTrackingProgress = function stopTrackingProgress() {
    this.clearInterval(this.progressInterval);
  };
  _proto.manualTimeUpdatesOn = function manualTimeUpdatesOn() {
    this.manualTimeUpdates = true;
    this.on("play", this.trackCurrentTime_);
    this.on("pause", this.stopTrackingCurrentTime_);
  };
  _proto.manualTimeUpdatesOff = function manualTimeUpdatesOff() {
    this.manualTimeUpdates = false;
    this.stopTrackingCurrentTime();
    this.off("play", this.trackCurrentTime_);
    this.off("pause", this.stopTrackingCurrentTime_);
  };
  _proto.trackCurrentTime = function trackCurrentTime() {
    if (this.currentTimeInterval) {
      this.stopTrackingCurrentTime();
    }
    this.currentTimeInterval = this.setInterval(function() {
      this.trigger({
        type: "timeupdate",
        target: this,
        manuallyTriggered: true
      });
    }, 250);
  };
  _proto.stopTrackingCurrentTime = function stopTrackingCurrentTime() {
    this.clearInterval(this.currentTimeInterval);
    this.trigger({
      type: "timeupdate",
      target: this,
      manuallyTriggered: true
    });
  };
  _proto.dispose = function dispose() {
    this.clearTracks(NORMAL.names);
    if (this.manualProgress) {
      this.manualProgressOff();
    }
    if (this.manualTimeUpdates) {
      this.manualTimeUpdatesOff();
    }
    _Component.prototype.dispose.call(this);
  };
  _proto.clearTracks = function clearTracks(types) {
    var _this3 = this;
    types = [].concat(types);
    types.forEach(function(type2) {
      var list = _this3[type2 + "Tracks"]() || [];
      var i = list.length;
      while (i--) {
        var track = list[i];
        if (type2 === "text") {
          _this3.removeRemoteTextTrack(track);
        }
        list.removeTrack(track);
      }
    });
  };
  _proto.cleanupAutoTextTracks = function cleanupAutoTextTracks() {
    var list = this.autoRemoteTextTracks_ || [];
    var i = list.length;
    while (i--) {
      var track = list[i];
      this.removeRemoteTextTrack(track);
    }
  };
  _proto.reset = function reset3() {
  };
  _proto.crossOrigin = function crossOrigin() {
  };
  _proto.setCrossOrigin = function setCrossOrigin() {
  };
  _proto.error = function error(err) {
    if (err !== void 0) {
      this.error_ = new MediaError(err);
      this.trigger("error");
    }
    return this.error_;
  };
  _proto.played = function played() {
    if (this.hasStarted_) {
      return createTimeRanges(0, 0);
    }
    return createTimeRanges();
  };
  _proto.play = function play() {
  };
  _proto.setScrubbing = function setScrubbing() {
  };
  _proto.scrubbing = function scrubbing() {
  };
  _proto.setCurrentTime = function setCurrentTime() {
    if (this.manualTimeUpdates) {
      this.trigger({
        type: "timeupdate",
        target: this,
        manuallyTriggered: true
      });
    }
  };
  _proto.initTrackListeners = function initTrackListeners() {
    var _this4 = this;
    NORMAL.names.forEach(function(name) {
      var props = NORMAL[name];
      var trackListChanges = function trackListChanges2() {
        _this4.trigger(name + "trackchange");
      };
      var tracks = _this4[props.getterName]();
      tracks.addEventListener("removetrack", trackListChanges);
      tracks.addEventListener("addtrack", trackListChanges);
      _this4.on("dispose", function() {
        tracks.removeEventListener("removetrack", trackListChanges);
        tracks.removeEventListener("addtrack", trackListChanges);
      });
    });
  };
  _proto.addWebVttScript_ = function addWebVttScript_() {
    var _this5 = this;
    if (import_window6.default.WebVTT) {
      return;
    }
    if (import_document.default.body.contains(this.el())) {
      if (!this.options_["vtt.js"] && isPlain(import_videojs_vtt.default) && Object.keys(import_videojs_vtt.default).length > 0) {
        this.trigger("vttjsloaded");
        return;
      }
      var script = import_document.default.createElement("script");
      script.src = this.options_["vtt.js"] || "/vtt.min.js";
      script.onload = function() {
        _this5.trigger("vttjsloaded");
      };
      script.onerror = function() {
        _this5.trigger("vttjserror");
      };
      this.on("dispose", function() {
        script.onload = null;
        script.onerror = null;
      });
      import_window6.default.WebVTT = true;
      this.el().parentNode.appendChild(script);
    } else {
      this.ready(this.addWebVttScript_);
    }
  };
  _proto.emulateTextTracks = function emulateTextTracks() {
    var _this6 = this;
    var tracks = this.textTracks();
    var remoteTracks = this.remoteTextTracks();
    var handleAddTrack = function handleAddTrack2(e) {
      return tracks.addTrack(e.track);
    };
    var handleRemoveTrack = function handleRemoveTrack2(e) {
      return tracks.removeTrack(e.track);
    };
    remoteTracks.on("addtrack", handleAddTrack);
    remoteTracks.on("removetrack", handleRemoveTrack);
    this.addWebVttScript_();
    var updateDisplay = function updateDisplay2() {
      return _this6.trigger("texttrackchange");
    };
    var textTracksChanges = function textTracksChanges2() {
      updateDisplay();
      for (var i = 0; i < tracks.length; i++) {
        var track = tracks[i];
        track.removeEventListener("cuechange", updateDisplay);
        if (track.mode === "showing") {
          track.addEventListener("cuechange", updateDisplay);
        }
      }
    };
    textTracksChanges();
    tracks.addEventListener("change", textTracksChanges);
    tracks.addEventListener("addtrack", textTracksChanges);
    tracks.addEventListener("removetrack", textTracksChanges);
    this.on("dispose", function() {
      remoteTracks.off("addtrack", handleAddTrack);
      remoteTracks.off("removetrack", handleRemoveTrack);
      tracks.removeEventListener("change", textTracksChanges);
      tracks.removeEventListener("addtrack", textTracksChanges);
      tracks.removeEventListener("removetrack", textTracksChanges);
      for (var i = 0; i < tracks.length; i++) {
        var track = tracks[i];
        track.removeEventListener("cuechange", updateDisplay);
      }
    });
  };
  _proto.addTextTrack = function addTextTrack(kind, label, language) {
    if (!kind) {
      throw new Error("TextTrack kind is required but was not provided");
    }
    return createTrackHelper(this, kind, label, language);
  };
  _proto.createRemoteTextTrack = function createRemoteTextTrack(options) {
    var track = mergeOptions$3(options, {
      tech: this
    });
    return new REMOTE.remoteTextEl.TrackClass(track);
  };
  _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
    var _this7 = this;
    if (options === void 0) {
      options = {};
    }
    var htmlTrackElement = this.createRemoteTextTrack(options);
    if (manualCleanup !== true && manualCleanup !== false) {
      log$1.warn('Calling addRemoteTextTrack without explicitly setting the "manualCleanup" parameter to `true` is deprecated and default to `false` in future version of video.js');
      manualCleanup = true;
    }
    this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
    this.remoteTextTracks().addTrack(htmlTrackElement.track);
    if (manualCleanup !== true) {
      this.ready(function() {
        return _this7.autoRemoteTextTracks_.addTrack(htmlTrackElement.track);
      });
    }
    return htmlTrackElement;
  };
  _proto.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
    var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
    this.remoteTextTrackEls().removeTrackElement_(trackElement);
    this.remoteTextTracks().removeTrack(track);
    this.autoRemoteTextTracks_.removeTrack(track);
  };
  _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
    return {};
  };
  _proto.requestPictureInPicture = function requestPictureInPicture() {
    var PromiseClass = this.options_.Promise || import_window6.default.Promise;
    if (PromiseClass) {
      return PromiseClass.reject();
    }
  };
  _proto.disablePictureInPicture = function disablePictureInPicture() {
    return true;
  };
  _proto.setDisablePictureInPicture = function setDisablePictureInPicture() {
  };
  _proto.requestVideoFrameCallback = function requestVideoFrameCallback(cb) {
    var _this8 = this;
    var id = newGUID();
    if (!this.isReady_ || this.paused()) {
      this.queuedHanders_.add(id);
      this.one("playing", function() {
        if (_this8.queuedHanders_.has(id)) {
          _this8.queuedHanders_["delete"](id);
          cb();
        }
      });
    } else {
      this.requestNamedAnimationFrame(id, cb);
    }
    return id;
  };
  _proto.cancelVideoFrameCallback = function cancelVideoFrameCallback(id) {
    if (this.queuedHanders_.has(id)) {
      this.queuedHanders_["delete"](id);
    } else {
      this.cancelNamedAnimationFrame(id);
    }
  };
  _proto.setPoster = function setPoster() {
  };
  _proto.playsinline = function playsinline() {
  };
  _proto.setPlaysinline = function setPlaysinline() {
  };
  _proto.overrideNativeAudioTracks = function overrideNativeAudioTracks() {
  };
  _proto.overrideNativeVideoTracks = function overrideNativeVideoTracks() {
  };
  _proto.canPlayType = function canPlayType3() {
    return "";
  };
  Tech2.canPlayType = function canPlayType3() {
    return "";
  };
  Tech2.canPlaySource = function canPlaySource(srcObj, options) {
    return Tech2.canPlayType(srcObj.type);
  };
  Tech2.isTech = function isTech(component) {
    return component.prototype instanceof Tech2 || component instanceof Tech2 || component === Tech2;
  };
  Tech2.registerTech = function registerTech(name, tech) {
    if (!Tech2.techs_) {
      Tech2.techs_ = {};
    }
    if (!Tech2.isTech(tech)) {
      throw new Error("Tech " + name + " must be a Tech");
    }
    if (!Tech2.canPlayType) {
      throw new Error("Techs must have a static canPlayType method on them");
    }
    if (!Tech2.canPlaySource) {
      throw new Error("Techs must have a static canPlaySource method on them");
    }
    name = toTitleCase$1(name);
    Tech2.techs_[name] = tech;
    Tech2.techs_[toLowerCase(name)] = tech;
    if (name !== "Tech") {
      Tech2.defaultTechOrder_.push(name);
    }
    return tech;
  };
  Tech2.getTech = function getTech(name) {
    if (!name) {
      return;
    }
    if (Tech2.techs_ && Tech2.techs_[name]) {
      return Tech2.techs_[name];
    }
    name = toTitleCase$1(name);
    if (import_window6.default && import_window6.default.videojs && import_window6.default.videojs[name]) {
      log$1.warn("The " + name + " tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)");
      return import_window6.default.videojs[name];
    }
  };
  return Tech2;
}(Component$1);
ALL.names.forEach(function(name) {
  var props = ALL[name];
  Tech.prototype[props.getterName] = function() {
    this[props.privateName] = this[props.privateName] || new props.ListClass();
    return this[props.privateName];
  };
});
Tech.prototype.featuresVolumeControl = true;
Tech.prototype.featuresMuteControl = true;
Tech.prototype.featuresFullscreenResize = false;
Tech.prototype.featuresPlaybackRate = false;
Tech.prototype.featuresProgressEvents = false;
Tech.prototype.featuresSourceset = false;
Tech.prototype.featuresTimeupdateEvents = false;
Tech.prototype.featuresNativeTextTracks = false;
Tech.prototype.featuresVideoFrameCallback = false;
Tech.withSourceHandlers = function(_Tech) {
  _Tech.registerSourceHandler = function(handler, index) {
    var handlers = _Tech.sourceHandlers;
    if (!handlers) {
      handlers = _Tech.sourceHandlers = [];
    }
    if (index === void 0) {
      index = handlers.length;
    }
    handlers.splice(index, 0, handler);
  };
  _Tech.canPlayType = function(type2) {
    var handlers = _Tech.sourceHandlers || [];
    var can;
    for (var i = 0; i < handlers.length; i++) {
      can = handlers[i].canPlayType(type2);
      if (can) {
        return can;
      }
    }
    return "";
  };
  _Tech.selectSourceHandler = function(source, options) {
    var handlers = _Tech.sourceHandlers || [];
    var can;
    for (var i = 0; i < handlers.length; i++) {
      can = handlers[i].canHandleSource(source, options);
      if (can) {
        return handlers[i];
      }
    }
    return null;
  };
  _Tech.canPlaySource = function(srcObj, options) {
    var sh = _Tech.selectSourceHandler(srcObj, options);
    if (sh) {
      return sh.canHandleSource(srcObj, options);
    }
    return "";
  };
  var deferrable = ["seekable", "seeking", "duration"];
  deferrable.forEach(function(fnName) {
    var originalFn = this[fnName];
    if (typeof originalFn !== "function") {
      return;
    }
    this[fnName] = function() {
      if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
        return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
      }
      return originalFn.apply(this, arguments);
    };
  }, _Tech.prototype);
  _Tech.prototype.setSource = function(source) {
    var sh = _Tech.selectSourceHandler(source, this.options_);
    if (!sh) {
      if (_Tech.nativeSourceHandler) {
        sh = _Tech.nativeSourceHandler;
      } else {
        log$1.error("No source handler found for the current source.");
      }
    }
    this.disposeSourceHandler();
    this.off("dispose", this.disposeSourceHandler_);
    if (sh !== _Tech.nativeSourceHandler) {
      this.currentSource_ = source;
    }
    this.sourceHandler_ = sh.handleSource(source, this, this.options_);
    this.one("dispose", this.disposeSourceHandler_);
  };
  _Tech.prototype.disposeSourceHandler = function() {
    if (this.currentSource_) {
      this.clearTracks(["audio", "video"]);
      this.currentSource_ = null;
    }
    this.cleanupAutoTextTracks();
    if (this.sourceHandler_) {
      if (this.sourceHandler_.dispose) {
        this.sourceHandler_.dispose();
      }
      this.sourceHandler_ = null;
    }
  };
};
Component$1.registerComponent("Tech", Tech);
Tech.registerTech("Tech", Tech);
Tech.defaultTechOrder_ = [];
var middlewares = {};
var middlewareInstances = {};
var TERMINATOR = {};
function use(type2, middleware) {
  middlewares[type2] = middlewares[type2] || [];
  middlewares[type2].push(middleware);
}
function setSource(player, src, next) {
  player.setTimeout(function() {
    return setSourceHelper(src, middlewares[src.type], next, player);
  }, 1);
}
function setTech(middleware, tech) {
  middleware.forEach(function(mw) {
    return mw.setTech && mw.setTech(tech);
  });
}
function get(middleware, tech, method) {
  return middleware.reduceRight(middlewareIterator(method), tech[method]());
}
function set(middleware, tech, method, arg) {
  return tech[method](middleware.reduce(middlewareIterator(method), arg));
}
function mediate(middleware, tech, method, arg) {
  if (arg === void 0) {
    arg = null;
  }
  var callMethod = "call" + toTitleCase$1(method);
  var middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  var terminated = middlewareValue === TERMINATOR;
  var returnValue = terminated ? null : tech[method](middlewareValue);
  executeRight(middleware, method, returnValue, terminated);
  return returnValue;
}
var allowedGetters = {
  buffered: 1,
  currentTime: 1,
  duration: 1,
  muted: 1,
  played: 1,
  paused: 1,
  seekable: 1,
  volume: 1,
  ended: 1
};
var allowedSetters = {
  setCurrentTime: 1,
  setMuted: 1,
  setVolume: 1
};
var allowedMediators = {
  play: 1,
  pause: 1
};
function middlewareIterator(method) {
  return function(value, mw) {
    if (value === TERMINATOR) {
      return TERMINATOR;
    }
    if (mw[method]) {
      return mw[method](value);
    }
    return value;
  };
}
function executeRight(mws, method, value, terminated) {
  for (var i = mws.length - 1; i >= 0; i--) {
    var mw = mws[i];
    if (mw[method]) {
      mw[method](terminated, value);
    }
  }
}
function clearCacheForPlayer(player) {
  middlewareInstances[player.id()] = null;
}
function getOrCreateFactory(player, mwFactory) {
  var mws = middlewareInstances[player.id()];
  var mw = null;
  if (mws === void 0 || mws === null) {
    mw = mwFactory(player);
    middlewareInstances[player.id()] = [[mwFactory, mw]];
    return mw;
  }
  for (var i = 0; i < mws.length; i++) {
    var _mws$i = mws[i], mwf = _mws$i[0], mwi = _mws$i[1];
    if (mwf !== mwFactory) {
      continue;
    }
    mw = mwi;
  }
  if (mw === null) {
    mw = mwFactory(player);
    mws.push([mwFactory, mw]);
  }
  return mw;
}
function setSourceHelper(src, middleware, next, player, acc, lastRun) {
  if (src === void 0) {
    src = {};
  }
  if (middleware === void 0) {
    middleware = [];
  }
  if (acc === void 0) {
    acc = [];
  }
  if (lastRun === void 0) {
    lastRun = false;
  }
  var _middleware = middleware, mwFactory = _middleware[0], mwrest = _middleware.slice(1);
  if (typeof mwFactory === "string") {
    setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun);
  } else if (mwFactory) {
    var mw = getOrCreateFactory(player, mwFactory);
    if (!mw.setSource) {
      acc.push(mw);
      return setSourceHelper(src, mwrest, next, player, acc, lastRun);
    }
    mw.setSource(assign({}, src), function(err, _src) {
      if (err) {
        return setSourceHelper(src, mwrest, next, player, acc, lastRun);
      }
      acc.push(mw);
      setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
    });
  } else if (mwrest.length) {
    setSourceHelper(src, mwrest, next, player, acc, lastRun);
  } else if (lastRun) {
    next(src, acc);
  } else {
    setSourceHelper(src, middlewares["*"], next, player, acc, true);
  }
}
var MimetypesKind = {
  opus: "video/ogg",
  ogv: "video/ogg",
  mp4: "video/mp4",
  mov: "video/mp4",
  m4v: "video/mp4",
  mkv: "video/x-matroska",
  m4a: "audio/mp4",
  mp3: "audio/mpeg",
  aac: "audio/aac",
  caf: "audio/x-caf",
  flac: "audio/flac",
  oga: "audio/ogg",
  wav: "audio/wav",
  m3u8: "application/x-mpegURL",
  mpd: "application/dash+xml",
  jpg: "image/jpeg",
  jpeg: "image/jpeg",
  gif: "image/gif",
  png: "image/png",
  svg: "image/svg+xml",
  webp: "image/webp"
};
var getMimetype = function getMimetype2(src) {
  if (src === void 0) {
    src = "";
  }
  var ext = getFileExtension(src);
  var mimetype = MimetypesKind[ext.toLowerCase()];
  return mimetype || "";
};
var findMimetype = function findMimetype2(player, src) {
  if (!src) {
    return "";
  }
  if (player.cache_.source.src === src && player.cache_.source.type) {
    return player.cache_.source.type;
  }
  var matchingSources = player.cache_.sources.filter(function(s2) {
    return s2.src === src;
  });
  if (matchingSources.length) {
    return matchingSources[0].type;
  }
  var sources = player.$$("source");
  for (var i = 0; i < sources.length; i++) {
    var s = sources[i];
    if (s.type && s.src && s.src === src) {
      return s.type;
    }
  }
  return getMimetype(src);
};
var filterSource = function filterSource2(src) {
  if (Array.isArray(src)) {
    var newsrc = [];
    src.forEach(function(srcobj) {
      srcobj = filterSource2(srcobj);
      if (Array.isArray(srcobj)) {
        newsrc = newsrc.concat(srcobj);
      } else if (isObject3(srcobj)) {
        newsrc.push(srcobj);
      }
    });
    src = newsrc;
  } else if (typeof src === "string" && src.trim()) {
    src = [fixSource({
      src
    })];
  } else if (isObject3(src) && typeof src.src === "string" && src.src && src.src.trim()) {
    src = [fixSource(src)];
  } else {
    src = [];
  }
  return src;
};
function fixSource(src) {
  if (!src.type) {
    var mimetype = getMimetype(src.src);
    if (mimetype) {
      src.type = mimetype;
    }
  }
  return src;
}
var MediaLoader = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(MediaLoader2, _Component);
  function MediaLoader2(player, options, ready) {
    var _this;
    var options_ = mergeOptions$3({
      createEl: false
    }, options);
    _this = _Component.call(this, player, options_, ready) || this;
    if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
      for (var i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
        var techName = toTitleCase$1(j[i]);
        var tech = Tech.getTech(techName);
        if (!techName) {
          tech = Component$1.getComponent(techName);
        }
        if (tech && tech.isSupported()) {
          player.loadTech_(techName);
          break;
        }
      }
    } else {
      player.src(options.playerOptions.sources);
    }
    return _this;
  }
  return MediaLoader2;
}(Component$1);
Component$1.registerComponent("MediaLoader", MediaLoader);
var ClickableComponent = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(ClickableComponent2, _Component);
  function ClickableComponent2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    if (_this.options_.controlText) {
      _this.controlText(_this.options_.controlText);
    }
    _this.handleMouseOver_ = function(e) {
      return _this.handleMouseOver(e);
    };
    _this.handleMouseOut_ = function(e) {
      return _this.handleMouseOut(e);
    };
    _this.handleClick_ = function(e) {
      return _this.handleClick(e);
    };
    _this.handleKeyDown_ = function(e) {
      return _this.handleKeyDown(e);
    };
    _this.emitTapEvents();
    _this.enable();
    return _this;
  }
  var _proto = ClickableComponent2.prototype;
  _proto.createEl = function createEl$1(tag, props, attributes) {
    if (tag === void 0) {
      tag = "div";
    }
    if (props === void 0) {
      props = {};
    }
    if (attributes === void 0) {
      attributes = {};
    }
    props = assign({
      className: this.buildCSSClass(),
      tabIndex: 0
    }, props);
    if (tag === "button") {
      log$1.error("Creating a ClickableComponent with an HTML element of " + tag + " is not supported; use a Button instead.");
    }
    attributes = assign({
      role: "button"
    }, attributes);
    this.tabIndex_ = props.tabIndex;
    var el = createEl(tag, props, attributes);
    el.appendChild(createEl("span", {
      className: "vjs-icon-placeholder"
    }, {
      "aria-hidden": true
    }));
    this.createControlTextEl(el);
    return el;
  };
  _proto.dispose = function dispose() {
    this.controlTextEl_ = null;
    _Component.prototype.dispose.call(this);
  };
  _proto.createControlTextEl = function createControlTextEl(el) {
    this.controlTextEl_ = createEl("span", {
      className: "vjs-control-text"
    }, {
      // let the screen reader user know that the text of the element may change
      "aria-live": "polite"
    });
    if (el) {
      el.appendChild(this.controlTextEl_);
    }
    this.controlText(this.controlText_, el);
    return this.controlTextEl_;
  };
  _proto.controlText = function controlText(text, el) {
    if (el === void 0) {
      el = this.el();
    }
    if (text === void 0) {
      return this.controlText_ || "Need Text";
    }
    var localizedText = this.localize(text);
    this.controlText_ = text;
    textContent(this.controlTextEl_, localizedText);
    if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
      el.setAttribute("title", localizedText);
    }
  };
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-control vjs-button " + _Component.prototype.buildCSSClass.call(this);
  };
  _proto.enable = function enable() {
    if (!this.enabled_) {
      this.enabled_ = true;
      this.removeClass("vjs-disabled");
      this.el_.setAttribute("aria-disabled", "false");
      if (typeof this.tabIndex_ !== "undefined") {
        this.el_.setAttribute("tabIndex", this.tabIndex_);
      }
      this.on(["tap", "click"], this.handleClick_);
      this.on("keydown", this.handleKeyDown_);
    }
  };
  _proto.disable = function disable() {
    this.enabled_ = false;
    this.addClass("vjs-disabled");
    this.el_.setAttribute("aria-disabled", "true");
    if (typeof this.tabIndex_ !== "undefined") {
      this.el_.removeAttribute("tabIndex");
    }
    this.off("mouseover", this.handleMouseOver_);
    this.off("mouseout", this.handleMouseOut_);
    this.off(["tap", "click"], this.handleClick_);
    this.off("keydown", this.handleKeyDown_);
  };
  _proto.handleLanguagechange = function handleLanguagechange() {
    this.controlText(this.controlText_);
  };
  _proto.handleClick = function handleClick(event) {
    if (this.options_.clickHandler) {
      this.options_.clickHandler.call(this, arguments);
    }
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    if (import_keycode.default.isEventKey(event, "Space") || import_keycode.default.isEventKey(event, "Enter")) {
      event.preventDefault();
      event.stopPropagation();
      this.trigger("click");
    } else {
      _Component.prototype.handleKeyDown.call(this, event);
    }
  };
  return ClickableComponent2;
}(Component$1);
Component$1.registerComponent("ClickableComponent", ClickableComponent);
var PosterImage = /* @__PURE__ */ function(_ClickableComponent) {
  _inheritsLoose(PosterImage2, _ClickableComponent);
  function PosterImage2(player, options) {
    var _this;
    _this = _ClickableComponent.call(this, player, options) || this;
    _this.update();
    _this.update_ = function(e) {
      return _this.update(e);
    };
    player.on("posterchange", _this.update_);
    return _this;
  }
  var _proto = PosterImage2.prototype;
  _proto.dispose = function dispose() {
    this.player().off("posterchange", this.update_);
    _ClickableComponent.prototype.dispose.call(this);
  };
  _proto.createEl = function createEl$1() {
    var el = createEl("div", {
      className: "vjs-poster",
      // Don't want poster to be tabbable.
      tabIndex: -1
    });
    return el;
  };
  _proto.update = function update(event) {
    var url = this.player().poster();
    this.setSrc(url);
    if (url) {
      this.show();
    } else {
      this.hide();
    }
  };
  _proto.setSrc = function setSrc(url) {
    var backgroundImage = "";
    if (url) {
      backgroundImage = 'url("' + url + '")';
    }
    this.el_.style.backgroundImage = backgroundImage;
  };
  _proto.handleClick = function handleClick(event) {
    if (!this.player_.controls()) {
      return;
    }
    var sourceIsEncrypted = this.player_.usingPlugin("eme") && this.player_.eme.sessions && this.player_.eme.sessions.length > 0;
    if (this.player_.tech(true) && // We've observed a bug in IE and Edge when playing back DRM content where
    // calling .focus() on the video element causes the video to go black,
    // so we avoid it in that specific case
    !((IE_VERSION || IS_EDGE) && sourceIsEncrypted)) {
      this.player_.tech(true).focus();
    }
    if (this.player_.paused()) {
      silencePromise(this.player_.play());
    } else {
      this.player_.pause();
    }
  };
  return PosterImage2;
}(ClickableComponent);
Component$1.registerComponent("PosterImage", PosterImage);
var darkGray = "#222";
var lightGray = "#ccc";
var fontMap = {
  monospace: "monospace",
  sansSerif: "sans-serif",
  serif: "serif",
  monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  monospaceSerif: '"Courier New", monospace',
  proportionalSansSerif: "sans-serif",
  proportionalSerif: "serif",
  casual: '"Comic Sans MS", Impact, fantasy',
  script: '"Monotype Corsiva", cursive',
  smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
};
function constructColor(color, opacity) {
  var hex;
  if (color.length === 4) {
    hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  } else if (color.length === 7) {
    hex = color.slice(1);
  } else {
    throw new Error("Invalid color code provided, " + color + "; must be formatted as e.g. #f0e or #f604e2.");
  }
  return "rgba(" + parseInt(hex.slice(0, 2), 16) + "," + parseInt(hex.slice(2, 4), 16) + "," + parseInt(hex.slice(4, 6), 16) + "," + opacity + ")";
}
function tryUpdateStyle(el, style, rule) {
  try {
    el.style[style] = rule;
  } catch (e) {
    return;
  }
}
var TextTrackDisplay = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(TextTrackDisplay2, _Component);
  function TextTrackDisplay2(player, options, ready) {
    var _this;
    _this = _Component.call(this, player, options, ready) || this;
    var updateDisplayHandler = function updateDisplayHandler2(e) {
      return _this.updateDisplay(e);
    };
    player.on("loadstart", function(e) {
      return _this.toggleDisplay(e);
    });
    player.on("texttrackchange", updateDisplayHandler);
    player.on("loadedmetadata", function(e) {
      return _this.preselectTrack(e);
    });
    player.ready(bind(_assertThisInitialized(_this), function() {
      if (player.tech_ && player.tech_.featuresNativeTextTracks) {
        this.hide();
        return;
      }
      player.on("fullscreenchange", updateDisplayHandler);
      player.on("playerresize", updateDisplayHandler);
      import_window6.default.addEventListener("orientationchange", updateDisplayHandler);
      player.on("dispose", function() {
        return import_window6.default.removeEventListener("orientationchange", updateDisplayHandler);
      });
      var tracks = this.options_.playerOptions.tracks || [];
      for (var i = 0; i < tracks.length; i++) {
        this.player_.addRemoteTextTrack(tracks[i], true);
      }
      this.preselectTrack();
    }));
    return _this;
  }
  var _proto = TextTrackDisplay2.prototype;
  _proto.preselectTrack = function preselectTrack() {
    var modes = {
      captions: 1,
      subtitles: 1
    };
    var trackList = this.player_.textTracks();
    var userPref = this.player_.cache_.selectedLanguage;
    var firstDesc;
    var firstCaptions;
    var preferredTrack;
    for (var i = 0; i < trackList.length; i++) {
      var track = trackList[i];
      if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
        if (track.kind === userPref.kind) {
          preferredTrack = track;
        } else if (!preferredTrack) {
          preferredTrack = track;
        }
      } else if (userPref && !userPref.enabled) {
        preferredTrack = null;
        firstDesc = null;
        firstCaptions = null;
      } else if (track["default"]) {
        if (track.kind === "descriptions" && !firstDesc) {
          firstDesc = track;
        } else if (track.kind in modes && !firstCaptions) {
          firstCaptions = track;
        }
      }
    }
    if (preferredTrack) {
      preferredTrack.mode = "showing";
    } else if (firstCaptions) {
      firstCaptions.mode = "showing";
    } else if (firstDesc) {
      firstDesc.mode = "showing";
    }
  };
  _proto.toggleDisplay = function toggleDisplay() {
    if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
      this.hide();
    } else {
      this.show();
    }
  };
  _proto.createEl = function createEl2() {
    return _Component.prototype.createEl.call(this, "div", {
      className: "vjs-text-track-display"
    }, {
      "translate": "yes",
      "aria-live": "off",
      "aria-atomic": "true"
    });
  };
  _proto.clearDisplay = function clearDisplay() {
    if (typeof import_window6.default.WebVTT === "function") {
      import_window6.default.WebVTT.processCues(import_window6.default, [], this.el_);
    }
  };
  _proto.updateDisplay = function updateDisplay() {
    var tracks = this.player_.textTracks();
    var allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
    this.clearDisplay();
    if (allowMultipleShowingTracks) {
      var showingTracks = [];
      for (var _i = 0; _i < tracks.length; ++_i) {
        var track = tracks[_i];
        if (track.mode !== "showing") {
          continue;
        }
        showingTracks.push(track);
      }
      this.updateForTrack(showingTracks);
      return;
    }
    var descriptionsTrack = null;
    var captionsSubtitlesTrack = null;
    var i = tracks.length;
    while (i--) {
      var _track = tracks[i];
      if (_track.mode === "showing") {
        if (_track.kind === "descriptions") {
          descriptionsTrack = _track;
        } else {
          captionsSubtitlesTrack = _track;
        }
      }
    }
    if (captionsSubtitlesTrack) {
      if (this.getAttribute("aria-live") !== "off") {
        this.setAttribute("aria-live", "off");
      }
      this.updateForTrack(captionsSubtitlesTrack);
    } else if (descriptionsTrack) {
      if (this.getAttribute("aria-live") !== "assertive") {
        this.setAttribute("aria-live", "assertive");
      }
      this.updateForTrack(descriptionsTrack);
    }
  };
  _proto.updateDisplayState = function updateDisplayState(track) {
    var overrides = this.player_.textTrackSettings.getValues();
    var cues = track.activeCues;
    var i = cues.length;
    while (i--) {
      var cue = cues[i];
      if (!cue) {
        continue;
      }
      var cueDiv = cue.displayState;
      if (overrides.color) {
        cueDiv.firstChild.style.color = overrides.color;
      }
      if (overrides.textOpacity) {
        tryUpdateStyle(cueDiv.firstChild, "color", constructColor(overrides.color || "#fff", overrides.textOpacity));
      }
      if (overrides.backgroundColor) {
        cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
      }
      if (overrides.backgroundOpacity) {
        tryUpdateStyle(cueDiv.firstChild, "backgroundColor", constructColor(overrides.backgroundColor || "#000", overrides.backgroundOpacity));
      }
      if (overrides.windowColor) {
        if (overrides.windowOpacity) {
          tryUpdateStyle(cueDiv, "backgroundColor", constructColor(overrides.windowColor, overrides.windowOpacity));
        } else {
          cueDiv.style.backgroundColor = overrides.windowColor;
        }
      }
      if (overrides.edgeStyle) {
        if (overrides.edgeStyle === "dropshadow") {
          cueDiv.firstChild.style.textShadow = "2px 2px 3px " + darkGray + ", 2px 2px 4px " + darkGray + ", 2px 2px 5px " + darkGray;
        } else if (overrides.edgeStyle === "raised") {
          cueDiv.firstChild.style.textShadow = "1px 1px " + darkGray + ", 2px 2px " + darkGray + ", 3px 3px " + darkGray;
        } else if (overrides.edgeStyle === "depressed") {
          cueDiv.firstChild.style.textShadow = "1px 1px " + lightGray + ", 0 1px " + lightGray + ", -1px -1px " + darkGray + ", 0 -1px " + darkGray;
        } else if (overrides.edgeStyle === "uniform") {
          cueDiv.firstChild.style.textShadow = "0 0 4px " + darkGray + ", 0 0 4px " + darkGray + ", 0 0 4px " + darkGray + ", 0 0 4px " + darkGray;
        }
      }
      if (overrides.fontPercent && overrides.fontPercent !== 1) {
        var fontSize = import_window6.default.parseFloat(cueDiv.style.fontSize);
        cueDiv.style.fontSize = fontSize * overrides.fontPercent + "px";
        cueDiv.style.height = "auto";
        cueDiv.style.top = "auto";
      }
      if (overrides.fontFamily && overrides.fontFamily !== "default") {
        if (overrides.fontFamily === "small-caps") {
          cueDiv.firstChild.style.fontVariant = "small-caps";
        } else {
          cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
        }
      }
    }
  };
  _proto.updateForTrack = function updateForTrack(tracks) {
    if (!Array.isArray(tracks)) {
      tracks = [tracks];
    }
    if (typeof import_window6.default.WebVTT !== "function" || tracks.every(function(track2) {
      return !track2.activeCues;
    })) {
      return;
    }
    var cues = [];
    for (var i = 0; i < tracks.length; ++i) {
      var track = tracks[i];
      for (var j = 0; j < track.activeCues.length; ++j) {
        cues.push(track.activeCues[j]);
      }
    }
    import_window6.default.WebVTT.processCues(import_window6.default, cues, this.el_);
    for (var _i2 = 0; _i2 < tracks.length; ++_i2) {
      var _track2 = tracks[_i2];
      for (var _j = 0; _j < _track2.activeCues.length; ++_j) {
        var cueEl = _track2.activeCues[_j].displayState;
        addClass(cueEl, "vjs-text-track-cue");
        addClass(cueEl, "vjs-text-track-cue-" + (_track2.language ? _track2.language : _i2));
        if (_track2.language) {
          setAttribute(cueEl, "lang", _track2.language);
        }
      }
      if (this.player_.textTrackSettings) {
        this.updateDisplayState(_track2);
      }
    }
  };
  return TextTrackDisplay2;
}(Component$1);
Component$1.registerComponent("TextTrackDisplay", TextTrackDisplay);
var LoadingSpinner = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(LoadingSpinner2, _Component);
  function LoadingSpinner2() {
    return _Component.apply(this, arguments) || this;
  }
  var _proto = LoadingSpinner2.prototype;
  _proto.createEl = function createEl$1() {
    var isAudio = this.player_.isAudio();
    var playerType = this.localize(isAudio ? "Audio Player" : "Video Player");
    var controlText = createEl("span", {
      className: "vjs-control-text",
      textContent: this.localize("{1} is loading.", [playerType])
    });
    var el = _Component.prototype.createEl.call(this, "div", {
      className: "vjs-loading-spinner",
      dir: "ltr"
    });
    el.appendChild(controlText);
    return el;
  };
  return LoadingSpinner2;
}(Component$1);
Component$1.registerComponent("LoadingSpinner", LoadingSpinner);
var Button = /* @__PURE__ */ function(_ClickableComponent) {
  _inheritsLoose(Button2, _ClickableComponent);
  function Button2() {
    return _ClickableComponent.apply(this, arguments) || this;
  }
  var _proto = Button2.prototype;
  _proto.createEl = function createEl$1(tag, props, attributes) {
    if (props === void 0) {
      props = {};
    }
    if (attributes === void 0) {
      attributes = {};
    }
    tag = "button";
    props = assign({
      className: this.buildCSSClass()
    }, props);
    attributes = assign({
      // Necessary since the default button type is "submit"
      type: "button"
    }, attributes);
    var el = createEl(tag, props, attributes);
    el.appendChild(createEl("span", {
      className: "vjs-icon-placeholder"
    }, {
      "aria-hidden": true
    }));
    this.createControlTextEl(el);
    return el;
  };
  _proto.addChild = function addChild(child, options) {
    if (options === void 0) {
      options = {};
    }
    var className = this.constructor.name;
    log$1.warn("Adding an actionable (user controllable) child to a Button (" + className + ") is not supported; use a ClickableComponent instead.");
    return Component$1.prototype.addChild.call(this, child, options);
  };
  _proto.enable = function enable() {
    _ClickableComponent.prototype.enable.call(this);
    this.el_.removeAttribute("disabled");
  };
  _proto.disable = function disable() {
    _ClickableComponent.prototype.disable.call(this);
    this.el_.setAttribute("disabled", "disabled");
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    if (import_keycode.default.isEventKey(event, "Space") || import_keycode.default.isEventKey(event, "Enter")) {
      event.stopPropagation();
      return;
    }
    _ClickableComponent.prototype.handleKeyDown.call(this, event);
  };
  return Button2;
}(ClickableComponent);
Component$1.registerComponent("Button", Button);
var BigPlayButton = /* @__PURE__ */ function(_Button) {
  _inheritsLoose(BigPlayButton2, _Button);
  function BigPlayButton2(player, options) {
    var _this;
    _this = _Button.call(this, player, options) || this;
    _this.mouseused_ = false;
    _this.on("mousedown", function(e) {
      return _this.handleMouseDown(e);
    });
    return _this;
  }
  var _proto = BigPlayButton2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-big-play-button";
  };
  _proto.handleClick = function handleClick(event) {
    var playPromise = this.player_.play();
    if (this.mouseused_ && event.clientX && event.clientY) {
      var sourceIsEncrypted = this.player_.usingPlugin("eme") && this.player_.eme.sessions && this.player_.eme.sessions.length > 0;
      silencePromise(playPromise);
      if (this.player_.tech(true) && // We've observed a bug in IE and Edge when playing back DRM content where
      // calling .focus() on the video element causes the video to go black,
      // so we avoid it in that specific case
      !((IE_VERSION || IS_EDGE) && sourceIsEncrypted)) {
        this.player_.tech(true).focus();
      }
      return;
    }
    var cb = this.player_.getChild("controlBar");
    var playToggle = cb && cb.getChild("playToggle");
    if (!playToggle) {
      this.player_.tech(true).focus();
      return;
    }
    var playFocus = function playFocus2() {
      return playToggle.focus();
    };
    if (isPromise2(playPromise)) {
      playPromise.then(playFocus, function() {
      });
    } else {
      this.setTimeout(playFocus, 1);
    }
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    this.mouseused_ = false;
    _Button.prototype.handleKeyDown.call(this, event);
  };
  _proto.handleMouseDown = function handleMouseDown(event) {
    this.mouseused_ = true;
  };
  return BigPlayButton2;
}(Button);
BigPlayButton.prototype.controlText_ = "Play Video";
Component$1.registerComponent("BigPlayButton", BigPlayButton);
var CloseButton = /* @__PURE__ */ function(_Button) {
  _inheritsLoose(CloseButton2, _Button);
  function CloseButton2(player, options) {
    var _this;
    _this = _Button.call(this, player, options) || this;
    _this.controlText(options && options.controlText || _this.localize("Close"));
    return _this;
  }
  var _proto = CloseButton2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-close-button " + _Button.prototype.buildCSSClass.call(this);
  };
  _proto.handleClick = function handleClick(event) {
    this.trigger({
      type: "close",
      bubbles: false
    });
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    if (import_keycode.default.isEventKey(event, "Esc")) {
      event.preventDefault();
      event.stopPropagation();
      this.trigger("click");
    } else {
      _Button.prototype.handleKeyDown.call(this, event);
    }
  };
  return CloseButton2;
}(Button);
Component$1.registerComponent("CloseButton", CloseButton);
var PlayToggle = /* @__PURE__ */ function(_Button) {
  _inheritsLoose(PlayToggle2, _Button);
  function PlayToggle2(player, options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    _this = _Button.call(this, player, options) || this;
    options.replay = options.replay === void 0 || options.replay;
    _this.on(player, "play", function(e) {
      return _this.handlePlay(e);
    });
    _this.on(player, "pause", function(e) {
      return _this.handlePause(e);
    });
    if (options.replay) {
      _this.on(player, "ended", function(e) {
        return _this.handleEnded(e);
      });
    }
    return _this;
  }
  var _proto = PlayToggle2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-play-control " + _Button.prototype.buildCSSClass.call(this);
  };
  _proto.handleClick = function handleClick(event) {
    if (this.player_.paused()) {
      silencePromise(this.player_.play());
    } else {
      this.player_.pause();
    }
  };
  _proto.handleSeeked = function handleSeeked(event) {
    this.removeClass("vjs-ended");
    if (this.player_.paused()) {
      this.handlePause(event);
    } else {
      this.handlePlay(event);
    }
  };
  _proto.handlePlay = function handlePlay(event) {
    this.removeClass("vjs-ended");
    this.removeClass("vjs-paused");
    this.addClass("vjs-playing");
    this.controlText("Pause");
  };
  _proto.handlePause = function handlePause(event) {
    this.removeClass("vjs-playing");
    this.addClass("vjs-paused");
    this.controlText("Play");
  };
  _proto.handleEnded = function handleEnded(event) {
    var _this2 = this;
    this.removeClass("vjs-playing");
    this.addClass("vjs-ended");
    this.controlText("Replay");
    this.one(this.player_, "seeked", function(e) {
      return _this2.handleSeeked(e);
    });
  };
  return PlayToggle2;
}(Button);
PlayToggle.prototype.controlText_ = "Play";
Component$1.registerComponent("PlayToggle", PlayToggle);
var defaultImplementation = function defaultImplementation2(seconds, guide) {
  seconds = seconds < 0 ? 0 : seconds;
  var s = Math.floor(seconds % 60);
  var m = Math.floor(seconds / 60 % 60);
  var h = Math.floor(seconds / 3600);
  var gm = Math.floor(guide / 60 % 60);
  var gh = Math.floor(guide / 3600);
  if (isNaN(seconds) || seconds === Infinity) {
    h = m = s = "-";
  }
  h = h > 0 || gh > 0 ? h + ":" : "";
  m = ((h || gm >= 10) && m < 10 ? "0" + m : m) + ":";
  s = s < 10 ? "0" + s : s;
  return h + m + s;
};
var implementation = defaultImplementation;
function setFormatTime(customImplementation) {
  implementation = customImplementation;
}
function resetFormatTime() {
  implementation = defaultImplementation;
}
function formatTime(seconds, guide) {
  if (guide === void 0) {
    guide = seconds;
  }
  return implementation(seconds, guide);
}
var TimeDisplay = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(TimeDisplay2, _Component);
  function TimeDisplay2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    _this.on(player, ["timeupdate", "ended"], function(e) {
      return _this.updateContent(e);
    });
    _this.updateTextNode_();
    return _this;
  }
  var _proto = TimeDisplay2.prototype;
  _proto.createEl = function createEl$1() {
    var className = this.buildCSSClass();
    var el = _Component.prototype.createEl.call(this, "div", {
      className: className + " vjs-time-control vjs-control"
    });
    var span = createEl("span", {
      className: "vjs-control-text",
      textContent: this.localize(this.labelText_) + "\xA0"
    }, {
      role: "presentation"
    });
    el.appendChild(span);
    this.contentEl_ = createEl("span", {
      className: className + "-display"
    }, {
      // tell screen readers not to automatically read the time as it changes
      "aria-live": "off",
      // span elements have no implicit role, but some screen readers (notably VoiceOver)
      // treat them as a break between items in the DOM when using arrow keys
      // (or left-to-right swipes on iOS) to read contents of a page. Using
      // role='presentation' causes VoiceOver to NOT treat this span as a break.
      "role": "presentation"
    });
    el.appendChild(this.contentEl_);
    return el;
  };
  _proto.dispose = function dispose() {
    this.contentEl_ = null;
    this.textNode_ = null;
    _Component.prototype.dispose.call(this);
  };
  _proto.updateTextNode_ = function updateTextNode_(time) {
    var _this2 = this;
    if (time === void 0) {
      time = 0;
    }
    time = formatTime(time);
    if (this.formattedTime_ === time) {
      return;
    }
    this.formattedTime_ = time;
    this.requestNamedAnimationFrame("TimeDisplay#updateTextNode_", function() {
      if (!_this2.contentEl_) {
        return;
      }
      var oldNode = _this2.textNode_;
      if (oldNode && _this2.contentEl_.firstChild !== oldNode) {
        oldNode = null;
        log$1.warn("TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.");
      }
      _this2.textNode_ = import_document.default.createTextNode(_this2.formattedTime_);
      if (!_this2.textNode_) {
        return;
      }
      if (oldNode) {
        _this2.contentEl_.replaceChild(_this2.textNode_, oldNode);
      } else {
        _this2.contentEl_.appendChild(_this2.textNode_);
      }
    });
  };
  _proto.updateContent = function updateContent(event) {
  };
  return TimeDisplay2;
}(Component$1);
TimeDisplay.prototype.labelText_ = "Time";
TimeDisplay.prototype.controlText_ = "Time";
Component$1.registerComponent("TimeDisplay", TimeDisplay);
var CurrentTimeDisplay = /* @__PURE__ */ function(_TimeDisplay) {
  _inheritsLoose(CurrentTimeDisplay2, _TimeDisplay);
  function CurrentTimeDisplay2() {
    return _TimeDisplay.apply(this, arguments) || this;
  }
  var _proto = CurrentTimeDisplay2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-current-time";
  };
  _proto.updateContent = function updateContent(event) {
    var time;
    if (this.player_.ended()) {
      time = this.player_.duration();
    } else {
      time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
    }
    this.updateTextNode_(time);
  };
  return CurrentTimeDisplay2;
}(TimeDisplay);
CurrentTimeDisplay.prototype.labelText_ = "Current Time";
CurrentTimeDisplay.prototype.controlText_ = "Current Time";
Component$1.registerComponent("CurrentTimeDisplay", CurrentTimeDisplay);
var DurationDisplay = /* @__PURE__ */ function(_TimeDisplay) {
  _inheritsLoose(DurationDisplay2, _TimeDisplay);
  function DurationDisplay2(player, options) {
    var _this;
    _this = _TimeDisplay.call(this, player, options) || this;
    var updateContent = function updateContent2(e) {
      return _this.updateContent(e);
    };
    _this.on(player, "durationchange", updateContent);
    _this.on(player, "loadstart", updateContent);
    _this.on(player, "loadedmetadata", updateContent);
    return _this;
  }
  var _proto = DurationDisplay2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-duration";
  };
  _proto.updateContent = function updateContent(event) {
    var duration5 = this.player_.duration();
    this.updateTextNode_(duration5);
  };
  return DurationDisplay2;
}(TimeDisplay);
DurationDisplay.prototype.labelText_ = "Duration";
DurationDisplay.prototype.controlText_ = "Duration";
Component$1.registerComponent("DurationDisplay", DurationDisplay);
var TimeDivider = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(TimeDivider2, _Component);
  function TimeDivider2() {
    return _Component.apply(this, arguments) || this;
  }
  var _proto = TimeDivider2.prototype;
  _proto.createEl = function createEl2() {
    var el = _Component.prototype.createEl.call(this, "div", {
      className: "vjs-time-control vjs-time-divider"
    }, {
      // this element and its contents can be hidden from assistive techs since
      // it is made extraneous by the announcement of the control text
      // for the current time and duration displays
      "aria-hidden": true
    });
    var div = _Component.prototype.createEl.call(this, "div");
    var span = _Component.prototype.createEl.call(this, "span", {
      textContent: "/"
    });
    div.appendChild(span);
    el.appendChild(div);
    return el;
  };
  return TimeDivider2;
}(Component$1);
Component$1.registerComponent("TimeDivider", TimeDivider);
var RemainingTimeDisplay = /* @__PURE__ */ function(_TimeDisplay) {
  _inheritsLoose(RemainingTimeDisplay2, _TimeDisplay);
  function RemainingTimeDisplay2(player, options) {
    var _this;
    _this = _TimeDisplay.call(this, player, options) || this;
    _this.on(player, "durationchange", function(e) {
      return _this.updateContent(e);
    });
    return _this;
  }
  var _proto = RemainingTimeDisplay2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-remaining-time";
  };
  _proto.createEl = function createEl$1() {
    var el = _TimeDisplay.prototype.createEl.call(this);
    if (this.options_.displayNegative !== false) {
      el.insertBefore(createEl("span", {}, {
        "aria-hidden": true
      }, "-"), this.contentEl_);
    }
    return el;
  };
  _proto.updateContent = function updateContent(event) {
    if (typeof this.player_.duration() !== "number") {
      return;
    }
    var time;
    if (this.player_.ended()) {
      time = 0;
    } else if (this.player_.remainingTimeDisplay) {
      time = this.player_.remainingTimeDisplay();
    } else {
      time = this.player_.remainingTime();
    }
    this.updateTextNode_(time);
  };
  return RemainingTimeDisplay2;
}(TimeDisplay);
RemainingTimeDisplay.prototype.labelText_ = "Remaining Time";
RemainingTimeDisplay.prototype.controlText_ = "Remaining Time";
Component$1.registerComponent("RemainingTimeDisplay", RemainingTimeDisplay);
var LiveDisplay = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(LiveDisplay2, _Component);
  function LiveDisplay2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    _this.updateShowing();
    _this.on(_this.player(), "durationchange", function(e) {
      return _this.updateShowing(e);
    });
    return _this;
  }
  var _proto = LiveDisplay2.prototype;
  _proto.createEl = function createEl$1() {
    var el = _Component.prototype.createEl.call(this, "div", {
      className: "vjs-live-control vjs-control"
    });
    this.contentEl_ = createEl("div", {
      className: "vjs-live-display"
    }, {
      "aria-live": "off"
    });
    this.contentEl_.appendChild(createEl("span", {
      className: "vjs-control-text",
      textContent: this.localize("Stream Type") + "\xA0"
    }));
    this.contentEl_.appendChild(import_document.default.createTextNode(this.localize("LIVE")));
    el.appendChild(this.contentEl_);
    return el;
  };
  _proto.dispose = function dispose() {
    this.contentEl_ = null;
    _Component.prototype.dispose.call(this);
  };
  _proto.updateShowing = function updateShowing(event) {
    if (this.player().duration() === Infinity) {
      this.show();
    } else {
      this.hide();
    }
  };
  return LiveDisplay2;
}(Component$1);
Component$1.registerComponent("LiveDisplay", LiveDisplay);
var SeekToLive = /* @__PURE__ */ function(_Button) {
  _inheritsLoose(SeekToLive2, _Button);
  function SeekToLive2(player, options) {
    var _this;
    _this = _Button.call(this, player, options) || this;
    _this.updateLiveEdgeStatus();
    if (_this.player_.liveTracker) {
      _this.updateLiveEdgeStatusHandler_ = function(e) {
        return _this.updateLiveEdgeStatus(e);
      };
      _this.on(_this.player_.liveTracker, "liveedgechange", _this.updateLiveEdgeStatusHandler_);
    }
    return _this;
  }
  var _proto = SeekToLive2.prototype;
  _proto.createEl = function createEl$1() {
    var el = _Button.prototype.createEl.call(this, "button", {
      className: "vjs-seek-to-live-control vjs-control"
    });
    this.textEl_ = createEl("span", {
      className: "vjs-seek-to-live-text",
      textContent: this.localize("LIVE")
    }, {
      "aria-hidden": "true"
    });
    el.appendChild(this.textEl_);
    return el;
  };
  _proto.updateLiveEdgeStatus = function updateLiveEdgeStatus() {
    if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
      this.setAttribute("aria-disabled", true);
      this.addClass("vjs-at-live-edge");
      this.controlText("Seek to live, currently playing live");
    } else {
      this.setAttribute("aria-disabled", false);
      this.removeClass("vjs-at-live-edge");
      this.controlText("Seek to live, currently behind live");
    }
  };
  _proto.handleClick = function handleClick() {
    this.player_.liveTracker.seekToLiveEdge();
  };
  _proto.dispose = function dispose() {
    if (this.player_.liveTracker) {
      this.off(this.player_.liveTracker, "liveedgechange", this.updateLiveEdgeStatusHandler_);
    }
    this.textEl_ = null;
    _Button.prototype.dispose.call(this);
  };
  return SeekToLive2;
}(Button);
SeekToLive.prototype.controlText_ = "Seek to live, currently playing live";
Component$1.registerComponent("SeekToLive", SeekToLive);
var clamp = function clamp2(number, min, max) {
  number = Number(number);
  return Math.min(max, Math.max(min, isNaN(number) ? min : number));
};
var Slider = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(Slider2, _Component);
  function Slider2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    _this.handleMouseDown_ = function(e) {
      return _this.handleMouseDown(e);
    };
    _this.handleMouseUp_ = function(e) {
      return _this.handleMouseUp(e);
    };
    _this.handleKeyDown_ = function(e) {
      return _this.handleKeyDown(e);
    };
    _this.handleClick_ = function(e) {
      return _this.handleClick(e);
    };
    _this.handleMouseMove_ = function(e) {
      return _this.handleMouseMove(e);
    };
    _this.update_ = function(e) {
      return _this.update(e);
    };
    _this.bar = _this.getChild(_this.options_.barName);
    _this.vertical(!!_this.options_.vertical);
    _this.enable();
    return _this;
  }
  var _proto = Slider2.prototype;
  _proto.enabled = function enabled() {
    return this.enabled_;
  };
  _proto.enable = function enable() {
    if (this.enabled()) {
      return;
    }
    this.on("mousedown", this.handleMouseDown_);
    this.on("touchstart", this.handleMouseDown_);
    this.on("keydown", this.handleKeyDown_);
    this.on("click", this.handleClick_);
    this.on(this.player_, "controlsvisible", this.update);
    if (this.playerEvent) {
      this.on(this.player_, this.playerEvent, this.update);
    }
    this.removeClass("disabled");
    this.setAttribute("tabindex", 0);
    this.enabled_ = true;
  };
  _proto.disable = function disable() {
    if (!this.enabled()) {
      return;
    }
    var doc = this.bar.el_.ownerDocument;
    this.off("mousedown", this.handleMouseDown_);
    this.off("touchstart", this.handleMouseDown_);
    this.off("keydown", this.handleKeyDown_);
    this.off("click", this.handleClick_);
    this.off(this.player_, "controlsvisible", this.update_);
    this.off(doc, "mousemove", this.handleMouseMove_);
    this.off(doc, "mouseup", this.handleMouseUp_);
    this.off(doc, "touchmove", this.handleMouseMove_);
    this.off(doc, "touchend", this.handleMouseUp_);
    this.removeAttribute("tabindex");
    this.addClass("disabled");
    if (this.playerEvent) {
      this.off(this.player_, this.playerEvent, this.update);
    }
    this.enabled_ = false;
  };
  _proto.createEl = function createEl2(type2, props, attributes) {
    if (props === void 0) {
      props = {};
    }
    if (attributes === void 0) {
      attributes = {};
    }
    props.className = props.className + " vjs-slider";
    props = assign({
      tabIndex: 0
    }, props);
    attributes = assign({
      "role": "slider",
      "aria-valuenow": 0,
      "aria-valuemin": 0,
      "aria-valuemax": 100,
      "tabIndex": 0
    }, attributes);
    return _Component.prototype.createEl.call(this, type2, props, attributes);
  };
  _proto.handleMouseDown = function handleMouseDown(event) {
    var doc = this.bar.el_.ownerDocument;
    if (event.type === "mousedown") {
      event.preventDefault();
    }
    if (event.type === "touchstart" && !IS_CHROME) {
      event.preventDefault();
    }
    blockTextSelection();
    this.addClass("vjs-sliding");
    this.trigger("slideractive");
    this.on(doc, "mousemove", this.handleMouseMove_);
    this.on(doc, "mouseup", this.handleMouseUp_);
    this.on(doc, "touchmove", this.handleMouseMove_);
    this.on(doc, "touchend", this.handleMouseUp_);
    this.handleMouseMove(event, true);
  };
  _proto.handleMouseMove = function handleMouseMove(event) {
  };
  _proto.handleMouseUp = function handleMouseUp() {
    var doc = this.bar.el_.ownerDocument;
    unblockTextSelection();
    this.removeClass("vjs-sliding");
    this.trigger("sliderinactive");
    this.off(doc, "mousemove", this.handleMouseMove_);
    this.off(doc, "mouseup", this.handleMouseUp_);
    this.off(doc, "touchmove", this.handleMouseMove_);
    this.off(doc, "touchend", this.handleMouseUp_);
    this.update();
  };
  _proto.update = function update() {
    var _this2 = this;
    if (!this.el_ || !this.bar) {
      return;
    }
    var progress = this.getProgress();
    if (progress === this.progress_) {
      return progress;
    }
    this.progress_ = progress;
    this.requestNamedAnimationFrame("Slider#update", function() {
      var sizeKey = _this2.vertical() ? "height" : "width";
      _this2.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + "%";
    });
    return progress;
  };
  _proto.getProgress = function getProgress() {
    return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  };
  _proto.calculateDistance = function calculateDistance(event) {
    var position = getPointerPosition(this.el_, event);
    if (this.vertical()) {
      return position.y;
    }
    return position.x;
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    if (import_keycode.default.isEventKey(event, "Left") || import_keycode.default.isEventKey(event, "Down")) {
      event.preventDefault();
      event.stopPropagation();
      this.stepBack();
    } else if (import_keycode.default.isEventKey(event, "Right") || import_keycode.default.isEventKey(event, "Up")) {
      event.preventDefault();
      event.stopPropagation();
      this.stepForward();
    } else {
      _Component.prototype.handleKeyDown.call(this, event);
    }
  };
  _proto.handleClick = function handleClick(event) {
    event.stopPropagation();
    event.preventDefault();
  };
  _proto.vertical = function vertical(bool) {
    if (bool === void 0) {
      return this.vertical_ || false;
    }
    this.vertical_ = !!bool;
    if (this.vertical_) {
      this.addClass("vjs-slider-vertical");
    } else {
      this.addClass("vjs-slider-horizontal");
    }
  };
  return Slider2;
}(Component$1);
Component$1.registerComponent("Slider", Slider);
var percentify = function percentify2(time, end) {
  return clamp(time / end * 100, 0, 100).toFixed(2) + "%";
};
var LoadProgressBar = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(LoadProgressBar2, _Component);
  function LoadProgressBar2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    _this.partEls_ = [];
    _this.on(player, "progress", function(e) {
      return _this.update(e);
    });
    return _this;
  }
  var _proto = LoadProgressBar2.prototype;
  _proto.createEl = function createEl$1() {
    var el = _Component.prototype.createEl.call(this, "div", {
      className: "vjs-load-progress"
    });
    var wrapper = createEl("span", {
      className: "vjs-control-text"
    });
    var loadedText = createEl("span", {
      textContent: this.localize("Loaded")
    });
    var separator = import_document.default.createTextNode(": ");
    this.percentageEl_ = createEl("span", {
      className: "vjs-control-text-loaded-percentage",
      textContent: "0%"
    });
    el.appendChild(wrapper);
    wrapper.appendChild(loadedText);
    wrapper.appendChild(separator);
    wrapper.appendChild(this.percentageEl_);
    return el;
  };
  _proto.dispose = function dispose() {
    this.partEls_ = null;
    this.percentageEl_ = null;
    _Component.prototype.dispose.call(this);
  };
  _proto.update = function update(event) {
    var _this2 = this;
    this.requestNamedAnimationFrame("LoadProgressBar#update", function() {
      var liveTracker = _this2.player_.liveTracker;
      var buffered = _this2.player_.buffered();
      var duration5 = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : _this2.player_.duration();
      var bufferedEnd = _this2.player_.bufferedEnd();
      var children = _this2.partEls_;
      var percent = percentify(bufferedEnd, duration5);
      if (_this2.percent_ !== percent) {
        _this2.el_.style.width = percent;
        textContent(_this2.percentageEl_, percent);
        _this2.percent_ = percent;
      }
      for (var i = 0; i < buffered.length; i++) {
        var start2 = buffered.start(i);
        var end = buffered.end(i);
        var part = children[i];
        if (!part) {
          part = _this2.el_.appendChild(createEl());
          children[i] = part;
        }
        if (part.dataset.start === start2 && part.dataset.end === end) {
          continue;
        }
        part.dataset.start = start2;
        part.dataset.end = end;
        part.style.left = percentify(start2, bufferedEnd);
        part.style.width = percentify(end - start2, bufferedEnd);
      }
      for (var _i = children.length; _i > buffered.length; _i--) {
        _this2.el_.removeChild(children[_i - 1]);
      }
      children.length = buffered.length;
    });
  };
  return LoadProgressBar2;
}(Component$1);
Component$1.registerComponent("LoadProgressBar", LoadProgressBar);
var TimeTooltip = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(TimeTooltip2, _Component);
  function TimeTooltip2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    _this.update = throttle(bind(_assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
    return _this;
  }
  var _proto = TimeTooltip2.prototype;
  _proto.createEl = function createEl2() {
    return _Component.prototype.createEl.call(this, "div", {
      className: "vjs-time-tooltip"
    }, {
      "aria-hidden": "true"
    });
  };
  _proto.update = function update(seekBarRect, seekBarPoint, content) {
    var tooltipRect = findPosition(this.el_);
    var playerRect = getBoundingClientRect(this.player_.el());
    var seekBarPointPx = seekBarRect.width * seekBarPoint;
    if (!playerRect || !tooltipRect) {
      return;
    }
    var spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx;
    var spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right);
    var pullTooltipBy = tooltipRect.width / 2;
    if (spaceLeftOfPoint < pullTooltipBy) {
      pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
    } else if (spaceRightOfPoint < pullTooltipBy) {
      pullTooltipBy = spaceRightOfPoint;
    }
    if (pullTooltipBy < 0) {
      pullTooltipBy = 0;
    } else if (pullTooltipBy > tooltipRect.width) {
      pullTooltipBy = tooltipRect.width;
    }
    pullTooltipBy = Math.round(pullTooltipBy);
    this.el_.style.right = "-" + pullTooltipBy + "px";
    this.write(content);
  };
  _proto.write = function write(content) {
    textContent(this.el_, content);
  };
  _proto.updateTime = function updateTime(seekBarRect, seekBarPoint, time, cb) {
    var _this2 = this;
    this.requestNamedAnimationFrame("TimeTooltip#updateTime", function() {
      var content;
      var duration5 = _this2.player_.duration();
      if (_this2.player_.liveTracker && _this2.player_.liveTracker.isLive()) {
        var liveWindow = _this2.player_.liveTracker.liveWindow();
        var secondsBehind = liveWindow - seekBarPoint * liveWindow;
        content = (secondsBehind < 1 ? "" : "-") + formatTime(secondsBehind, liveWindow);
      } else {
        content = formatTime(time, duration5);
      }
      _this2.update(seekBarRect, seekBarPoint, content);
      if (cb) {
        cb();
      }
    });
  };
  return TimeTooltip2;
}(Component$1);
Component$1.registerComponent("TimeTooltip", TimeTooltip);
var PlayProgressBar = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(PlayProgressBar2, _Component);
  function PlayProgressBar2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    _this.update = throttle(bind(_assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
    return _this;
  }
  var _proto = PlayProgressBar2.prototype;
  _proto.createEl = function createEl2() {
    return _Component.prototype.createEl.call(this, "div", {
      className: "vjs-play-progress vjs-slider-bar"
    }, {
      "aria-hidden": "true"
    });
  };
  _proto.update = function update(seekBarRect, seekBarPoint) {
    var timeTooltip = this.getChild("timeTooltip");
    if (!timeTooltip) {
      return;
    }
    var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
    timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  };
  return PlayProgressBar2;
}(Component$1);
PlayProgressBar.prototype.options_ = {
  children: []
};
if (!IS_IOS && !IS_ANDROID) {
  PlayProgressBar.prototype.options_.children.push("timeTooltip");
}
Component$1.registerComponent("PlayProgressBar", PlayProgressBar);
var MouseTimeDisplay = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(MouseTimeDisplay2, _Component);
  function MouseTimeDisplay2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    _this.update = throttle(bind(_assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
    return _this;
  }
  var _proto = MouseTimeDisplay2.prototype;
  _proto.createEl = function createEl2() {
    return _Component.prototype.createEl.call(this, "div", {
      className: "vjs-mouse-display"
    });
  };
  _proto.update = function update(seekBarRect, seekBarPoint) {
    var _this2 = this;
    var time = seekBarPoint * this.player_.duration();
    this.getChild("timeTooltip").updateTime(seekBarRect, seekBarPoint, time, function() {
      _this2.el_.style.left = seekBarRect.width * seekBarPoint + "px";
    });
  };
  return MouseTimeDisplay2;
}(Component$1);
MouseTimeDisplay.prototype.options_ = {
  children: ["timeTooltip"]
};
Component$1.registerComponent("MouseTimeDisplay", MouseTimeDisplay);
var STEP_SECONDS = 5;
var PAGE_KEY_MULTIPLIER = 12;
var SeekBar = /* @__PURE__ */ function(_Slider) {
  _inheritsLoose(SeekBar2, _Slider);
  function SeekBar2(player, options) {
    var _this;
    _this = _Slider.call(this, player, options) || this;
    _this.setEventHandlers_();
    return _this;
  }
  var _proto = SeekBar2.prototype;
  _proto.setEventHandlers_ = function setEventHandlers_() {
    var _this2 = this;
    this.update_ = bind(this, this.update);
    this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
    this.on(this.player_, ["ended", "durationchange", "timeupdate"], this.update);
    if (this.player_.liveTracker) {
      this.on(this.player_.liveTracker, "liveedgechange", this.update);
    }
    this.updateInterval = null;
    this.enableIntervalHandler_ = function(e) {
      return _this2.enableInterval_(e);
    };
    this.disableIntervalHandler_ = function(e) {
      return _this2.disableInterval_(e);
    };
    this.on(this.player_, ["playing"], this.enableIntervalHandler_);
    this.on(this.player_, ["ended", "pause", "waiting"], this.disableIntervalHandler_);
    if ("hidden" in import_document.default && "visibilityState" in import_document.default) {
      this.on(import_document.default, "visibilitychange", this.toggleVisibility_);
    }
  };
  _proto.toggleVisibility_ = function toggleVisibility_(e) {
    if (import_document.default.visibilityState === "hidden") {
      this.cancelNamedAnimationFrame("SeekBar#update");
      this.cancelNamedAnimationFrame("Slider#update");
      this.disableInterval_(e);
    } else {
      if (!this.player_.ended() && !this.player_.paused()) {
        this.enableInterval_();
      }
      this.update();
    }
  };
  _proto.enableInterval_ = function enableInterval_() {
    if (this.updateInterval) {
      return;
    }
    this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  };
  _proto.disableInterval_ = function disableInterval_(e) {
    if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== "ended") {
      return;
    }
    if (!this.updateInterval) {
      return;
    }
    this.clearInterval(this.updateInterval);
    this.updateInterval = null;
  };
  _proto.createEl = function createEl2() {
    return _Slider.prototype.createEl.call(this, "div", {
      className: "vjs-progress-holder"
    }, {
      "aria-label": this.localize("Progress Bar")
    });
  };
  _proto.update = function update(event) {
    var _this3 = this;
    if (import_document.default.visibilityState === "hidden") {
      return;
    }
    var percent = _Slider.prototype.update.call(this);
    this.requestNamedAnimationFrame("SeekBar#update", function() {
      var currentTime = _this3.player_.ended() ? _this3.player_.duration() : _this3.getCurrentTime_();
      var liveTracker = _this3.player_.liveTracker;
      var duration5 = _this3.player_.duration();
      if (liveTracker && liveTracker.isLive()) {
        duration5 = _this3.player_.liveTracker.liveCurrentTime();
      }
      if (_this3.percent_ !== percent) {
        _this3.el_.setAttribute("aria-valuenow", (percent * 100).toFixed(2));
        _this3.percent_ = percent;
      }
      if (_this3.currentTime_ !== currentTime || _this3.duration_ !== duration5) {
        _this3.el_.setAttribute("aria-valuetext", _this3.localize("progress bar timing: currentTime={1} duration={2}", [formatTime(currentTime, duration5), formatTime(duration5, duration5)], "{1} of {2}"));
        _this3.currentTime_ = currentTime;
        _this3.duration_ = duration5;
      }
      if (_this3.bar) {
        _this3.bar.update(getBoundingClientRect(_this3.el()), _this3.getProgress());
      }
    });
    return percent;
  };
  _proto.userSeek_ = function userSeek_(ct) {
    if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
      this.player_.liveTracker.nextSeekedFromUser();
    }
    this.player_.currentTime(ct);
  };
  _proto.getCurrentTime_ = function getCurrentTime_() {
    return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  };
  _proto.getPercent = function getPercent() {
    var currentTime = this.getCurrentTime_();
    var percent;
    var liveTracker = this.player_.liveTracker;
    if (liveTracker && liveTracker.isLive()) {
      percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow();
      if (liveTracker.atLiveEdge()) {
        percent = 1;
      }
    } else {
      percent = currentTime / this.player_.duration();
    }
    return percent;
  };
  _proto.handleMouseDown = function handleMouseDown(event) {
    if (!isSingleLeftClick(event)) {
      return;
    }
    event.stopPropagation();
    this.videoWasPlaying = !this.player_.paused();
    this.player_.pause();
    _Slider.prototype.handleMouseDown.call(this, event);
  };
  _proto.handleMouseMove = function handleMouseMove(event, mouseDown) {
    if (mouseDown === void 0) {
      mouseDown = false;
    }
    if (!isSingleLeftClick(event)) {
      return;
    }
    if (!mouseDown && !this.player_.scrubbing()) {
      this.player_.scrubbing(true);
    }
    var newTime;
    var distance = this.calculateDistance(event);
    var liveTracker = this.player_.liveTracker;
    if (!liveTracker || !liveTracker.isLive()) {
      newTime = distance * this.player_.duration();
      if (newTime === this.player_.duration()) {
        newTime = newTime - 0.1;
      }
    } else {
      if (distance >= 0.99) {
        liveTracker.seekToLiveEdge();
        return;
      }
      var seekableStart = liveTracker.seekableStart();
      var seekableEnd = liveTracker.liveCurrentTime();
      newTime = seekableStart + distance * liveTracker.liveWindow();
      if (newTime >= seekableEnd) {
        newTime = seekableEnd;
      }
      if (newTime <= seekableStart) {
        newTime = seekableStart + 0.1;
      }
      if (newTime === Infinity) {
        return;
      }
    }
    this.userSeek_(newTime);
  };
  _proto.enable = function enable() {
    _Slider.prototype.enable.call(this);
    var mouseTimeDisplay = this.getChild("mouseTimeDisplay");
    if (!mouseTimeDisplay) {
      return;
    }
    mouseTimeDisplay.show();
  };
  _proto.disable = function disable() {
    _Slider.prototype.disable.call(this);
    var mouseTimeDisplay = this.getChild("mouseTimeDisplay");
    if (!mouseTimeDisplay) {
      return;
    }
    mouseTimeDisplay.hide();
  };
  _proto.handleMouseUp = function handleMouseUp(event) {
    _Slider.prototype.handleMouseUp.call(this, event);
    if (event) {
      event.stopPropagation();
    }
    this.player_.scrubbing(false);
    this.player_.trigger({
      type: "timeupdate",
      target: this,
      manuallyTriggered: true
    });
    if (this.videoWasPlaying) {
      silencePromise(this.player_.play());
    } else {
      this.update_();
    }
  };
  _proto.stepForward = function stepForward() {
    this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  };
  _proto.stepBack = function stepBack() {
    this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  };
  _proto.handleAction = function handleAction(event) {
    if (this.player_.paused()) {
      this.player_.play();
    } else {
      this.player_.pause();
    }
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    var liveTracker = this.player_.liveTracker;
    if (import_keycode.default.isEventKey(event, "Space") || import_keycode.default.isEventKey(event, "Enter")) {
      event.preventDefault();
      event.stopPropagation();
      this.handleAction(event);
    } else if (import_keycode.default.isEventKey(event, "Home")) {
      event.preventDefault();
      event.stopPropagation();
      this.userSeek_(0);
    } else if (import_keycode.default.isEventKey(event, "End")) {
      event.preventDefault();
      event.stopPropagation();
      if (liveTracker && liveTracker.isLive()) {
        this.userSeek_(liveTracker.liveCurrentTime());
      } else {
        this.userSeek_(this.player_.duration());
      }
    } else if (/^[0-9]$/.test((0, import_keycode.default)(event))) {
      event.preventDefault();
      event.stopPropagation();
      var gotoFraction = (import_keycode.default.codes[(0, import_keycode.default)(event)] - import_keycode.default.codes["0"]) * 10 / 100;
      if (liveTracker && liveTracker.isLive()) {
        this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
      } else {
        this.userSeek_(this.player_.duration() * gotoFraction);
      }
    } else if (import_keycode.default.isEventKey(event, "PgDn")) {
      event.preventDefault();
      event.stopPropagation();
      this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
    } else if (import_keycode.default.isEventKey(event, "PgUp")) {
      event.preventDefault();
      event.stopPropagation();
      this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
    } else {
      _Slider.prototype.handleKeyDown.call(this, event);
    }
  };
  _proto.dispose = function dispose() {
    this.disableInterval_();
    this.off(this.player_, ["ended", "durationchange", "timeupdate"], this.update);
    if (this.player_.liveTracker) {
      this.off(this.player_.liveTracker, "liveedgechange", this.update);
    }
    this.off(this.player_, ["playing"], this.enableIntervalHandler_);
    this.off(this.player_, ["ended", "pause", "waiting"], this.disableIntervalHandler_);
    if ("hidden" in import_document.default && "visibilityState" in import_document.default) {
      this.off(import_document.default, "visibilitychange", this.toggleVisibility_);
    }
    _Slider.prototype.dispose.call(this);
  };
  return SeekBar2;
}(Slider);
SeekBar.prototype.options_ = {
  children: ["loadProgressBar", "playProgressBar"],
  barName: "playProgressBar"
};
if (!IS_IOS && !IS_ANDROID) {
  SeekBar.prototype.options_.children.splice(1, 0, "mouseTimeDisplay");
}
Component$1.registerComponent("SeekBar", SeekBar);
var ProgressControl = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(ProgressControl2, _Component);
  function ProgressControl2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    _this.handleMouseMove = throttle(bind(_assertThisInitialized(_this), _this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
    _this.throttledHandleMouseSeek = throttle(bind(_assertThisInitialized(_this), _this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
    _this.handleMouseUpHandler_ = function(e) {
      return _this.handleMouseUp(e);
    };
    _this.handleMouseDownHandler_ = function(e) {
      return _this.handleMouseDown(e);
    };
    _this.enable();
    return _this;
  }
  var _proto = ProgressControl2.prototype;
  _proto.createEl = function createEl2() {
    return _Component.prototype.createEl.call(this, "div", {
      className: "vjs-progress-control vjs-control"
    });
  };
  _proto.handleMouseMove = function handleMouseMove(event) {
    var seekBar = this.getChild("seekBar");
    if (!seekBar) {
      return;
    }
    var playProgressBar = seekBar.getChild("playProgressBar");
    var mouseTimeDisplay = seekBar.getChild("mouseTimeDisplay");
    if (!playProgressBar && !mouseTimeDisplay) {
      return;
    }
    var seekBarEl = seekBar.el();
    var seekBarRect = findPosition(seekBarEl);
    var seekBarPoint = getPointerPosition(seekBarEl, event).x;
    seekBarPoint = clamp(seekBarPoint, 0, 1);
    if (mouseTimeDisplay) {
      mouseTimeDisplay.update(seekBarRect, seekBarPoint);
    }
    if (playProgressBar) {
      playProgressBar.update(seekBarRect, seekBar.getProgress());
    }
  };
  _proto.handleMouseSeek = function handleMouseSeek(event) {
    var seekBar = this.getChild("seekBar");
    if (seekBar) {
      seekBar.handleMouseMove(event);
    }
  };
  _proto.enabled = function enabled() {
    return this.enabled_;
  };
  _proto.disable = function disable() {
    this.children().forEach(function(child) {
      return child.disable && child.disable();
    });
    if (!this.enabled()) {
      return;
    }
    this.off(["mousedown", "touchstart"], this.handleMouseDownHandler_);
    this.off(this.el_, "mousemove", this.handleMouseMove);
    this.removeListenersAddedOnMousedownAndTouchstart();
    this.addClass("disabled");
    this.enabled_ = false;
    if (this.player_.scrubbing()) {
      var seekBar = this.getChild("seekBar");
      this.player_.scrubbing(false);
      if (seekBar.videoWasPlaying) {
        silencePromise(this.player_.play());
      }
    }
  };
  _proto.enable = function enable() {
    this.children().forEach(function(child) {
      return child.enable && child.enable();
    });
    if (this.enabled()) {
      return;
    }
    this.on(["mousedown", "touchstart"], this.handleMouseDownHandler_);
    this.on(this.el_, "mousemove", this.handleMouseMove);
    this.removeClass("disabled");
    this.enabled_ = true;
  };
  _proto.removeListenersAddedOnMousedownAndTouchstart = function removeListenersAddedOnMousedownAndTouchstart() {
    var doc = this.el_.ownerDocument;
    this.off(doc, "mousemove", this.throttledHandleMouseSeek);
    this.off(doc, "touchmove", this.throttledHandleMouseSeek);
    this.off(doc, "mouseup", this.handleMouseUpHandler_);
    this.off(doc, "touchend", this.handleMouseUpHandler_);
  };
  _proto.handleMouseDown = function handleMouseDown(event) {
    var doc = this.el_.ownerDocument;
    var seekBar = this.getChild("seekBar");
    if (seekBar) {
      seekBar.handleMouseDown(event);
    }
    this.on(doc, "mousemove", this.throttledHandleMouseSeek);
    this.on(doc, "touchmove", this.throttledHandleMouseSeek);
    this.on(doc, "mouseup", this.handleMouseUpHandler_);
    this.on(doc, "touchend", this.handleMouseUpHandler_);
  };
  _proto.handleMouseUp = function handleMouseUp(event) {
    var seekBar = this.getChild("seekBar");
    if (seekBar) {
      seekBar.handleMouseUp(event);
    }
    this.removeListenersAddedOnMousedownAndTouchstart();
  };
  return ProgressControl2;
}(Component$1);
ProgressControl.prototype.options_ = {
  children: ["seekBar"]
};
Component$1.registerComponent("ProgressControl", ProgressControl);
var PictureInPictureToggle = /* @__PURE__ */ function(_Button) {
  _inheritsLoose(PictureInPictureToggle2, _Button);
  function PictureInPictureToggle2(player, options) {
    var _this;
    _this = _Button.call(this, player, options) || this;
    _this.on(player, ["enterpictureinpicture", "leavepictureinpicture"], function(e) {
      return _this.handlePictureInPictureChange(e);
    });
    _this.on(player, ["disablepictureinpicturechanged", "loadedmetadata"], function(e) {
      return _this.handlePictureInPictureEnabledChange(e);
    });
    _this.on(player, ["loadedmetadata", "audioonlymodechange", "audiopostermodechange"], function() {
      var isSourceAudio = player.currentType().substring(0, 5) === "audio";
      if (isSourceAudio || player.audioPosterMode() || player.audioOnlyMode()) {
        if (player.isInPictureInPicture()) {
          player.exitPictureInPicture();
        }
        _this.hide();
      } else {
        _this.show();
      }
    });
    _this.disable();
    return _this;
  }
  var _proto = PictureInPictureToggle2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-picture-in-picture-control " + _Button.prototype.buildCSSClass.call(this);
  };
  _proto.handlePictureInPictureEnabledChange = function handlePictureInPictureEnabledChange() {
    if (import_document.default.pictureInPictureEnabled && this.player_.disablePictureInPicture() === false) {
      this.enable();
    } else {
      this.disable();
    }
  };
  _proto.handlePictureInPictureChange = function handlePictureInPictureChange(event) {
    if (this.player_.isInPictureInPicture()) {
      this.controlText("Exit Picture-in-Picture");
    } else {
      this.controlText("Picture-in-Picture");
    }
    this.handlePictureInPictureEnabledChange();
  };
  _proto.handleClick = function handleClick(event) {
    if (!this.player_.isInPictureInPicture()) {
      this.player_.requestPictureInPicture();
    } else {
      this.player_.exitPictureInPicture();
    }
  };
  return PictureInPictureToggle2;
}(Button);
PictureInPictureToggle.prototype.controlText_ = "Picture-in-Picture";
Component$1.registerComponent("PictureInPictureToggle", PictureInPictureToggle);
var FullscreenToggle = /* @__PURE__ */ function(_Button) {
  _inheritsLoose(FullscreenToggle2, _Button);
  function FullscreenToggle2(player, options) {
    var _this;
    _this = _Button.call(this, player, options) || this;
    _this.on(player, "fullscreenchange", function(e) {
      return _this.handleFullscreenChange(e);
    });
    if (import_document.default[player.fsApi_.fullscreenEnabled] === false) {
      _this.disable();
    }
    return _this;
  }
  var _proto = FullscreenToggle2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-fullscreen-control " + _Button.prototype.buildCSSClass.call(this);
  };
  _proto.handleFullscreenChange = function handleFullscreenChange(event) {
    if (this.player_.isFullscreen()) {
      this.controlText("Non-Fullscreen");
    } else {
      this.controlText("Fullscreen");
    }
  };
  _proto.handleClick = function handleClick(event) {
    if (!this.player_.isFullscreen()) {
      this.player_.requestFullscreen();
    } else {
      this.player_.exitFullscreen();
    }
  };
  return FullscreenToggle2;
}(Button);
FullscreenToggle.prototype.controlText_ = "Fullscreen";
Component$1.registerComponent("FullscreenToggle", FullscreenToggle);
var checkVolumeSupport = function checkVolumeSupport2(self2, player) {
  if (player.tech_ && !player.tech_.featuresVolumeControl) {
    self2.addClass("vjs-hidden");
  }
  self2.on(player, "loadstart", function() {
    if (!player.tech_.featuresVolumeControl) {
      self2.addClass("vjs-hidden");
    } else {
      self2.removeClass("vjs-hidden");
    }
  });
};
var VolumeLevel = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(VolumeLevel2, _Component);
  function VolumeLevel2() {
    return _Component.apply(this, arguments) || this;
  }
  var _proto = VolumeLevel2.prototype;
  _proto.createEl = function createEl2() {
    var el = _Component.prototype.createEl.call(this, "div", {
      className: "vjs-volume-level"
    });
    el.appendChild(_Component.prototype.createEl.call(this, "span", {
      className: "vjs-control-text"
    }));
    return el;
  };
  return VolumeLevel2;
}(Component$1);
Component$1.registerComponent("VolumeLevel", VolumeLevel);
var VolumeLevelTooltip = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(VolumeLevelTooltip2, _Component);
  function VolumeLevelTooltip2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    _this.update = throttle(bind(_assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
    return _this;
  }
  var _proto = VolumeLevelTooltip2.prototype;
  _proto.createEl = function createEl2() {
    return _Component.prototype.createEl.call(this, "div", {
      className: "vjs-volume-tooltip"
    }, {
      "aria-hidden": "true"
    });
  };
  _proto.update = function update(rangeBarRect, rangeBarPoint, vertical, content) {
    if (!vertical) {
      var tooltipRect = getBoundingClientRect(this.el_);
      var playerRect = getBoundingClientRect(this.player_.el());
      var volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
      if (!playerRect || !tooltipRect) {
        return;
      }
      var spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
      var spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
      var pullTooltipBy = tooltipRect.width / 2;
      if (spaceLeftOfPoint < pullTooltipBy) {
        pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
      } else if (spaceRightOfPoint < pullTooltipBy) {
        pullTooltipBy = spaceRightOfPoint;
      }
      if (pullTooltipBy < 0) {
        pullTooltipBy = 0;
      } else if (pullTooltipBy > tooltipRect.width) {
        pullTooltipBy = tooltipRect.width;
      }
      this.el_.style.right = "-" + pullTooltipBy + "px";
    }
    this.write(content + "%");
  };
  _proto.write = function write(content) {
    textContent(this.el_, content);
  };
  _proto.updateVolume = function updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
    var _this2 = this;
    this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume", function() {
      _this2.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
      if (cb) {
        cb();
      }
    });
  };
  return VolumeLevelTooltip2;
}(Component$1);
Component$1.registerComponent("VolumeLevelTooltip", VolumeLevelTooltip);
var MouseVolumeLevelDisplay = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(MouseVolumeLevelDisplay2, _Component);
  function MouseVolumeLevelDisplay2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    _this.update = throttle(bind(_assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
    return _this;
  }
  var _proto = MouseVolumeLevelDisplay2.prototype;
  _proto.createEl = function createEl2() {
    return _Component.prototype.createEl.call(this, "div", {
      className: "vjs-mouse-display"
    });
  };
  _proto.update = function update(rangeBarRect, rangeBarPoint, vertical) {
    var _this2 = this;
    var volume = 100 * rangeBarPoint;
    this.getChild("volumeLevelTooltip").updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, function() {
      if (vertical) {
        _this2.el_.style.bottom = rangeBarRect.height * rangeBarPoint + "px";
      } else {
        _this2.el_.style.left = rangeBarRect.width * rangeBarPoint + "px";
      }
    });
  };
  return MouseVolumeLevelDisplay2;
}(Component$1);
MouseVolumeLevelDisplay.prototype.options_ = {
  children: ["volumeLevelTooltip"]
};
Component$1.registerComponent("MouseVolumeLevelDisplay", MouseVolumeLevelDisplay);
var VolumeBar = /* @__PURE__ */ function(_Slider) {
  _inheritsLoose(VolumeBar2, _Slider);
  function VolumeBar2(player, options) {
    var _this;
    _this = _Slider.call(this, player, options) || this;
    _this.on("slideractive", function(e) {
      return _this.updateLastVolume_(e);
    });
    _this.on(player, "volumechange", function(e) {
      return _this.updateARIAAttributes(e);
    });
    player.ready(function() {
      return _this.updateARIAAttributes();
    });
    return _this;
  }
  var _proto = VolumeBar2.prototype;
  _proto.createEl = function createEl2() {
    return _Slider.prototype.createEl.call(this, "div", {
      className: "vjs-volume-bar vjs-slider-bar"
    }, {
      "aria-label": this.localize("Volume Level"),
      "aria-live": "polite"
    });
  };
  _proto.handleMouseDown = function handleMouseDown(event) {
    if (!isSingleLeftClick(event)) {
      return;
    }
    _Slider.prototype.handleMouseDown.call(this, event);
  };
  _proto.handleMouseMove = function handleMouseMove(event) {
    var mouseVolumeLevelDisplay = this.getChild("mouseVolumeLevelDisplay");
    if (mouseVolumeLevelDisplay) {
      var volumeBarEl = this.el();
      var volumeBarRect = getBoundingClientRect(volumeBarEl);
      var vertical = this.vertical();
      var volumeBarPoint = getPointerPosition(volumeBarEl, event);
      volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x;
      volumeBarPoint = clamp(volumeBarPoint, 0, 1);
      mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
    }
    if (!isSingleLeftClick(event)) {
      return;
    }
    this.checkMuted();
    this.player_.volume(this.calculateDistance(event));
  };
  _proto.checkMuted = function checkMuted() {
    if (this.player_.muted()) {
      this.player_.muted(false);
    }
  };
  _proto.getPercent = function getPercent() {
    if (this.player_.muted()) {
      return 0;
    }
    return this.player_.volume();
  };
  _proto.stepForward = function stepForward() {
    this.checkMuted();
    this.player_.volume(this.player_.volume() + 0.1);
  };
  _proto.stepBack = function stepBack() {
    this.checkMuted();
    this.player_.volume(this.player_.volume() - 0.1);
  };
  _proto.updateARIAAttributes = function updateARIAAttributes(event) {
    var ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
    this.el_.setAttribute("aria-valuenow", ariaValue);
    this.el_.setAttribute("aria-valuetext", ariaValue + "%");
  };
  _proto.volumeAsPercentage_ = function volumeAsPercentage_() {
    return Math.round(this.player_.volume() * 100);
  };
  _proto.updateLastVolume_ = function updateLastVolume_() {
    var _this2 = this;
    var volumeBeforeDrag = this.player_.volume();
    this.one("sliderinactive", function() {
      if (_this2.player_.volume() === 0) {
        _this2.player_.lastVolume_(volumeBeforeDrag);
      }
    });
  };
  return VolumeBar2;
}(Slider);
VolumeBar.prototype.options_ = {
  children: ["volumeLevel"],
  barName: "volumeLevel"
};
if (!IS_IOS && !IS_ANDROID) {
  VolumeBar.prototype.options_.children.splice(0, 0, "mouseVolumeLevelDisplay");
}
VolumeBar.prototype.playerEvent = "volumechange";
Component$1.registerComponent("VolumeBar", VolumeBar);
var VolumeControl = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(VolumeControl2, _Component);
  function VolumeControl2(player, options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    options.vertical = options.vertical || false;
    if (typeof options.volumeBar === "undefined" || isPlain(options.volumeBar)) {
      options.volumeBar = options.volumeBar || {};
      options.volumeBar.vertical = options.vertical;
    }
    _this = _Component.call(this, player, options) || this;
    checkVolumeSupport(_assertThisInitialized(_this), player);
    _this.throttledHandleMouseMove = throttle(bind(_assertThisInitialized(_this), _this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
    _this.handleMouseUpHandler_ = function(e) {
      return _this.handleMouseUp(e);
    };
    _this.on("mousedown", function(e) {
      return _this.handleMouseDown(e);
    });
    _this.on("touchstart", function(e) {
      return _this.handleMouseDown(e);
    });
    _this.on("mousemove", function(e) {
      return _this.handleMouseMove(e);
    });
    _this.on(_this.volumeBar, ["focus", "slideractive"], function() {
      _this.volumeBar.addClass("vjs-slider-active");
      _this.addClass("vjs-slider-active");
      _this.trigger("slideractive");
    });
    _this.on(_this.volumeBar, ["blur", "sliderinactive"], function() {
      _this.volumeBar.removeClass("vjs-slider-active");
      _this.removeClass("vjs-slider-active");
      _this.trigger("sliderinactive");
    });
    return _this;
  }
  var _proto = VolumeControl2.prototype;
  _proto.createEl = function createEl2() {
    var orientationClass = "vjs-volume-horizontal";
    if (this.options_.vertical) {
      orientationClass = "vjs-volume-vertical";
    }
    return _Component.prototype.createEl.call(this, "div", {
      className: "vjs-volume-control vjs-control " + orientationClass
    });
  };
  _proto.handleMouseDown = function handleMouseDown(event) {
    var doc = this.el_.ownerDocument;
    this.on(doc, "mousemove", this.throttledHandleMouseMove);
    this.on(doc, "touchmove", this.throttledHandleMouseMove);
    this.on(doc, "mouseup", this.handleMouseUpHandler_);
    this.on(doc, "touchend", this.handleMouseUpHandler_);
  };
  _proto.handleMouseUp = function handleMouseUp(event) {
    var doc = this.el_.ownerDocument;
    this.off(doc, "mousemove", this.throttledHandleMouseMove);
    this.off(doc, "touchmove", this.throttledHandleMouseMove);
    this.off(doc, "mouseup", this.handleMouseUpHandler_);
    this.off(doc, "touchend", this.handleMouseUpHandler_);
  };
  _proto.handleMouseMove = function handleMouseMove(event) {
    this.volumeBar.handleMouseMove(event);
  };
  return VolumeControl2;
}(Component$1);
VolumeControl.prototype.options_ = {
  children: ["volumeBar"]
};
Component$1.registerComponent("VolumeControl", VolumeControl);
var checkMuteSupport = function checkMuteSupport2(self2, player) {
  if (player.tech_ && !player.tech_.featuresMuteControl) {
    self2.addClass("vjs-hidden");
  }
  self2.on(player, "loadstart", function() {
    if (!player.tech_.featuresMuteControl) {
      self2.addClass("vjs-hidden");
    } else {
      self2.removeClass("vjs-hidden");
    }
  });
};
var MuteToggle = /* @__PURE__ */ function(_Button) {
  _inheritsLoose(MuteToggle2, _Button);
  function MuteToggle2(player, options) {
    var _this;
    _this = _Button.call(this, player, options) || this;
    checkMuteSupport(_assertThisInitialized(_this), player);
    _this.on(player, ["loadstart", "volumechange"], function(e) {
      return _this.update(e);
    });
    return _this;
  }
  var _proto = MuteToggle2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-mute-control " + _Button.prototype.buildCSSClass.call(this);
  };
  _proto.handleClick = function handleClick(event) {
    var vol = this.player_.volume();
    var lastVolume = this.player_.lastVolume_();
    if (vol === 0) {
      var volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
      this.player_.volume(volumeToSet);
      this.player_.muted(false);
    } else {
      this.player_.muted(this.player_.muted() ? false : true);
    }
  };
  _proto.update = function update(event) {
    this.updateIcon_();
    this.updateControlText_();
  };
  _proto.updateIcon_ = function updateIcon_() {
    var vol = this.player_.volume();
    var level = 3;
    if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
      this.player_.muted(this.player_.tech_.el_.muted);
    }
    if (vol === 0 || this.player_.muted()) {
      level = 0;
    } else if (vol < 0.33) {
      level = 1;
    } else if (vol < 0.67) {
      level = 2;
    }
    for (var i = 0; i < 4; i++) {
      removeClass(this.el_, "vjs-vol-" + i);
    }
    addClass(this.el_, "vjs-vol-" + level);
  };
  _proto.updateControlText_ = function updateControlText_() {
    var soundOff = this.player_.muted() || this.player_.volume() === 0;
    var text = soundOff ? "Unmute" : "Mute";
    if (this.controlText() !== text) {
      this.controlText(text);
    }
  };
  return MuteToggle2;
}(Button);
MuteToggle.prototype.controlText_ = "Mute";
Component$1.registerComponent("MuteToggle", MuteToggle);
var VolumePanel = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(VolumePanel2, _Component);
  function VolumePanel2(player, options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    if (typeof options.inline !== "undefined") {
      options.inline = options.inline;
    } else {
      options.inline = true;
    }
    if (typeof options.volumeControl === "undefined" || isPlain(options.volumeControl)) {
      options.volumeControl = options.volumeControl || {};
      options.volumeControl.vertical = !options.inline;
    }
    _this = _Component.call(this, player, options) || this;
    _this.handleKeyPressHandler_ = function(e) {
      return _this.handleKeyPress(e);
    };
    _this.on(player, ["loadstart"], function(e) {
      return _this.volumePanelState_(e);
    });
    _this.on(_this.muteToggle, "keyup", function(e) {
      return _this.handleKeyPress(e);
    });
    _this.on(_this.volumeControl, "keyup", function(e) {
      return _this.handleVolumeControlKeyUp(e);
    });
    _this.on("keydown", function(e) {
      return _this.handleKeyPress(e);
    });
    _this.on("mouseover", function(e) {
      return _this.handleMouseOver(e);
    });
    _this.on("mouseout", function(e) {
      return _this.handleMouseOut(e);
    });
    _this.on(_this.volumeControl, ["slideractive"], _this.sliderActive_);
    _this.on(_this.volumeControl, ["sliderinactive"], _this.sliderInactive_);
    return _this;
  }
  var _proto = VolumePanel2.prototype;
  _proto.sliderActive_ = function sliderActive_() {
    this.addClass("vjs-slider-active");
  };
  _proto.sliderInactive_ = function sliderInactive_() {
    this.removeClass("vjs-slider-active");
  };
  _proto.volumePanelState_ = function volumePanelState_() {
    if (this.volumeControl.hasClass("vjs-hidden") && this.muteToggle.hasClass("vjs-hidden")) {
      this.addClass("vjs-hidden");
    }
    if (this.volumeControl.hasClass("vjs-hidden") && !this.muteToggle.hasClass("vjs-hidden")) {
      this.addClass("vjs-mute-toggle-only");
    }
  };
  _proto.createEl = function createEl2() {
    var orientationClass = "vjs-volume-panel-horizontal";
    if (!this.options_.inline) {
      orientationClass = "vjs-volume-panel-vertical";
    }
    return _Component.prototype.createEl.call(this, "div", {
      className: "vjs-volume-panel vjs-control " + orientationClass
    });
  };
  _proto.dispose = function dispose() {
    this.handleMouseOut();
    _Component.prototype.dispose.call(this);
  };
  _proto.handleVolumeControlKeyUp = function handleVolumeControlKeyUp(event) {
    if (import_keycode.default.isEventKey(event, "Esc")) {
      this.muteToggle.focus();
    }
  };
  _proto.handleMouseOver = function handleMouseOver(event) {
    this.addClass("vjs-hover");
    on(import_document.default, "keyup", this.handleKeyPressHandler_);
  };
  _proto.handleMouseOut = function handleMouseOut(event) {
    this.removeClass("vjs-hover");
    off(import_document.default, "keyup", this.handleKeyPressHandler_);
  };
  _proto.handleKeyPress = function handleKeyPress(event) {
    if (import_keycode.default.isEventKey(event, "Esc")) {
      this.handleMouseOut();
    }
  };
  return VolumePanel2;
}(Component$1);
VolumePanel.prototype.options_ = {
  children: ["muteToggle", "volumeControl"]
};
Component$1.registerComponent("VolumePanel", VolumePanel);
var Menu = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(Menu2, _Component);
  function Menu2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    if (options) {
      _this.menuButton_ = options.menuButton;
    }
    _this.focusedChild_ = -1;
    _this.on("keydown", function(e) {
      return _this.handleKeyDown(e);
    });
    _this.boundHandleBlur_ = function(e) {
      return _this.handleBlur(e);
    };
    _this.boundHandleTapClick_ = function(e) {
      return _this.handleTapClick(e);
    };
    return _this;
  }
  var _proto = Menu2.prototype;
  _proto.addEventListenerForItem = function addEventListenerForItem(component) {
    if (!(component instanceof Component$1)) {
      return;
    }
    this.on(component, "blur", this.boundHandleBlur_);
    this.on(component, ["tap", "click"], this.boundHandleTapClick_);
  };
  _proto.removeEventListenerForItem = function removeEventListenerForItem(component) {
    if (!(component instanceof Component$1)) {
      return;
    }
    this.off(component, "blur", this.boundHandleBlur_);
    this.off(component, ["tap", "click"], this.boundHandleTapClick_);
  };
  _proto.removeChild = function removeChild(component) {
    if (typeof component === "string") {
      component = this.getChild(component);
    }
    this.removeEventListenerForItem(component);
    _Component.prototype.removeChild.call(this, component);
  };
  _proto.addItem = function addItem(component) {
    var childComponent = this.addChild(component);
    if (childComponent) {
      this.addEventListenerForItem(childComponent);
    }
  };
  _proto.createEl = function createEl$1() {
    var contentElType = this.options_.contentElType || "ul";
    this.contentEl_ = createEl(contentElType, {
      className: "vjs-menu-content"
    });
    this.contentEl_.setAttribute("role", "menu");
    var el = _Component.prototype.createEl.call(this, "div", {
      append: this.contentEl_,
      className: "vjs-menu"
    });
    el.appendChild(this.contentEl_);
    on(el, "click", function(event) {
      event.preventDefault();
      event.stopImmediatePropagation();
    });
    return el;
  };
  _proto.dispose = function dispose() {
    this.contentEl_ = null;
    this.boundHandleBlur_ = null;
    this.boundHandleTapClick_ = null;
    _Component.prototype.dispose.call(this);
  };
  _proto.handleBlur = function handleBlur(event) {
    var relatedTarget = event.relatedTarget || import_document.default.activeElement;
    if (!this.children().some(function(element) {
      return element.el() === relatedTarget;
    })) {
      var btn = this.menuButton_;
      if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
        btn.unpressButton();
      }
    }
  };
  _proto.handleTapClick = function handleTapClick(event) {
    if (this.menuButton_) {
      this.menuButton_.unpressButton();
      var childComponents = this.children();
      if (!Array.isArray(childComponents)) {
        return;
      }
      var foundComponent = childComponents.filter(function(component) {
        return component.el() === event.target;
      })[0];
      if (!foundComponent) {
        return;
      }
      if (foundComponent.name() !== "CaptionSettingsMenuItem") {
        this.menuButton_.focus();
      }
    }
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    if (import_keycode.default.isEventKey(event, "Left") || import_keycode.default.isEventKey(event, "Down")) {
      event.preventDefault();
      event.stopPropagation();
      this.stepForward();
    } else if (import_keycode.default.isEventKey(event, "Right") || import_keycode.default.isEventKey(event, "Up")) {
      event.preventDefault();
      event.stopPropagation();
      this.stepBack();
    }
  };
  _proto.stepForward = function stepForward() {
    var stepChild = 0;
    if (this.focusedChild_ !== void 0) {
      stepChild = this.focusedChild_ + 1;
    }
    this.focus(stepChild);
  };
  _proto.stepBack = function stepBack() {
    var stepChild = 0;
    if (this.focusedChild_ !== void 0) {
      stepChild = this.focusedChild_ - 1;
    }
    this.focus(stepChild);
  };
  _proto.focus = function focus(item) {
    if (item === void 0) {
      item = 0;
    }
    var children = this.children().slice();
    var haveTitle = children.length && children[0].hasClass("vjs-menu-title");
    if (haveTitle) {
      children.shift();
    }
    if (children.length > 0) {
      if (item < 0) {
        item = 0;
      } else if (item >= children.length) {
        item = children.length - 1;
      }
      this.focusedChild_ = item;
      children[item].el_.focus();
    }
  };
  return Menu2;
}(Component$1);
Component$1.registerComponent("Menu", Menu);
var MenuButton = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(MenuButton3, _Component);
  function MenuButton3(player, options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    _this = _Component.call(this, player, options) || this;
    _this.menuButton_ = new Button(player, options);
    _this.menuButton_.controlText(_this.controlText_);
    _this.menuButton_.el_.setAttribute("aria-haspopup", "true");
    var buttonClass = Button.prototype.buildCSSClass();
    _this.menuButton_.el_.className = _this.buildCSSClass() + " " + buttonClass;
    _this.menuButton_.removeClass("vjs-control");
    _this.addChild(_this.menuButton_);
    _this.update();
    _this.enabled_ = true;
    var handleClick = function handleClick2(e) {
      return _this.handleClick(e);
    };
    _this.handleMenuKeyUp_ = function(e) {
      return _this.handleMenuKeyUp(e);
    };
    _this.on(_this.menuButton_, "tap", handleClick);
    _this.on(_this.menuButton_, "click", handleClick);
    _this.on(_this.menuButton_, "keydown", function(e) {
      return _this.handleKeyDown(e);
    });
    _this.on(_this.menuButton_, "mouseenter", function() {
      _this.addClass("vjs-hover");
      _this.menu.show();
      on(import_document.default, "keyup", _this.handleMenuKeyUp_);
    });
    _this.on("mouseleave", function(e) {
      return _this.handleMouseLeave(e);
    });
    _this.on("keydown", function(e) {
      return _this.handleSubmenuKeyDown(e);
    });
    return _this;
  }
  var _proto = MenuButton3.prototype;
  _proto.update = function update() {
    var menu = this.createMenu();
    if (this.menu) {
      this.menu.dispose();
      this.removeChild(this.menu);
    }
    this.menu = menu;
    this.addChild(menu);
    this.buttonPressed_ = false;
    this.menuButton_.el_.setAttribute("aria-expanded", "false");
    if (this.items && this.items.length <= this.hideThreshold_) {
      this.hide();
      this.menu.contentEl_.removeAttribute("role");
    } else {
      this.show();
      this.menu.contentEl_.setAttribute("role", "menu");
    }
  };
  _proto.createMenu = function createMenu() {
    var menu = new Menu(this.player_, {
      menuButton: this
    });
    this.hideThreshold_ = 0;
    if (this.options_.title) {
      var titleEl = createEl("li", {
        className: "vjs-menu-title",
        textContent: toTitleCase$1(this.options_.title),
        tabIndex: -1
      });
      var titleComponent = new Component$1(this.player_, {
        el: titleEl
      });
      menu.addItem(titleComponent);
    }
    this.items = this.createItems();
    if (this.items) {
      for (var i = 0; i < this.items.length; i++) {
        menu.addItem(this.items[i]);
      }
    }
    return menu;
  };
  _proto.createItems = function createItems() {
  };
  _proto.createEl = function createEl2() {
    return _Component.prototype.createEl.call(this, "div", {
      className: this.buildWrapperCSSClass()
    }, {});
  };
  _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
    var menuButtonClass = "vjs-menu-button";
    if (this.options_.inline === true) {
      menuButtonClass += "-inline";
    } else {
      menuButtonClass += "-popup";
    }
    var buttonClass = Button.prototype.buildCSSClass();
    return "vjs-menu-button " + menuButtonClass + " " + buttonClass + " " + _Component.prototype.buildCSSClass.call(this);
  };
  _proto.buildCSSClass = function buildCSSClass() {
    var menuButtonClass = "vjs-menu-button";
    if (this.options_.inline === true) {
      menuButtonClass += "-inline";
    } else {
      menuButtonClass += "-popup";
    }
    return "vjs-menu-button " + menuButtonClass + " " + _Component.prototype.buildCSSClass.call(this);
  };
  _proto.controlText = function controlText(text, el) {
    if (el === void 0) {
      el = this.menuButton_.el();
    }
    return this.menuButton_.controlText(text, el);
  };
  _proto.dispose = function dispose() {
    this.handleMouseLeave();
    _Component.prototype.dispose.call(this);
  };
  _proto.handleClick = function handleClick(event) {
    if (this.buttonPressed_) {
      this.unpressButton();
    } else {
      this.pressButton();
    }
  };
  _proto.handleMouseLeave = function handleMouseLeave(event) {
    this.removeClass("vjs-hover");
    off(import_document.default, "keyup", this.handleMenuKeyUp_);
  };
  _proto.focus = function focus() {
    this.menuButton_.focus();
  };
  _proto.blur = function blur() {
    this.menuButton_.blur();
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    if (import_keycode.default.isEventKey(event, "Esc") || import_keycode.default.isEventKey(event, "Tab")) {
      if (this.buttonPressed_) {
        this.unpressButton();
      }
      if (!import_keycode.default.isEventKey(event, "Tab")) {
        event.preventDefault();
        this.menuButton_.focus();
      }
    } else if (import_keycode.default.isEventKey(event, "Up") || import_keycode.default.isEventKey(event, "Down")) {
      if (!this.buttonPressed_) {
        event.preventDefault();
        this.pressButton();
      }
    }
  };
  _proto.handleMenuKeyUp = function handleMenuKeyUp(event) {
    if (import_keycode.default.isEventKey(event, "Esc") || import_keycode.default.isEventKey(event, "Tab")) {
      this.removeClass("vjs-hover");
    }
  };
  _proto.handleSubmenuKeyPress = function handleSubmenuKeyPress(event) {
    this.handleSubmenuKeyDown(event);
  };
  _proto.handleSubmenuKeyDown = function handleSubmenuKeyDown(event) {
    if (import_keycode.default.isEventKey(event, "Esc") || import_keycode.default.isEventKey(event, "Tab")) {
      if (this.buttonPressed_) {
        this.unpressButton();
      }
      if (!import_keycode.default.isEventKey(event, "Tab")) {
        event.preventDefault();
        this.menuButton_.focus();
      }
    }
  };
  _proto.pressButton = function pressButton() {
    if (this.enabled_) {
      this.buttonPressed_ = true;
      this.menu.show();
      this.menu.lockShowing();
      this.menuButton_.el_.setAttribute("aria-expanded", "true");
      if (IS_IOS && isInFrame()) {
        return;
      }
      this.menu.focus();
    }
  };
  _proto.unpressButton = function unpressButton() {
    if (this.enabled_) {
      this.buttonPressed_ = false;
      this.menu.unlockShowing();
      this.menu.hide();
      this.menuButton_.el_.setAttribute("aria-expanded", "false");
    }
  };
  _proto.disable = function disable() {
    this.unpressButton();
    this.enabled_ = false;
    this.addClass("vjs-disabled");
    this.menuButton_.disable();
  };
  _proto.enable = function enable() {
    this.enabled_ = true;
    this.removeClass("vjs-disabled");
    this.menuButton_.enable();
  };
  return MenuButton3;
}(Component$1);
Component$1.registerComponent("MenuButton", MenuButton);
var TrackButton = /* @__PURE__ */ function(_MenuButton) {
  _inheritsLoose(TrackButton2, _MenuButton);
  function TrackButton2(player, options) {
    var _this;
    var tracks = options.tracks;
    _this = _MenuButton.call(this, player, options) || this;
    if (_this.items.length <= 1) {
      _this.hide();
    }
    if (!tracks) {
      return _assertThisInitialized(_this);
    }
    var updateHandler = bind(_assertThisInitialized(_this), _this.update);
    tracks.addEventListener("removetrack", updateHandler);
    tracks.addEventListener("addtrack", updateHandler);
    tracks.addEventListener("labelchange", updateHandler);
    _this.player_.on("ready", updateHandler);
    _this.player_.on("dispose", function() {
      tracks.removeEventListener("removetrack", updateHandler);
      tracks.removeEventListener("addtrack", updateHandler);
      tracks.removeEventListener("labelchange", updateHandler);
    });
    return _this;
  }
  return TrackButton2;
}(MenuButton);
Component$1.registerComponent("TrackButton", TrackButton);
var MenuKeys = ["Tab", "Esc", "Up", "Down", "Right", "Left"];
var MenuItem = /* @__PURE__ */ function(_ClickableComponent) {
  _inheritsLoose(MenuItem2, _ClickableComponent);
  function MenuItem2(player, options) {
    var _this;
    _this = _ClickableComponent.call(this, player, options) || this;
    _this.selectable = options.selectable;
    _this.isSelected_ = options.selected || false;
    _this.multiSelectable = options.multiSelectable;
    _this.selected(_this.isSelected_);
    if (_this.selectable) {
      if (_this.multiSelectable) {
        _this.el_.setAttribute("role", "menuitemcheckbox");
      } else {
        _this.el_.setAttribute("role", "menuitemradio");
      }
    } else {
      _this.el_.setAttribute("role", "menuitem");
    }
    return _this;
  }
  var _proto = MenuItem2.prototype;
  _proto.createEl = function createEl$1(type2, props, attrs) {
    this.nonIconControl = true;
    var el = _ClickableComponent.prototype.createEl.call(this, "li", assign({
      className: "vjs-menu-item",
      tabIndex: -1
    }, props), attrs);
    el.replaceChild(createEl("span", {
      className: "vjs-menu-item-text",
      textContent: this.localize(this.options_.label)
    }), el.querySelector(".vjs-icon-placeholder"));
    return el;
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    if (!MenuKeys.some(function(key) {
      return import_keycode.default.isEventKey(event, key);
    })) {
      _ClickableComponent.prototype.handleKeyDown.call(this, event);
    }
  };
  _proto.handleClick = function handleClick(event) {
    this.selected(true);
  };
  _proto.selected = function selected(_selected) {
    if (this.selectable) {
      if (_selected) {
        this.addClass("vjs-selected");
        this.el_.setAttribute("aria-checked", "true");
        this.controlText(", selected");
        this.isSelected_ = true;
      } else {
        this.removeClass("vjs-selected");
        this.el_.setAttribute("aria-checked", "false");
        this.controlText("");
        this.isSelected_ = false;
      }
    }
  };
  return MenuItem2;
}(ClickableComponent);
Component$1.registerComponent("MenuItem", MenuItem);
var TextTrackMenuItem = /* @__PURE__ */ function(_MenuItem) {
  _inheritsLoose(TextTrackMenuItem2, _MenuItem);
  function TextTrackMenuItem2(player, options) {
    var _this;
    var track = options.track;
    var tracks = player.textTracks();
    options.label = track.label || track.language || "Unknown";
    options.selected = track.mode === "showing";
    _this = _MenuItem.call(this, player, options) || this;
    _this.track = track;
    _this.kinds = (options.kinds || [options.kind || _this.track.kind]).filter(Boolean);
    var changeHandler = function changeHandler2() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      _this.handleTracksChange.apply(_assertThisInitialized(_this), args);
    };
    var selectedLanguageChangeHandler = function selectedLanguageChangeHandler2() {
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }
      _this.handleSelectedLanguageChange.apply(_assertThisInitialized(_this), args);
    };
    player.on(["loadstart", "texttrackchange"], changeHandler);
    tracks.addEventListener("change", changeHandler);
    tracks.addEventListener("selectedlanguagechange", selectedLanguageChangeHandler);
    _this.on("dispose", function() {
      player.off(["loadstart", "texttrackchange"], changeHandler);
      tracks.removeEventListener("change", changeHandler);
      tracks.removeEventListener("selectedlanguagechange", selectedLanguageChangeHandler);
    });
    if (tracks.onchange === void 0) {
      var event;
      _this.on(["tap", "click"], function() {
        if (typeof import_window6.default.Event !== "object") {
          try {
            event = new import_window6.default.Event("change");
          } catch (err) {
          }
        }
        if (!event) {
          event = import_document.default.createEvent("Event");
          event.initEvent("change", true, true);
        }
        tracks.dispatchEvent(event);
      });
    }
    _this.handleTracksChange();
    return _this;
  }
  var _proto = TextTrackMenuItem2.prototype;
  _proto.handleClick = function handleClick(event) {
    var referenceTrack = this.track;
    var tracks = this.player_.textTracks();
    _MenuItem.prototype.handleClick.call(this, event);
    if (!tracks) {
      return;
    }
    for (var i = 0; i < tracks.length; i++) {
      var track = tracks[i];
      if (this.kinds.indexOf(track.kind) === -1) {
        continue;
      }
      if (track === referenceTrack) {
        if (track.mode !== "showing") {
          track.mode = "showing";
        }
      } else if (track.mode !== "disabled") {
        track.mode = "disabled";
      }
    }
  };
  _proto.handleTracksChange = function handleTracksChange(event) {
    var shouldBeSelected = this.track.mode === "showing";
    if (shouldBeSelected !== this.isSelected_) {
      this.selected(shouldBeSelected);
    }
  };
  _proto.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) {
    if (this.track.mode === "showing") {
      var selectedLanguage = this.player_.cache_.selectedLanguage;
      if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
        return;
      }
      this.player_.cache_.selectedLanguage = {
        enabled: true,
        language: this.track.language,
        kind: this.track.kind
      };
    }
  };
  _proto.dispose = function dispose() {
    this.track = null;
    _MenuItem.prototype.dispose.call(this);
  };
  return TextTrackMenuItem2;
}(MenuItem);
Component$1.registerComponent("TextTrackMenuItem", TextTrackMenuItem);
var OffTextTrackMenuItem = /* @__PURE__ */ function(_TextTrackMenuItem) {
  _inheritsLoose(OffTextTrackMenuItem2, _TextTrackMenuItem);
  function OffTextTrackMenuItem2(player, options) {
    options.track = {
      player,
      // it is no longer necessary to store `kind` or `kinds` on the track itself
      // since they are now stored in the `kinds` property of all instances of
      // TextTrackMenuItem, but this will remain for backwards compatibility
      kind: options.kind,
      kinds: options.kinds,
      "default": false,
      mode: "disabled"
    };
    if (!options.kinds) {
      options.kinds = [options.kind];
    }
    if (options.label) {
      options.track.label = options.label;
    } else {
      options.track.label = options.kinds.join(" and ") + " off";
    }
    options.selectable = true;
    options.multiSelectable = false;
    return _TextTrackMenuItem.call(this, player, options) || this;
  }
  var _proto = OffTextTrackMenuItem2.prototype;
  _proto.handleTracksChange = function handleTracksChange(event) {
    var tracks = this.player().textTracks();
    var shouldBeSelected = true;
    for (var i = 0, l = tracks.length; i < l; i++) {
      var track = tracks[i];
      if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === "showing") {
        shouldBeSelected = false;
        break;
      }
    }
    if (shouldBeSelected !== this.isSelected_) {
      this.selected(shouldBeSelected);
    }
  };
  _proto.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) {
    var tracks = this.player().textTracks();
    var allHidden = true;
    for (var i = 0, l = tracks.length; i < l; i++) {
      var track = tracks[i];
      if (["captions", "descriptions", "subtitles"].indexOf(track.kind) > -1 && track.mode === "showing") {
        allHidden = false;
        break;
      }
    }
    if (allHidden) {
      this.player_.cache_.selectedLanguage = {
        enabled: false
      };
    }
  };
  return OffTextTrackMenuItem2;
}(TextTrackMenuItem);
Component$1.registerComponent("OffTextTrackMenuItem", OffTextTrackMenuItem);
var TextTrackButton = /* @__PURE__ */ function(_TrackButton) {
  _inheritsLoose(TextTrackButton2, _TrackButton);
  function TextTrackButton2(player, options) {
    if (options === void 0) {
      options = {};
    }
    options.tracks = player.textTracks();
    return _TrackButton.call(this, player, options) || this;
  }
  var _proto = TextTrackButton2.prototype;
  _proto.createItems = function createItems(items, TrackMenuItem) {
    if (items === void 0) {
      items = [];
    }
    if (TrackMenuItem === void 0) {
      TrackMenuItem = TextTrackMenuItem;
    }
    var label;
    if (this.label_) {
      label = this.label_ + " off";
    }
    items.push(new OffTextTrackMenuItem(this.player_, {
      kinds: this.kinds_,
      kind: this.kind_,
      label
    }));
    this.hideThreshold_ += 1;
    var tracks = this.player_.textTracks();
    if (!Array.isArray(this.kinds_)) {
      this.kinds_ = [this.kind_];
    }
    for (var i = 0; i < tracks.length; i++) {
      var track = tracks[i];
      if (this.kinds_.indexOf(track.kind) > -1) {
        var item = new TrackMenuItem(this.player_, {
          track,
          kinds: this.kinds_,
          kind: this.kind_,
          // MenuItem is selectable
          selectable: true,
          // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
          multiSelectable: false
        });
        item.addClass("vjs-" + track.kind + "-menu-item");
        items.push(item);
      }
    }
    return items;
  };
  return TextTrackButton2;
}(TrackButton);
Component$1.registerComponent("TextTrackButton", TextTrackButton);
var ChaptersTrackMenuItem = /* @__PURE__ */ function(_MenuItem) {
  _inheritsLoose(ChaptersTrackMenuItem2, _MenuItem);
  function ChaptersTrackMenuItem2(player, options) {
    var _this;
    var track = options.track;
    var cue = options.cue;
    var currentTime = player.currentTime();
    options.selectable = true;
    options.multiSelectable = false;
    options.label = cue.text;
    options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
    _this = _MenuItem.call(this, player, options) || this;
    _this.track = track;
    _this.cue = cue;
    return _this;
  }
  var _proto = ChaptersTrackMenuItem2.prototype;
  _proto.handleClick = function handleClick(event) {
    _MenuItem.prototype.handleClick.call(this);
    this.player_.currentTime(this.cue.startTime);
  };
  return ChaptersTrackMenuItem2;
}(MenuItem);
Component$1.registerComponent("ChaptersTrackMenuItem", ChaptersTrackMenuItem);
var ChaptersButton = /* @__PURE__ */ function(_TextTrackButton) {
  _inheritsLoose(ChaptersButton2, _TextTrackButton);
  function ChaptersButton2(player, options, ready) {
    var _this;
    _this = _TextTrackButton.call(this, player, options, ready) || this;
    _this.selectCurrentItem_ = function() {
      _this.items.forEach(function(item) {
        item.selected(_this.track_.activeCues[0] === item.cue);
      });
    };
    return _this;
  }
  var _proto = ChaptersButton2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-chapters-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  };
  _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
    return "vjs-chapters-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  };
  _proto.update = function update(event) {
    if (event && event.track && event.track.kind !== "chapters") {
      return;
    }
    var track = this.findChaptersTrack();
    if (track !== this.track_) {
      this.setTrack(track);
      _TextTrackButton.prototype.update.call(this);
    } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
      _TextTrackButton.prototype.update.call(this);
    }
  };
  _proto.setTrack = function setTrack(track) {
    if (this.track_ === track) {
      return;
    }
    if (!this.updateHandler_) {
      this.updateHandler_ = this.update.bind(this);
    }
    if (this.track_) {
      var remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
      if (remoteTextTrackEl) {
        remoteTextTrackEl.removeEventListener("load", this.updateHandler_);
      }
      this.track_.removeEventListener("cuechange", this.selectCurrentItem_);
      this.track_ = null;
    }
    this.track_ = track;
    if (this.track_) {
      this.track_.mode = "hidden";
      var _remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
      if (_remoteTextTrackEl) {
        _remoteTextTrackEl.addEventListener("load", this.updateHandler_);
      }
      this.track_.addEventListener("cuechange", this.selectCurrentItem_);
    }
  };
  _proto.findChaptersTrack = function findChaptersTrack() {
    var tracks = this.player_.textTracks() || [];
    for (var i = tracks.length - 1; i >= 0; i--) {
      var track = tracks[i];
      if (track.kind === this.kind_) {
        return track;
      }
    }
  };
  _proto.getMenuCaption = function getMenuCaption() {
    if (this.track_ && this.track_.label) {
      return this.track_.label;
    }
    return this.localize(toTitleCase$1(this.kind_));
  };
  _proto.createMenu = function createMenu() {
    this.options_.title = this.getMenuCaption();
    return _TextTrackButton.prototype.createMenu.call(this);
  };
  _proto.createItems = function createItems() {
    var items = [];
    if (!this.track_) {
      return items;
    }
    var cues = this.track_.cues;
    if (!cues) {
      return items;
    }
    for (var i = 0, l = cues.length; i < l; i++) {
      var cue = cues[i];
      var mi = new ChaptersTrackMenuItem(this.player_, {
        track: this.track_,
        cue
      });
      items.push(mi);
    }
    return items;
  };
  return ChaptersButton2;
}(TextTrackButton);
ChaptersButton.prototype.kind_ = "chapters";
ChaptersButton.prototype.controlText_ = "Chapters";
Component$1.registerComponent("ChaptersButton", ChaptersButton);
var DescriptionsButton = /* @__PURE__ */ function(_TextTrackButton) {
  _inheritsLoose(DescriptionsButton2, _TextTrackButton);
  function DescriptionsButton2(player, options, ready) {
    var _this;
    _this = _TextTrackButton.call(this, player, options, ready) || this;
    var tracks = player.textTracks();
    var changeHandler = bind(_assertThisInitialized(_this), _this.handleTracksChange);
    tracks.addEventListener("change", changeHandler);
    _this.on("dispose", function() {
      tracks.removeEventListener("change", changeHandler);
    });
    return _this;
  }
  var _proto = DescriptionsButton2.prototype;
  _proto.handleTracksChange = function handleTracksChange(event) {
    var tracks = this.player().textTracks();
    var disabled = false;
    for (var i = 0, l = tracks.length; i < l; i++) {
      var track = tracks[i];
      if (track.kind !== this.kind_ && track.mode === "showing") {
        disabled = true;
        break;
      }
    }
    if (disabled) {
      this.disable();
    } else {
      this.enable();
    }
  };
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-descriptions-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  };
  _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
    return "vjs-descriptions-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  };
  return DescriptionsButton2;
}(TextTrackButton);
DescriptionsButton.prototype.kind_ = "descriptions";
DescriptionsButton.prototype.controlText_ = "Descriptions";
Component$1.registerComponent("DescriptionsButton", DescriptionsButton);
var SubtitlesButton = /* @__PURE__ */ function(_TextTrackButton) {
  _inheritsLoose(SubtitlesButton2, _TextTrackButton);
  function SubtitlesButton2(player, options, ready) {
    return _TextTrackButton.call(this, player, options, ready) || this;
  }
  var _proto = SubtitlesButton2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-subtitles-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  };
  _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
    return "vjs-subtitles-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  };
  return SubtitlesButton2;
}(TextTrackButton);
SubtitlesButton.prototype.kind_ = "subtitles";
SubtitlesButton.prototype.controlText_ = "Subtitles";
Component$1.registerComponent("SubtitlesButton", SubtitlesButton);
var CaptionSettingsMenuItem = /* @__PURE__ */ function(_TextTrackMenuItem) {
  _inheritsLoose(CaptionSettingsMenuItem2, _TextTrackMenuItem);
  function CaptionSettingsMenuItem2(player, options) {
    var _this;
    options.track = {
      player,
      kind: options.kind,
      label: options.kind + " settings",
      selectable: false,
      "default": false,
      mode: "disabled"
    };
    options.selectable = false;
    options.name = "CaptionSettingsMenuItem";
    _this = _TextTrackMenuItem.call(this, player, options) || this;
    _this.addClass("vjs-texttrack-settings");
    _this.controlText(", opens " + options.kind + " settings dialog");
    return _this;
  }
  var _proto = CaptionSettingsMenuItem2.prototype;
  _proto.handleClick = function handleClick(event) {
    this.player().getChild("textTrackSettings").open();
  };
  return CaptionSettingsMenuItem2;
}(TextTrackMenuItem);
Component$1.registerComponent("CaptionSettingsMenuItem", CaptionSettingsMenuItem);
var CaptionsButton = /* @__PURE__ */ function(_TextTrackButton) {
  _inheritsLoose(CaptionsButton2, _TextTrackButton);
  function CaptionsButton2(player, options, ready) {
    return _TextTrackButton.call(this, player, options, ready) || this;
  }
  var _proto = CaptionsButton2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-captions-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  };
  _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
    return "vjs-captions-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  };
  _proto.createItems = function createItems() {
    var items = [];
    if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild("textTrackSettings")) {
      items.push(new CaptionSettingsMenuItem(this.player_, {
        kind: this.kind_
      }));
      this.hideThreshold_ += 1;
    }
    return _TextTrackButton.prototype.createItems.call(this, items);
  };
  return CaptionsButton2;
}(TextTrackButton);
CaptionsButton.prototype.kind_ = "captions";
CaptionsButton.prototype.controlText_ = "Captions";
Component$1.registerComponent("CaptionsButton", CaptionsButton);
var SubsCapsMenuItem = /* @__PURE__ */ function(_TextTrackMenuItem) {
  _inheritsLoose(SubsCapsMenuItem2, _TextTrackMenuItem);
  function SubsCapsMenuItem2() {
    return _TextTrackMenuItem.apply(this, arguments) || this;
  }
  var _proto = SubsCapsMenuItem2.prototype;
  _proto.createEl = function createEl$1(type2, props, attrs) {
    var el = _TextTrackMenuItem.prototype.createEl.call(this, type2, props, attrs);
    var parentSpan = el.querySelector(".vjs-menu-item-text");
    if (this.options_.track.kind === "captions") {
      parentSpan.appendChild(createEl("span", {
        className: "vjs-icon-placeholder"
      }, {
        "aria-hidden": true
      }));
      parentSpan.appendChild(createEl("span", {
        className: "vjs-control-text",
        // space added as the text will visually flow with the
        // label
        textContent: " " + this.localize("Captions")
      }));
    }
    return el;
  };
  return SubsCapsMenuItem2;
}(TextTrackMenuItem);
Component$1.registerComponent("SubsCapsMenuItem", SubsCapsMenuItem);
var SubsCapsButton = /* @__PURE__ */ function(_TextTrackButton) {
  _inheritsLoose(SubsCapsButton2, _TextTrackButton);
  function SubsCapsButton2(player, options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    _this = _TextTrackButton.call(this, player, options) || this;
    _this.label_ = "subtitles";
    if (["en", "en-us", "en-ca", "fr-ca"].indexOf(_this.player_.language_) > -1) {
      _this.label_ = "captions";
    }
    _this.menuButton_.controlText(toTitleCase$1(_this.label_));
    return _this;
  }
  var _proto = SubsCapsButton2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-subs-caps-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  };
  _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
    return "vjs-subs-caps-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  };
  _proto.createItems = function createItems() {
    var items = [];
    if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild("textTrackSettings")) {
      items.push(new CaptionSettingsMenuItem(this.player_, {
        kind: this.label_
      }));
      this.hideThreshold_ += 1;
    }
    items = _TextTrackButton.prototype.createItems.call(this, items, SubsCapsMenuItem);
    return items;
  };
  return SubsCapsButton2;
}(TextTrackButton);
SubsCapsButton.prototype.kinds_ = ["captions", "subtitles"];
SubsCapsButton.prototype.controlText_ = "Subtitles";
Component$1.registerComponent("SubsCapsButton", SubsCapsButton);
var AudioTrackMenuItem = /* @__PURE__ */ function(_MenuItem) {
  _inheritsLoose(AudioTrackMenuItem2, _MenuItem);
  function AudioTrackMenuItem2(player, options) {
    var _this;
    var track = options.track;
    var tracks = player.audioTracks();
    options.label = track.label || track.language || "Unknown";
    options.selected = track.enabled;
    _this = _MenuItem.call(this, player, options) || this;
    _this.track = track;
    _this.addClass("vjs-" + track.kind + "-menu-item");
    var changeHandler = function changeHandler2() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      _this.handleTracksChange.apply(_assertThisInitialized(_this), args);
    };
    tracks.addEventListener("change", changeHandler);
    _this.on("dispose", function() {
      tracks.removeEventListener("change", changeHandler);
    });
    return _this;
  }
  var _proto = AudioTrackMenuItem2.prototype;
  _proto.createEl = function createEl$1(type2, props, attrs) {
    var el = _MenuItem.prototype.createEl.call(this, type2, props, attrs);
    var parentSpan = el.querySelector(".vjs-menu-item-text");
    if (this.options_.track.kind === "main-desc") {
      parentSpan.appendChild(createEl("span", {
        className: "vjs-icon-placeholder"
      }, {
        "aria-hidden": true
      }));
      parentSpan.appendChild(createEl("span", {
        className: "vjs-control-text",
        textContent: " " + this.localize("Descriptions")
      }));
    }
    return el;
  };
  _proto.handleClick = function handleClick(event) {
    _MenuItem.prototype.handleClick.call(this, event);
    this.track.enabled = true;
    if (this.player_.tech_.featuresNativeAudioTracks) {
      var tracks = this.player_.audioTracks();
      for (var i = 0; i < tracks.length; i++) {
        var track = tracks[i];
        if (track === this.track) {
          continue;
        }
        track.enabled = track === this.track;
      }
    }
  };
  _proto.handleTracksChange = function handleTracksChange(event) {
    this.selected(this.track.enabled);
  };
  return AudioTrackMenuItem2;
}(MenuItem);
Component$1.registerComponent("AudioTrackMenuItem", AudioTrackMenuItem);
var AudioTrackButton = /* @__PURE__ */ function(_TrackButton) {
  _inheritsLoose(AudioTrackButton2, _TrackButton);
  function AudioTrackButton2(player, options) {
    if (options === void 0) {
      options = {};
    }
    options.tracks = player.audioTracks();
    return _TrackButton.call(this, player, options) || this;
  }
  var _proto = AudioTrackButton2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-audio-button " + _TrackButton.prototype.buildCSSClass.call(this);
  };
  _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
    return "vjs-audio-button " + _TrackButton.prototype.buildWrapperCSSClass.call(this);
  };
  _proto.createItems = function createItems(items) {
    if (items === void 0) {
      items = [];
    }
    this.hideThreshold_ = 1;
    var tracks = this.player_.audioTracks();
    for (var i = 0; i < tracks.length; i++) {
      var track = tracks[i];
      items.push(new AudioTrackMenuItem(this.player_, {
        track,
        // MenuItem is selectable
        selectable: true,
        // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
        multiSelectable: false
      }));
    }
    return items;
  };
  return AudioTrackButton2;
}(TrackButton);
AudioTrackButton.prototype.controlText_ = "Audio Track";
Component$1.registerComponent("AudioTrackButton", AudioTrackButton);
var PlaybackRateMenuItem = /* @__PURE__ */ function(_MenuItem) {
  _inheritsLoose(PlaybackRateMenuItem2, _MenuItem);
  function PlaybackRateMenuItem2(player, options) {
    var _this;
    var label = options.rate;
    var rate = parseFloat(label, 10);
    options.label = label;
    options.selected = rate === player.playbackRate();
    options.selectable = true;
    options.multiSelectable = false;
    _this = _MenuItem.call(this, player, options) || this;
    _this.label = label;
    _this.rate = rate;
    _this.on(player, "ratechange", function(e) {
      return _this.update(e);
    });
    return _this;
  }
  var _proto = PlaybackRateMenuItem2.prototype;
  _proto.handleClick = function handleClick(event) {
    _MenuItem.prototype.handleClick.call(this);
    this.player().playbackRate(this.rate);
  };
  _proto.update = function update(event) {
    this.selected(this.player().playbackRate() === this.rate);
  };
  return PlaybackRateMenuItem2;
}(MenuItem);
PlaybackRateMenuItem.prototype.contentElType = "button";
Component$1.registerComponent("PlaybackRateMenuItem", PlaybackRateMenuItem);
var PlaybackRateMenuButton = /* @__PURE__ */ function(_MenuButton) {
  _inheritsLoose(PlaybackRateMenuButton2, _MenuButton);
  function PlaybackRateMenuButton2(player, options) {
    var _this;
    _this = _MenuButton.call(this, player, options) || this;
    _this.menuButton_.el_.setAttribute("aria-describedby", _this.labelElId_);
    _this.updateVisibility();
    _this.updateLabel();
    _this.on(player, "loadstart", function(e) {
      return _this.updateVisibility(e);
    });
    _this.on(player, "ratechange", function(e) {
      return _this.updateLabel(e);
    });
    _this.on(player, "playbackrateschange", function(e) {
      return _this.handlePlaybackRateschange(e);
    });
    return _this;
  }
  var _proto = PlaybackRateMenuButton2.prototype;
  _proto.createEl = function createEl$1() {
    var el = _MenuButton.prototype.createEl.call(this);
    this.labelElId_ = "vjs-playback-rate-value-label-" + this.id_;
    this.labelEl_ = createEl("div", {
      className: "vjs-playback-rate-value",
      id: this.labelElId_,
      textContent: "1x"
    });
    el.appendChild(this.labelEl_);
    return el;
  };
  _proto.dispose = function dispose() {
    this.labelEl_ = null;
    _MenuButton.prototype.dispose.call(this);
  };
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-playback-rate " + _MenuButton.prototype.buildCSSClass.call(this);
  };
  _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
    return "vjs-playback-rate " + _MenuButton.prototype.buildWrapperCSSClass.call(this);
  };
  _proto.createItems = function createItems() {
    var rates = this.playbackRates();
    var items = [];
    for (var i = rates.length - 1; i >= 0; i--) {
      items.push(new PlaybackRateMenuItem(this.player(), {
        rate: rates[i] + "x"
      }));
    }
    return items;
  };
  _proto.updateARIAAttributes = function updateARIAAttributes() {
    this.el().setAttribute("aria-valuenow", this.player().playbackRate());
  };
  _proto.handleClick = function handleClick(event) {
    var currentRate = this.player().playbackRate();
    var rates = this.playbackRates();
    var currentIndex = rates.indexOf(currentRate);
    var newIndex = (currentIndex + 1) % rates.length;
    this.player().playbackRate(rates[newIndex]);
  };
  _proto.handlePlaybackRateschange = function handlePlaybackRateschange(event) {
    this.update();
  };
  _proto.playbackRates = function playbackRates() {
    var player = this.player();
    return player.playbackRates && player.playbackRates() || [];
  };
  _proto.playbackRateSupported = function playbackRateSupported() {
    return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  };
  _proto.updateVisibility = function updateVisibility(event) {
    if (this.playbackRateSupported()) {
      this.removeClass("vjs-hidden");
    } else {
      this.addClass("vjs-hidden");
    }
  };
  _proto.updateLabel = function updateLabel(event) {
    if (this.playbackRateSupported()) {
      this.labelEl_.textContent = this.player().playbackRate() + "x";
    }
  };
  return PlaybackRateMenuButton2;
}(MenuButton);
PlaybackRateMenuButton.prototype.controlText_ = "Playback Rate";
Component$1.registerComponent("PlaybackRateMenuButton", PlaybackRateMenuButton);
var Spacer = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(Spacer2, _Component);
  function Spacer2() {
    return _Component.apply(this, arguments) || this;
  }
  var _proto = Spacer2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-spacer " + _Component.prototype.buildCSSClass.call(this);
  };
  _proto.createEl = function createEl2(tag, props, attributes) {
    if (tag === void 0) {
      tag = "div";
    }
    if (props === void 0) {
      props = {};
    }
    if (attributes === void 0) {
      attributes = {};
    }
    if (!props.className) {
      props.className = this.buildCSSClass();
    }
    return _Component.prototype.createEl.call(this, tag, props, attributes);
  };
  return Spacer2;
}(Component$1);
Component$1.registerComponent("Spacer", Spacer);
var CustomControlSpacer = /* @__PURE__ */ function(_Spacer) {
  _inheritsLoose(CustomControlSpacer2, _Spacer);
  function CustomControlSpacer2() {
    return _Spacer.apply(this, arguments) || this;
  }
  var _proto = CustomControlSpacer2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-custom-control-spacer " + _Spacer.prototype.buildCSSClass.call(this);
  };
  _proto.createEl = function createEl2() {
    return _Spacer.prototype.createEl.call(this, "div", {
      className: this.buildCSSClass(),
      // No-flex/table-cell mode requires there be some content
      // in the cell to fill the remaining space of the table.
      textContent: "\xA0"
    });
  };
  return CustomControlSpacer2;
}(Spacer);
Component$1.registerComponent("CustomControlSpacer", CustomControlSpacer);
var ControlBar = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(ControlBar2, _Component);
  function ControlBar2() {
    return _Component.apply(this, arguments) || this;
  }
  var _proto = ControlBar2.prototype;
  _proto.createEl = function createEl2() {
    return _Component.prototype.createEl.call(this, "div", {
      className: "vjs-control-bar",
      dir: "ltr"
    });
  };
  return ControlBar2;
}(Component$1);
ControlBar.prototype.options_ = {
  children: ["playToggle", "volumePanel", "currentTimeDisplay", "timeDivider", "durationDisplay", "progressControl", "liveDisplay", "seekToLive", "remainingTimeDisplay", "customControlSpacer", "playbackRateMenuButton", "chaptersButton", "descriptionsButton", "subsCapsButton", "audioTrackButton", "fullscreenToggle"]
};
if ("exitPictureInPicture" in import_document.default) {
  ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length - 1, 0, "pictureInPictureToggle");
}
Component$1.registerComponent("ControlBar", ControlBar);
var ErrorDisplay = /* @__PURE__ */ function(_ModalDialog) {
  _inheritsLoose(ErrorDisplay2, _ModalDialog);
  function ErrorDisplay2(player, options) {
    var _this;
    _this = _ModalDialog.call(this, player, options) || this;
    _this.on(player, "error", function(e) {
      return _this.open(e);
    });
    return _this;
  }
  var _proto = ErrorDisplay2.prototype;
  _proto.buildCSSClass = function buildCSSClass() {
    return "vjs-error-display " + _ModalDialog.prototype.buildCSSClass.call(this);
  };
  _proto.content = function content() {
    var error = this.player().error();
    return error ? this.localize(error.message) : "";
  };
  return ErrorDisplay2;
}(ModalDialog);
ErrorDisplay.prototype.options_ = _extends2({}, ModalDialog.prototype.options_, {
  pauseOnOpen: false,
  fillAlways: true,
  temporary: false,
  uncloseable: true
});
Component$1.registerComponent("ErrorDisplay", ErrorDisplay);
var LOCAL_STORAGE_KEY$1 = "vjs-text-track-settings";
var COLOR_BLACK = ["#000", "Black"];
var COLOR_BLUE = ["#00F", "Blue"];
var COLOR_CYAN = ["#0FF", "Cyan"];
var COLOR_GREEN = ["#0F0", "Green"];
var COLOR_MAGENTA = ["#F0F", "Magenta"];
var COLOR_RED = ["#F00", "Red"];
var COLOR_WHITE = ["#FFF", "White"];
var COLOR_YELLOW = ["#FF0", "Yellow"];
var OPACITY_OPAQUE = ["1", "Opaque"];
var OPACITY_SEMI = ["0.5", "Semi-Transparent"];
var OPACITY_TRANS = ["0", "Transparent"];
var selectConfigs = {
  backgroundColor: {
    selector: ".vjs-bg-color > select",
    id: "captions-background-color-%s",
    label: "Color",
    options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  },
  backgroundOpacity: {
    selector: ".vjs-bg-opacity > select",
    id: "captions-background-opacity-%s",
    label: "Transparency",
    options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS]
  },
  color: {
    selector: ".vjs-fg-color > select",
    id: "captions-foreground-color-%s",
    label: "Color",
    options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  },
  edgeStyle: {
    selector: ".vjs-edge-style > select",
    id: "%s",
    label: "Text Edge Style",
    options: [["none", "None"], ["raised", "Raised"], ["depressed", "Depressed"], ["uniform", "Uniform"], ["dropshadow", "Dropshadow"]]
  },
  fontFamily: {
    selector: ".vjs-font-family > select",
    id: "captions-font-family-%s",
    label: "Font Family",
    options: [["proportionalSansSerif", "Proportional Sans-Serif"], ["monospaceSansSerif", "Monospace Sans-Serif"], ["proportionalSerif", "Proportional Serif"], ["monospaceSerif", "Monospace Serif"], ["casual", "Casual"], ["script", "Script"], ["small-caps", "Small Caps"]]
  },
  fontPercent: {
    selector: ".vjs-font-percent > select",
    id: "captions-font-size-%s",
    label: "Font Size",
    options: [["0.50", "50%"], ["0.75", "75%"], ["1.00", "100%"], ["1.25", "125%"], ["1.50", "150%"], ["1.75", "175%"], ["2.00", "200%"], ["3.00", "300%"], ["4.00", "400%"]],
    "default": 2,
    parser: function parser5(v) {
      return v === "1.00" ? null : Number(v);
    }
  },
  textOpacity: {
    selector: ".vjs-text-opacity > select",
    id: "captions-foreground-opacity-%s",
    label: "Transparency",
    options: [OPACITY_OPAQUE, OPACITY_SEMI]
  },
  // Options for this object are defined below.
  windowColor: {
    selector: ".vjs-window-color > select",
    id: "captions-window-color-%s",
    label: "Color"
  },
  // Options for this object are defined below.
  windowOpacity: {
    selector: ".vjs-window-opacity > select",
    id: "captions-window-opacity-%s",
    label: "Transparency",
    options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE]
  }
};
selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
function parseOptionValue(value, parser6) {
  if (parser6) {
    value = parser6(value);
  }
  if (value && value !== "none") {
    return value;
  }
}
function getSelectedOptionValue(el, parser6) {
  var value = el.options[el.options.selectedIndex].value;
  return parseOptionValue(value, parser6);
}
function setSelectedOption(el, value, parser6) {
  if (!value) {
    return;
  }
  for (var i = 0; i < el.options.length; i++) {
    if (parseOptionValue(el.options[i].value, parser6) === value) {
      el.selectedIndex = i;
      break;
    }
  }
}
var TextTrackSettings = /* @__PURE__ */ function(_ModalDialog) {
  _inheritsLoose(TextTrackSettings2, _ModalDialog);
  function TextTrackSettings2(player, options) {
    var _this;
    options.temporary = false;
    _this = _ModalDialog.call(this, player, options) || this;
    _this.updateDisplay = _this.updateDisplay.bind(_assertThisInitialized(_this));
    _this.fill();
    _this.hasBeenOpened_ = _this.hasBeenFilled_ = true;
    _this.endDialog = createEl("p", {
      className: "vjs-control-text",
      textContent: _this.localize("End of dialog window.")
    });
    _this.el().appendChild(_this.endDialog);
    _this.setDefaults();
    if (options.persistTextTrackSettings === void 0) {
      _this.options_.persistTextTrackSettings = _this.options_.playerOptions.persistTextTrackSettings;
    }
    _this.on(_this.$(".vjs-done-button"), "click", function() {
      _this.saveSettings();
      _this.close();
    });
    _this.on(_this.$(".vjs-default-button"), "click", function() {
      _this.setDefaults();
      _this.updateDisplay();
    });
    each(selectConfigs, function(config) {
      _this.on(_this.$(config.selector), "change", _this.updateDisplay);
    });
    if (_this.options_.persistTextTrackSettings) {
      _this.restoreSettings();
    }
    return _this;
  }
  var _proto = TextTrackSettings2.prototype;
  _proto.dispose = function dispose() {
    this.endDialog = null;
    _ModalDialog.prototype.dispose.call(this);
  };
  _proto.createElSelect_ = function createElSelect_(key, legendId, type2) {
    var _this2 = this;
    if (legendId === void 0) {
      legendId = "";
    }
    if (type2 === void 0) {
      type2 = "label";
    }
    var config = selectConfigs[key];
    var id = config.id.replace("%s", this.id_);
    var selectLabelledbyIds = [legendId, id].join(" ").trim();
    return ["<" + type2 + ' id="' + id + '" class="' + (type2 === "label" ? "vjs-label" : "") + '">', this.localize(config.label), "</" + type2 + ">", '<select aria-labelledby="' + selectLabelledbyIds + '">'].concat(config.options.map(function(o) {
      var optionId = id + "-" + o[1].replace(/\W+/g, "");
      return ['<option id="' + optionId + '" value="' + o[0] + '" ', 'aria-labelledby="' + selectLabelledbyIds + " " + optionId + '">', _this2.localize(o[1]), "</option>"].join("");
    })).concat("</select>").join("");
  };
  _proto.createElFgColor_ = function createElFgColor_() {
    var legendId = "captions-text-legend-" + this.id_;
    return ['<fieldset class="vjs-fg-color vjs-track-setting">', '<legend id="' + legendId + '">', this.localize("Text"), "</legend>", this.createElSelect_("color", legendId), '<span class="vjs-text-opacity vjs-opacity">', this.createElSelect_("textOpacity", legendId), "</span>", "</fieldset>"].join("");
  };
  _proto.createElBgColor_ = function createElBgColor_() {
    var legendId = "captions-background-" + this.id_;
    return ['<fieldset class="vjs-bg-color vjs-track-setting">', '<legend id="' + legendId + '">', this.localize("Background"), "</legend>", this.createElSelect_("backgroundColor", legendId), '<span class="vjs-bg-opacity vjs-opacity">', this.createElSelect_("backgroundOpacity", legendId), "</span>", "</fieldset>"].join("");
  };
  _proto.createElWinColor_ = function createElWinColor_() {
    var legendId = "captions-window-" + this.id_;
    return ['<fieldset class="vjs-window-color vjs-track-setting">', '<legend id="' + legendId + '">', this.localize("Window"), "</legend>", this.createElSelect_("windowColor", legendId), '<span class="vjs-window-opacity vjs-opacity">', this.createElSelect_("windowOpacity", legendId), "</span>", "</fieldset>"].join("");
  };
  _proto.createElColors_ = function createElColors_() {
    return createEl("div", {
      className: "vjs-track-settings-colors",
      innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join("")
    });
  };
  _proto.createElFont_ = function createElFont_() {
    return createEl("div", {
      className: "vjs-track-settings-font",
      innerHTML: ['<fieldset class="vjs-font-percent vjs-track-setting">', this.createElSelect_("fontPercent", "", "legend"), "</fieldset>", '<fieldset class="vjs-edge-style vjs-track-setting">', this.createElSelect_("edgeStyle", "", "legend"), "</fieldset>", '<fieldset class="vjs-font-family vjs-track-setting">', this.createElSelect_("fontFamily", "", "legend"), "</fieldset>"].join("")
    });
  };
  _proto.createElControls_ = function createElControls_() {
    var defaultsDescription = this.localize("restore all settings to the default values");
    return createEl("div", {
      className: "vjs-track-settings-controls",
      innerHTML: ['<button type="button" class="vjs-default-button" title="' + defaultsDescription + '">', this.localize("Reset"), '<span class="vjs-control-text"> ' + defaultsDescription + "</span>", "</button>", '<button type="button" class="vjs-done-button">' + this.localize("Done") + "</button>"].join("")
    });
  };
  _proto.content = function content() {
    return [this.createElColors_(), this.createElFont_(), this.createElControls_()];
  };
  _proto.label = function label() {
    return this.localize("Caption Settings Dialog");
  };
  _proto.description = function description() {
    return this.localize("Beginning of dialog window. Escape will cancel and close the window.");
  };
  _proto.buildCSSClass = function buildCSSClass() {
    return _ModalDialog.prototype.buildCSSClass.call(this) + " vjs-text-track-settings";
  };
  _proto.getValues = function getValues() {
    var _this3 = this;
    return reduce(selectConfigs, function(accum, config, key) {
      var value = getSelectedOptionValue(_this3.$(config.selector), config.parser);
      if (value !== void 0) {
        accum[key] = value;
      }
      return accum;
    }, {});
  };
  _proto.setValues = function setValues(values3) {
    var _this4 = this;
    each(selectConfigs, function(config, key) {
      setSelectedOption(_this4.$(config.selector), values3[key], config.parser);
    });
  };
  _proto.setDefaults = function setDefaults() {
    var _this5 = this;
    each(selectConfigs, function(config) {
      var index = config.hasOwnProperty("default") ? config["default"] : 0;
      _this5.$(config.selector).selectedIndex = index;
    });
  };
  _proto.restoreSettings = function restoreSettings() {
    var values3;
    try {
      values3 = JSON.parse(import_window6.default.localStorage.getItem(LOCAL_STORAGE_KEY$1));
    } catch (err) {
      log$1.warn(err);
    }
    if (values3) {
      this.setValues(values3);
    }
  };
  _proto.saveSettings = function saveSettings() {
    if (!this.options_.persistTextTrackSettings) {
      return;
    }
    var values3 = this.getValues();
    try {
      if (Object.keys(values3).length) {
        import_window6.default.localStorage.setItem(LOCAL_STORAGE_KEY$1, JSON.stringify(values3));
      } else {
        import_window6.default.localStorage.removeItem(LOCAL_STORAGE_KEY$1);
      }
    } catch (err) {
      log$1.warn(err);
    }
  };
  _proto.updateDisplay = function updateDisplay() {
    var ttDisplay = this.player_.getChild("textTrackDisplay");
    if (ttDisplay) {
      ttDisplay.updateDisplay();
    }
  };
  _proto.conditionalBlur_ = function conditionalBlur_() {
    this.previouslyActiveEl_ = null;
    var cb = this.player_.controlBar;
    var subsCapsBtn = cb && cb.subsCapsButton;
    var ccBtn = cb && cb.captionsButton;
    if (subsCapsBtn) {
      subsCapsBtn.focus();
    } else if (ccBtn) {
      ccBtn.focus();
    }
  };
  return TextTrackSettings2;
}(ModalDialog);
Component$1.registerComponent("TextTrackSettings", TextTrackSettings);
var ResizeManager = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(ResizeManager2, _Component);
  function ResizeManager2(player, options) {
    var _this;
    var RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || import_window6.default.ResizeObserver;
    if (options.ResizeObserver === null) {
      RESIZE_OBSERVER_AVAILABLE = false;
    }
    var options_ = mergeOptions$3({
      createEl: !RESIZE_OBSERVER_AVAILABLE,
      reportTouchActivity: false
    }, options);
    _this = _Component.call(this, player, options_) || this;
    _this.ResizeObserver = options.ResizeObserver || import_window6.default.ResizeObserver;
    _this.loadListener_ = null;
    _this.resizeObserver_ = null;
    _this.debouncedHandler_ = debounce(function() {
      _this.resizeHandler();
    }, 100, false, _assertThisInitialized(_this));
    if (RESIZE_OBSERVER_AVAILABLE) {
      _this.resizeObserver_ = new _this.ResizeObserver(_this.debouncedHandler_);
      _this.resizeObserver_.observe(player.el());
    } else {
      _this.loadListener_ = function() {
        if (!_this.el_ || !_this.el_.contentWindow) {
          return;
        }
        var debouncedHandler_ = _this.debouncedHandler_;
        var unloadListener_ = _this.unloadListener_ = function() {
          off(this, "resize", debouncedHandler_);
          off(this, "unload", unloadListener_);
          unloadListener_ = null;
        };
        on(_this.el_.contentWindow, "unload", unloadListener_);
        on(_this.el_.contentWindow, "resize", debouncedHandler_);
      };
      _this.one("load", _this.loadListener_);
    }
    return _this;
  }
  var _proto = ResizeManager2.prototype;
  _proto.createEl = function createEl2() {
    return _Component.prototype.createEl.call(this, "iframe", {
      className: "vjs-resize-manager",
      tabIndex: -1,
      title: this.localize("No content")
    }, {
      "aria-hidden": "true"
    });
  };
  _proto.resizeHandler = function resizeHandler() {
    if (!this.player_ || !this.player_.trigger) {
      return;
    }
    this.player_.trigger("playerresize");
  };
  _proto.dispose = function dispose() {
    if (this.debouncedHandler_) {
      this.debouncedHandler_.cancel();
    }
    if (this.resizeObserver_) {
      if (this.player_.el()) {
        this.resizeObserver_.unobserve(this.player_.el());
      }
      this.resizeObserver_.disconnect();
    }
    if (this.loadListener_) {
      this.off("load", this.loadListener_);
    }
    if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
      this.unloadListener_.call(this.el_.contentWindow);
    }
    this.ResizeObserver = null;
    this.resizeObserver = null;
    this.debouncedHandler_ = null;
    this.loadListener_ = null;
    _Component.prototype.dispose.call(this);
  };
  return ResizeManager2;
}(Component$1);
Component$1.registerComponent("ResizeManager", ResizeManager);
var defaults2 = {
  trackingThreshold: 20,
  liveTolerance: 15
};
var LiveTracker = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(LiveTracker2, _Component);
  function LiveTracker2(player, options) {
    var _this;
    var options_ = mergeOptions$3(defaults2, options, {
      createEl: false
    });
    _this = _Component.call(this, player, options_) || this;
    _this.handleVisibilityChange_ = function(e) {
      return _this.handleVisibilityChange(e);
    };
    _this.trackLiveHandler_ = function() {
      return _this.trackLive_();
    };
    _this.handlePlay_ = function(e) {
      return _this.handlePlay(e);
    };
    _this.handleFirstTimeupdate_ = function(e) {
      return _this.handleFirstTimeupdate(e);
    };
    _this.handleSeeked_ = function(e) {
      return _this.handleSeeked(e);
    };
    _this.seekToLiveEdge_ = function(e) {
      return _this.seekToLiveEdge(e);
    };
    _this.reset_();
    _this.on(_this.player_, "durationchange", function(e) {
      return _this.handleDurationchange(e);
    });
    _this.on(_this.player_, "canplay", function() {
      return _this.toggleTracking();
    });
    if (IE_VERSION && "hidden" in import_document.default && "visibilityState" in import_document.default) {
      _this.on(import_document.default, "visibilitychange", _this.handleVisibilityChange_);
    }
    return _this;
  }
  var _proto = LiveTracker2.prototype;
  _proto.handleVisibilityChange = function handleVisibilityChange() {
    if (this.player_.duration() !== Infinity) {
      return;
    }
    if (import_document.default.hidden) {
      this.stopTracking();
    } else {
      this.startTracking();
    }
  };
  _proto.trackLive_ = function trackLive_() {
    var seekable3 = this.player_.seekable();
    if (!seekable3 || !seekable3.length) {
      return;
    }
    var newTime = Number(import_window6.default.performance.now().toFixed(4));
    var deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1e3;
    this.lastTime_ = newTime;
    this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
    var liveCurrentTime = this.liveCurrentTime();
    var currentTime = this.player_.currentTime();
    var isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance;
    if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
      isBehind = false;
    }
    if (isBehind !== this.behindLiveEdge_) {
      this.behindLiveEdge_ = isBehind;
      this.trigger("liveedgechange");
    }
  };
  _proto.handleDurationchange = function handleDurationchange() {
    this.toggleTracking();
  };
  _proto.toggleTracking = function toggleTracking() {
    if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
      if (this.player_.options_.liveui) {
        this.player_.addClass("vjs-liveui");
      }
      this.startTracking();
    } else {
      this.player_.removeClass("vjs-liveui");
      this.stopTracking();
    }
  };
  _proto.startTracking = function startTracking() {
    if (this.isTracking()) {
      return;
    }
    if (!this.timeupdateSeen_) {
      this.timeupdateSeen_ = this.player_.hasStarted();
    }
    this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
    this.trackLive_();
    this.on(this.player_, ["play", "pause"], this.trackLiveHandler_);
    if (!this.timeupdateSeen_) {
      this.one(this.player_, "play", this.handlePlay_);
      this.one(this.player_, "timeupdate", this.handleFirstTimeupdate_);
    } else {
      this.on(this.player_, "seeked", this.handleSeeked_);
    }
  };
  _proto.handleFirstTimeupdate = function handleFirstTimeupdate() {
    this.timeupdateSeen_ = true;
    this.on(this.player_, "seeked", this.handleSeeked_);
  };
  _proto.handleSeeked = function handleSeeked() {
    var timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
    this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
    this.nextSeekedFromUser_ = false;
    this.trackLive_();
  };
  _proto.handlePlay = function handlePlay() {
    this.one(this.player_, "timeupdate", this.seekToLiveEdge_);
  };
  _proto.reset_ = function reset_() {
    this.lastTime_ = -1;
    this.pastSeekEnd_ = 0;
    this.lastSeekEnd_ = -1;
    this.behindLiveEdge_ = true;
    this.timeupdateSeen_ = false;
    this.seekedBehindLive_ = false;
    this.nextSeekedFromUser_ = false;
    this.clearInterval(this.trackingInterval_);
    this.trackingInterval_ = null;
    this.off(this.player_, ["play", "pause"], this.trackLiveHandler_);
    this.off(this.player_, "seeked", this.handleSeeked_);
    this.off(this.player_, "play", this.handlePlay_);
    this.off(this.player_, "timeupdate", this.handleFirstTimeupdate_);
    this.off(this.player_, "timeupdate", this.seekToLiveEdge_);
  };
  _proto.nextSeekedFromUser = function nextSeekedFromUser() {
    this.nextSeekedFromUser_ = true;
  };
  _proto.stopTracking = function stopTracking() {
    if (!this.isTracking()) {
      return;
    }
    this.reset_();
    this.trigger("liveedgechange");
  };
  _proto.seekableEnd = function seekableEnd() {
    var seekable3 = this.player_.seekable();
    var seekableEnds = [];
    var i = seekable3 ? seekable3.length : 0;
    while (i--) {
      seekableEnds.push(seekable3.end(i));
    }
    return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  };
  _proto.seekableStart = function seekableStart() {
    var seekable3 = this.player_.seekable();
    var seekableStarts = [];
    var i = seekable3 ? seekable3.length : 0;
    while (i--) {
      seekableStarts.push(seekable3.start(i));
    }
    return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  };
  _proto.liveWindow = function liveWindow() {
    var liveCurrentTime = this.liveCurrentTime();
    if (liveCurrentTime === Infinity) {
      return 0;
    }
    return liveCurrentTime - this.seekableStart();
  };
  _proto.isLive = function isLive() {
    return this.isTracking();
  };
  _proto.atLiveEdge = function atLiveEdge() {
    return !this.behindLiveEdge();
  };
  _proto.liveCurrentTime = function liveCurrentTime() {
    return this.pastSeekEnd() + this.seekableEnd();
  };
  _proto.pastSeekEnd = function pastSeekEnd() {
    var seekableEnd = this.seekableEnd();
    if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
      this.pastSeekEnd_ = 0;
    }
    this.lastSeekEnd_ = seekableEnd;
    return this.pastSeekEnd_;
  };
  _proto.behindLiveEdge = function behindLiveEdge() {
    return this.behindLiveEdge_;
  };
  _proto.isTracking = function isTracking() {
    return typeof this.trackingInterval_ === "number";
  };
  _proto.seekToLiveEdge = function seekToLiveEdge() {
    this.seekedBehindLive_ = false;
    if (this.atLiveEdge()) {
      return;
    }
    this.nextSeekedFromUser_ = false;
    this.player_.currentTime(this.liveCurrentTime());
  };
  _proto.dispose = function dispose() {
    this.off(import_document.default, "visibilitychange", this.handleVisibilityChange_);
    this.stopTracking();
    _Component.prototype.dispose.call(this);
  };
  return LiveTracker2;
}(Component$1);
Component$1.registerComponent("LiveTracker", LiveTracker);
var sourcesetLoad = function sourcesetLoad2(tech) {
  var el = tech.el();
  if (el.hasAttribute("src")) {
    tech.triggerSourceset(el.src);
    return true;
  }
  var sources = tech.$$("source");
  var srcUrls = [];
  var src = "";
  if (!sources.length) {
    return false;
  }
  for (var i = 0; i < sources.length; i++) {
    var url = sources[i].src;
    if (url && srcUrls.indexOf(url) === -1) {
      srcUrls.push(url);
    }
  }
  if (!srcUrls.length) {
    return false;
  }
  if (srcUrls.length === 1) {
    src = srcUrls[0];
  }
  tech.triggerSourceset(src);
  return true;
};
var innerHTMLDescriptorPolyfill = Object.defineProperty({}, "innerHTML", {
  get: function get2() {
    return this.cloneNode(true).innerHTML;
  },
  set: function set2(v) {
    var dummy = import_document.default.createElement(this.nodeName.toLowerCase());
    dummy.innerHTML = v;
    var docFrag = import_document.default.createDocumentFragment();
    while (dummy.childNodes.length) {
      docFrag.appendChild(dummy.childNodes[0]);
    }
    this.innerText = "";
    import_window6.default.Element.prototype.appendChild.call(this, docFrag);
    return this.innerHTML;
  }
});
var getDescriptor = function getDescriptor2(priority, prop) {
  var descriptor = {};
  for (var i = 0; i < priority.length; i++) {
    descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
    if (descriptor && descriptor.set && descriptor.get) {
      break;
    }
  }
  descriptor.enumerable = true;
  descriptor.configurable = true;
  return descriptor;
};
var getInnerHTMLDescriptor = function getInnerHTMLDescriptor2(tech) {
  return getDescriptor([tech.el(), import_window6.default.HTMLMediaElement.prototype, import_window6.default.Element.prototype, innerHTMLDescriptorPolyfill], "innerHTML");
};
var firstSourceWatch = function firstSourceWatch2(tech) {
  var el = tech.el();
  if (el.resetSourceWatch_) {
    return;
  }
  var old = {};
  var innerDescriptor = getInnerHTMLDescriptor(tech);
  var appendWrapper = function appendWrapper2(appendFn) {
    return function() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      var retval = appendFn.apply(el, args);
      sourcesetLoad(tech);
      return retval;
    };
  };
  ["append", "appendChild", "insertAdjacentHTML"].forEach(function(k) {
    if (!el[k]) {
      return;
    }
    old[k] = el[k];
    el[k] = appendWrapper(old[k]);
  });
  Object.defineProperty(el, "innerHTML", mergeOptions$3(innerDescriptor, {
    set: appendWrapper(innerDescriptor.set)
  }));
  el.resetSourceWatch_ = function() {
    el.resetSourceWatch_ = null;
    Object.keys(old).forEach(function(k) {
      el[k] = old[k];
    });
    Object.defineProperty(el, "innerHTML", innerDescriptor);
  };
  tech.one("sourceset", el.resetSourceWatch_);
};
var srcDescriptorPolyfill = Object.defineProperty({}, "src", {
  get: function get3() {
    if (this.hasAttribute("src")) {
      return getAbsoluteURL(import_window6.default.Element.prototype.getAttribute.call(this, "src"));
    }
    return "";
  },
  set: function set3(v) {
    import_window6.default.Element.prototype.setAttribute.call(this, "src", v);
    return v;
  }
});
var getSrcDescriptor = function getSrcDescriptor2(tech) {
  return getDescriptor([tech.el(), import_window6.default.HTMLMediaElement.prototype, srcDescriptorPolyfill], "src");
};
var setupSourceset = function setupSourceset2(tech) {
  if (!tech.featuresSourceset) {
    return;
  }
  var el = tech.el();
  if (el.resetSourceset_) {
    return;
  }
  var srcDescriptor = getSrcDescriptor(tech);
  var oldSetAttribute = el.setAttribute;
  var oldLoad = el.load;
  Object.defineProperty(el, "src", mergeOptions$3(srcDescriptor, {
    set: function set4(v) {
      var retval = srcDescriptor.set.call(el, v);
      tech.triggerSourceset(el.src);
      return retval;
    }
  }));
  el.setAttribute = function(n, v) {
    var retval = oldSetAttribute.call(el, n, v);
    if (/src/i.test(n)) {
      tech.triggerSourceset(el.src);
    }
    return retval;
  };
  el.load = function() {
    var retval = oldLoad.call(el);
    if (!sourcesetLoad(tech)) {
      tech.triggerSourceset("");
      firstSourceWatch(tech);
    }
    return retval;
  };
  if (el.currentSrc) {
    tech.triggerSourceset(el.currentSrc);
  } else if (!sourcesetLoad(tech)) {
    firstSourceWatch(tech);
  }
  el.resetSourceset_ = function() {
    el.resetSourceset_ = null;
    el.load = oldLoad;
    el.setAttribute = oldSetAttribute;
    Object.defineProperty(el, "src", srcDescriptor);
    if (el.resetSourceWatch_) {
      el.resetSourceWatch_();
    }
  };
};
var defineLazyProperty = function defineLazyProperty2(obj, key, getValue, setter) {
  if (setter === void 0) {
    setter = true;
  }
  var set4 = function set5(value) {
    return Object.defineProperty(obj, key, {
      value,
      enumerable: true,
      writable: true
    });
  };
  var options = {
    configurable: true,
    enumerable: true,
    get: function get7() {
      var value = getValue();
      set4(value);
      return value;
    }
  };
  if (setter) {
    options.set = set4;
  }
  return Object.defineProperty(obj, key, options);
};
var Html5 = /* @__PURE__ */ function(_Tech) {
  _inheritsLoose(Html52, _Tech);
  function Html52(options, ready) {
    var _this;
    _this = _Tech.call(this, options, ready) || this;
    var source = options.source;
    var crossoriginTracks = false;
    _this.featuresVideoFrameCallback = _this.featuresVideoFrameCallback && _this.el_.tagName === "VIDEO";
    if (source && (_this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
      _this.setSource(source);
    } else {
      _this.handleLateInit_(_this.el_);
    }
    if (options.enableSourceset) {
      _this.setupSourcesetHandling_();
    }
    _this.isScrubbing_ = false;
    if (_this.el_.hasChildNodes()) {
      var nodes = _this.el_.childNodes;
      var nodesLength = nodes.length;
      var removeNodes = [];
      while (nodesLength--) {
        var node = nodes[nodesLength];
        var nodeName = node.nodeName.toLowerCase();
        if (nodeName === "track") {
          if (!_this.featuresNativeTextTracks) {
            removeNodes.push(node);
          } else {
            _this.remoteTextTrackEls().addTrackElement_(node);
            _this.remoteTextTracks().addTrack(node.track);
            _this.textTracks().addTrack(node.track);
            if (!crossoriginTracks && !_this.el_.hasAttribute("crossorigin") && isCrossOrigin(node.src)) {
              crossoriginTracks = true;
            }
          }
        }
      }
      for (var i = 0; i < removeNodes.length; i++) {
        _this.el_.removeChild(removeNodes[i]);
      }
    }
    _this.proxyNativeTracks_();
    if (_this.featuresNativeTextTracks && crossoriginTracks) {
      log$1.warn("Text Tracks are being loaded from another origin but the crossorigin attribute isn't used.\nThis may prevent text tracks from loading.");
    }
    _this.restoreMetadataTracksInIOSNativePlayer_();
    if ((TOUCH_ENABLED || IS_IPHONE || IS_NATIVE_ANDROID) && options.nativeControlsForTouch === true) {
      _this.setControls(true);
    }
    _this.proxyWebkitFullscreen_();
    _this.triggerReady();
    return _this;
  }
  var _proto = Html52.prototype;
  _proto.dispose = function dispose() {
    if (this.el_ && this.el_.resetSourceset_) {
      this.el_.resetSourceset_();
    }
    Html52.disposeMediaElement(this.el_);
    this.options_ = null;
    _Tech.prototype.dispose.call(this);
  };
  _proto.setupSourcesetHandling_ = function setupSourcesetHandling_() {
    setupSourceset(this);
  };
  _proto.restoreMetadataTracksInIOSNativePlayer_ = function restoreMetadataTracksInIOSNativePlayer_() {
    var textTracks = this.textTracks();
    var metadataTracksPreFullscreenState;
    var takeMetadataTrackSnapshot = function takeMetadataTrackSnapshot2() {
      metadataTracksPreFullscreenState = [];
      for (var i = 0; i < textTracks.length; i++) {
        var track = textTracks[i];
        if (track.kind === "metadata") {
          metadataTracksPreFullscreenState.push({
            track,
            storedMode: track.mode
          });
        }
      }
    };
    takeMetadataTrackSnapshot();
    textTracks.addEventListener("change", takeMetadataTrackSnapshot);
    this.on("dispose", function() {
      return textTracks.removeEventListener("change", takeMetadataTrackSnapshot);
    });
    var restoreTrackMode = function restoreTrackMode2() {
      for (var i = 0; i < metadataTracksPreFullscreenState.length; i++) {
        var storedTrack = metadataTracksPreFullscreenState[i];
        if (storedTrack.track.mode === "disabled" && storedTrack.track.mode !== storedTrack.storedMode) {
          storedTrack.track.mode = storedTrack.storedMode;
        }
      }
      textTracks.removeEventListener("change", restoreTrackMode2);
    };
    this.on("webkitbeginfullscreen", function() {
      textTracks.removeEventListener("change", takeMetadataTrackSnapshot);
      textTracks.removeEventListener("change", restoreTrackMode);
      textTracks.addEventListener("change", restoreTrackMode);
    });
    this.on("webkitendfullscreen", function() {
      textTracks.removeEventListener("change", takeMetadataTrackSnapshot);
      textTracks.addEventListener("change", takeMetadataTrackSnapshot);
      textTracks.removeEventListener("change", restoreTrackMode);
    });
  };
  _proto.overrideNative_ = function overrideNative_(type2, override) {
    var _this2 = this;
    if (override !== this["featuresNative" + type2 + "Tracks"]) {
      return;
    }
    var lowerCaseType = type2.toLowerCase();
    if (this[lowerCaseType + "TracksListeners_"]) {
      Object.keys(this[lowerCaseType + "TracksListeners_"]).forEach(function(eventName) {
        var elTracks = _this2.el()[lowerCaseType + "Tracks"];
        elTracks.removeEventListener(eventName, _this2[lowerCaseType + "TracksListeners_"][eventName]);
      });
    }
    this["featuresNative" + type2 + "Tracks"] = !override;
    this[lowerCaseType + "TracksListeners_"] = null;
    this.proxyNativeTracksForType_(lowerCaseType);
  };
  _proto.overrideNativeAudioTracks = function overrideNativeAudioTracks(override) {
    this.overrideNative_("Audio", override);
  };
  _proto.overrideNativeVideoTracks = function overrideNativeVideoTracks(override) {
    this.overrideNative_("Video", override);
  };
  _proto.proxyNativeTracksForType_ = function proxyNativeTracksForType_(name) {
    var _this3 = this;
    var props = NORMAL[name];
    var elTracks = this.el()[props.getterName];
    var techTracks = this[props.getterName]();
    if (!this["featuresNative" + props.capitalName + "Tracks"] || !elTracks || !elTracks.addEventListener) {
      return;
    }
    var listeners = {
      change: function change(e) {
        var event = {
          type: "change",
          target: techTracks,
          currentTarget: techTracks,
          srcElement: techTracks
        };
        techTracks.trigger(event);
        if (name === "text") {
          _this3[REMOTE.remoteText.getterName]().trigger(event);
        }
      },
      addtrack: function addtrack(e) {
        techTracks.addTrack(e.track);
      },
      removetrack: function removetrack(e) {
        techTracks.removeTrack(e.track);
      }
    };
    var removeOldTracks = function removeOldTracks2() {
      var removeTracks = [];
      for (var i = 0; i < techTracks.length; i++) {
        var found = false;
        for (var j = 0; j < elTracks.length; j++) {
          if (elTracks[j] === techTracks[i]) {
            found = true;
            break;
          }
        }
        if (!found) {
          removeTracks.push(techTracks[i]);
        }
      }
      while (removeTracks.length) {
        techTracks.removeTrack(removeTracks.shift());
      }
    };
    this[props.getterName + "Listeners_"] = listeners;
    Object.keys(listeners).forEach(function(eventName) {
      var listener = listeners[eventName];
      elTracks.addEventListener(eventName, listener);
      _this3.on("dispose", function(e) {
        return elTracks.removeEventListener(eventName, listener);
      });
    });
    this.on("loadstart", removeOldTracks);
    this.on("dispose", function(e) {
      return _this3.off("loadstart", removeOldTracks);
    });
  };
  _proto.proxyNativeTracks_ = function proxyNativeTracks_() {
    var _this4 = this;
    NORMAL.names.forEach(function(name) {
      _this4.proxyNativeTracksForType_(name);
    });
  };
  _proto.createEl = function createEl2() {
    var el = this.options_.tag;
    if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
      if (el) {
        var clone = el.cloneNode(true);
        if (el.parentNode) {
          el.parentNode.insertBefore(clone, el);
        }
        Html52.disposeMediaElement(el);
        el = clone;
      } else {
        el = import_document.default.createElement("video");
        var tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
        var attributes = mergeOptions$3({}, tagAttributes);
        if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
          delete attributes.controls;
        }
        setAttributes(el, assign(attributes, {
          id: this.options_.techId,
          "class": "vjs-tech"
        }));
      }
      el.playerId = this.options_.playerId;
    }
    if (typeof this.options_.preload !== "undefined") {
      setAttribute(el, "preload", this.options_.preload);
    }
    if (this.options_.disablePictureInPicture !== void 0) {
      el.disablePictureInPicture = this.options_.disablePictureInPicture;
    }
    var settingsAttrs = ["loop", "muted", "playsinline", "autoplay"];
    for (var i = 0; i < settingsAttrs.length; i++) {
      var attr = settingsAttrs[i];
      var value = this.options_[attr];
      if (typeof value !== "undefined") {
        if (value) {
          setAttribute(el, attr, attr);
        } else {
          removeAttribute(el, attr);
        }
        el[attr] = value;
      }
    }
    return el;
  };
  _proto.handleLateInit_ = function handleLateInit_(el) {
    if (el.networkState === 0 || el.networkState === 3) {
      return;
    }
    if (el.readyState === 0) {
      var loadstartFired = false;
      var setLoadstartFired = function setLoadstartFired2() {
        loadstartFired = true;
      };
      this.on("loadstart", setLoadstartFired);
      var triggerLoadstart = function triggerLoadstart2() {
        if (!loadstartFired) {
          this.trigger("loadstart");
        }
      };
      this.on("loadedmetadata", triggerLoadstart);
      this.ready(function() {
        this.off("loadstart", setLoadstartFired);
        this.off("loadedmetadata", triggerLoadstart);
        if (!loadstartFired) {
          this.trigger("loadstart");
        }
      });
      return;
    }
    var eventsToTrigger = ["loadstart"];
    eventsToTrigger.push("loadedmetadata");
    if (el.readyState >= 2) {
      eventsToTrigger.push("loadeddata");
    }
    if (el.readyState >= 3) {
      eventsToTrigger.push("canplay");
    }
    if (el.readyState >= 4) {
      eventsToTrigger.push("canplaythrough");
    }
    this.ready(function() {
      eventsToTrigger.forEach(function(type2) {
        this.trigger(type2);
      }, this);
    });
  };
  _proto.setScrubbing = function setScrubbing(isScrubbing) {
    this.isScrubbing_ = isScrubbing;
  };
  _proto.scrubbing = function scrubbing() {
    return this.isScrubbing_;
  };
  _proto.setCurrentTime = function setCurrentTime(seconds) {
    try {
      if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
        this.el_.fastSeek(seconds);
      } else {
        this.el_.currentTime = seconds;
      }
    } catch (e) {
      log$1(e, "Video is not ready. (Video.js)");
    }
  };
  _proto.duration = function duration5() {
    var _this5 = this;
    if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
      var checkProgress = function checkProgress2() {
        if (_this5.el_.currentTime > 0) {
          if (_this5.el_.duration === Infinity) {
            _this5.trigger("durationchange");
          }
          _this5.off("timeupdate", checkProgress2);
        }
      };
      this.on("timeupdate", checkProgress);
      return NaN;
    }
    return this.el_.duration || NaN;
  };
  _proto.width = function width2() {
    return this.el_.offsetWidth;
  };
  _proto.height = function height2() {
    return this.el_.offsetHeight;
  };
  _proto.proxyWebkitFullscreen_ = function proxyWebkitFullscreen_() {
    var _this6 = this;
    if (!("webkitDisplayingFullscreen" in this.el_)) {
      return;
    }
    var endFn = function endFn2() {
      this.trigger("fullscreenchange", {
        isFullscreen: false
      });
      if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
        this.el_.controls = false;
      }
    };
    var beginFn = function beginFn2() {
      if ("webkitPresentationMode" in this.el_ && this.el_.webkitPresentationMode !== "picture-in-picture") {
        this.one("webkitendfullscreen", endFn);
        this.trigger("fullscreenchange", {
          isFullscreen: true,
          // set a flag in case another tech triggers fullscreenchange
          nativeIOSFullscreen: true
        });
      }
    };
    this.on("webkitbeginfullscreen", beginFn);
    this.on("dispose", function() {
      _this6.off("webkitbeginfullscreen", beginFn);
      _this6.off("webkitendfullscreen", endFn);
    });
  };
  _proto.supportsFullScreen = function supportsFullScreen() {
    if (typeof this.el_.webkitEnterFullScreen === "function") {
      var userAgent = import_window6.default.navigator && import_window6.default.navigator.userAgent || "";
      if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) {
        return true;
      }
    }
    return false;
  };
  _proto.enterFullScreen = function enterFullScreen() {
    var video = this.el_;
    if (video.paused && video.networkState <= video.HAVE_METADATA) {
      silencePromise(this.el_.play());
      this.setTimeout(function() {
        video.pause();
        try {
          video.webkitEnterFullScreen();
        } catch (e) {
          this.trigger("fullscreenerror", e);
        }
      }, 0);
    } else {
      try {
        video.webkitEnterFullScreen();
      } catch (e) {
        this.trigger("fullscreenerror", e);
      }
    }
  };
  _proto.exitFullScreen = function exitFullScreen() {
    if (!this.el_.webkitDisplayingFullscreen) {
      this.trigger("fullscreenerror", new Error("The video is not fullscreen"));
      return;
    }
    this.el_.webkitExitFullScreen();
  };
  _proto.requestPictureInPicture = function requestPictureInPicture() {
    return this.el_.requestPictureInPicture();
  };
  _proto.requestVideoFrameCallback = function requestVideoFrameCallback(cb) {
    if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
      return this.el_.requestVideoFrameCallback(cb);
    }
    return _Tech.prototype.requestVideoFrameCallback.call(this, cb);
  };
  _proto.cancelVideoFrameCallback = function cancelVideoFrameCallback(id) {
    if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
      this.el_.cancelVideoFrameCallback(id);
    } else {
      _Tech.prototype.cancelVideoFrameCallback.call(this, id);
    }
  };
  _proto.src = function src(_src) {
    if (_src === void 0) {
      return this.el_.src;
    }
    this.setSrc(_src);
  };
  _proto.reset = function reset3() {
    Html52.resetMediaElement(this.el_);
  };
  _proto.currentSrc = function currentSrc() {
    if (this.currentSource_) {
      return this.currentSource_.src;
    }
    return this.el_.currentSrc;
  };
  _proto.setControls = function setControls(val) {
    this.el_.controls = !!val;
  };
  _proto.addTextTrack = function addTextTrack(kind, label, language) {
    if (!this.featuresNativeTextTracks) {
      return _Tech.prototype.addTextTrack.call(this, kind, label, language);
    }
    return this.el_.addTextTrack(kind, label, language);
  };
  _proto.createRemoteTextTrack = function createRemoteTextTrack(options) {
    if (!this.featuresNativeTextTracks) {
      return _Tech.prototype.createRemoteTextTrack.call(this, options);
    }
    var htmlTrackElement = import_document.default.createElement("track");
    if (options.kind) {
      htmlTrackElement.kind = options.kind;
    }
    if (options.label) {
      htmlTrackElement.label = options.label;
    }
    if (options.language || options.srclang) {
      htmlTrackElement.srclang = options.language || options.srclang;
    }
    if (options["default"]) {
      htmlTrackElement["default"] = options["default"];
    }
    if (options.id) {
      htmlTrackElement.id = options.id;
    }
    if (options.src) {
      htmlTrackElement.src = options.src;
    }
    return htmlTrackElement;
  };
  _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
    var htmlTrackElement = _Tech.prototype.addRemoteTextTrack.call(this, options, manualCleanup);
    if (this.featuresNativeTextTracks) {
      this.el().appendChild(htmlTrackElement);
    }
    return htmlTrackElement;
  };
  _proto.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
    _Tech.prototype.removeRemoteTextTrack.call(this, track);
    if (this.featuresNativeTextTracks) {
      var tracks = this.$$("track");
      var i = tracks.length;
      while (i--) {
        if (track === tracks[i] || track === tracks[i].track) {
          this.el().removeChild(tracks[i]);
        }
      }
    }
  };
  _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
    if (typeof this.el().getVideoPlaybackQuality === "function") {
      return this.el().getVideoPlaybackQuality();
    }
    var videoPlaybackQuality = {};
    if (typeof this.el().webkitDroppedFrameCount !== "undefined" && typeof this.el().webkitDecodedFrameCount !== "undefined") {
      videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
      videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
    }
    if (import_window6.default.performance && typeof import_window6.default.performance.now === "function") {
      videoPlaybackQuality.creationTime = import_window6.default.performance.now();
    } else if (import_window6.default.performance && import_window6.default.performance.timing && typeof import_window6.default.performance.timing.navigationStart === "number") {
      videoPlaybackQuality.creationTime = import_window6.default.Date.now() - import_window6.default.performance.timing.navigationStart;
    }
    return videoPlaybackQuality;
  };
  return Html52;
}(Tech);
defineLazyProperty(Html5, "TEST_VID", function() {
  if (!isReal()) {
    return;
  }
  var video = import_document.default.createElement("video");
  var track = import_document.default.createElement("track");
  track.kind = "captions";
  track.srclang = "en";
  track.label = "English";
  video.appendChild(track);
  return video;
});
Html5.isSupported = function() {
  try {
    Html5.TEST_VID.volume = 0.5;
  } catch (e) {
    return false;
  }
  return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
};
Html5.canPlayType = function(type2) {
  return Html5.TEST_VID.canPlayType(type2);
};
Html5.canPlaySource = function(srcObj, options) {
  return Html5.canPlayType(srcObj.type);
};
Html5.canControlVolume = function() {
  try {
    var volume = Html5.TEST_VID.volume;
    Html5.TEST_VID.volume = volume / 2 + 0.1;
    var canControl = volume !== Html5.TEST_VID.volume;
    if (canControl && IS_IOS) {
      import_window6.default.setTimeout(function() {
        if (Html5 && Html5.prototype) {
          Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
        }
      });
      return false;
    }
    return canControl;
  } catch (e) {
    return false;
  }
};
Html5.canMuteVolume = function() {
  try {
    var muted = Html5.TEST_VID.muted;
    Html5.TEST_VID.muted = !muted;
    if (Html5.TEST_VID.muted) {
      setAttribute(Html5.TEST_VID, "muted", "muted");
    } else {
      removeAttribute(Html5.TEST_VID, "muted", "muted");
    }
    return muted !== Html5.TEST_VID.muted;
  } catch (e) {
    return false;
  }
};
Html5.canControlPlaybackRate = function() {
  if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
    return false;
  }
  try {
    var playbackRate = Html5.TEST_VID.playbackRate;
    Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
    return playbackRate !== Html5.TEST_VID.playbackRate;
  } catch (e) {
    return false;
  }
};
Html5.canOverrideAttributes = function() {
  try {
    var noop4 = function noop5() {
    };
    Object.defineProperty(import_document.default.createElement("video"), "src", {
      get: noop4,
      set: noop4
    });
    Object.defineProperty(import_document.default.createElement("audio"), "src", {
      get: noop4,
      set: noop4
    });
    Object.defineProperty(import_document.default.createElement("video"), "innerHTML", {
      get: noop4,
      set: noop4
    });
    Object.defineProperty(import_document.default.createElement("audio"), "innerHTML", {
      get: noop4,
      set: noop4
    });
  } catch (e) {
    return false;
  }
  return true;
};
Html5.supportsNativeTextTracks = function() {
  return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
};
Html5.supportsNativeVideoTracks = function() {
  return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
};
Html5.supportsNativeAudioTracks = function() {
  return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
};
Html5.Events = ["loadstart", "suspend", "abort", "error", "emptied", "stalled", "loadedmetadata", "loadeddata", "canplay", "canplaythrough", "playing", "waiting", "seeking", "seeked", "ended", "durationchange", "timeupdate", "progress", "play", "pause", "ratechange", "resize", "volumechange"];
[["featuresMuteControl", "canMuteVolume"], ["featuresPlaybackRate", "canControlPlaybackRate"], ["featuresSourceset", "canOverrideAttributes"], ["featuresNativeTextTracks", "supportsNativeTextTracks"], ["featuresNativeVideoTracks", "supportsNativeVideoTracks"], ["featuresNativeAudioTracks", "supportsNativeAudioTracks"]].forEach(function(_ref) {
  var key = _ref[0], fn = _ref[1];
  defineLazyProperty(Html5.prototype, key, function() {
    return Html5[fn]();
  }, true);
});
Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
Html5.prototype.movingMediaElementInDOM = !IS_IOS;
Html5.prototype.featuresFullscreenResize = true;
Html5.prototype.featuresProgressEvents = true;
Html5.prototype.featuresTimeupdateEvents = true;
Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback);
var canPlayType;
Html5.patchCanPlayType = function() {
  if (ANDROID_VERSION >= 4 && !IS_FIREFOX && !IS_CHROME) {
    canPlayType = Html5.TEST_VID && Html5.TEST_VID.constructor.prototype.canPlayType;
    Html5.TEST_VID.constructor.prototype.canPlayType = function(type2) {
      var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i;
      if (type2 && mpegurlRE.test(type2)) {
        return "maybe";
      }
      return canPlayType.call(this, type2);
    };
  }
};
Html5.unpatchCanPlayType = function() {
  var r2 = Html5.TEST_VID.constructor.prototype.canPlayType;
  if (canPlayType) {
    Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType;
  }
  return r2;
};
Html5.patchCanPlayType();
Html5.disposeMediaElement = function(el) {
  if (!el) {
    return;
  }
  if (el.parentNode) {
    el.parentNode.removeChild(el);
  }
  while (el.hasChildNodes()) {
    el.removeChild(el.firstChild);
  }
  el.removeAttribute("src");
  if (typeof el.load === "function") {
    (function() {
      try {
        el.load();
      } catch (e) {
      }
    })();
  }
};
Html5.resetMediaElement = function(el) {
  if (!el) {
    return;
  }
  var sources = el.querySelectorAll("source");
  var i = sources.length;
  while (i--) {
    el.removeChild(sources[i]);
  }
  el.removeAttribute("src");
  if (typeof el.load === "function") {
    (function() {
      try {
        el.load();
      } catch (e) {
      }
    })();
  }
};
[
  /**
   * Get the value of `muted` from the media element. `muted` indicates
   * that the volume for the media should be set to silent. This does not actually change
   * the `volume` attribute.
   *
   * @method Html5#muted
   * @return {boolean}
   *         - True if the value of `volume` should be ignored and the audio set to silent.
   *         - False if the value of `volume` should be used.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
   */
  "muted",
  /**
   * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
   * whether the media should start muted or not. Only changes the default state of the
   * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
   * current state.
   *
   * @method Html5#defaultMuted
   * @return {boolean}
   *         - The value of `defaultMuted` from the media element.
   *         - True indicates that the media should start muted.
   *         - False indicates that the media should not start muted
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
   */
  "defaultMuted",
  /**
   * Get the value of `autoplay` from the media element. `autoplay` indicates
   * that the media should start to play as soon as the page is ready.
   *
   * @method Html5#autoplay
   * @return {boolean}
   *         - The value of `autoplay` from the media element.
   *         - True indicates that the media should start as soon as the page loads.
   *         - False indicates that the media should not start as soon as the page loads.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
   */
  "autoplay",
  /**
   * Get the value of `controls` from the media element. `controls` indicates
   * whether the native media controls should be shown or hidden.
   *
   * @method Html5#controls
   * @return {boolean}
   *         - The value of `controls` from the media element.
   *         - True indicates that native controls should be showing.
   *         - False indicates that native controls should be hidden.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
   */
  "controls",
  /**
   * Get the value of `loop` from the media element. `loop` indicates
   * that the media should return to the start of the media and continue playing once
   * it reaches the end.
   *
   * @method Html5#loop
   * @return {boolean}
   *         - The value of `loop` from the media element.
   *         - True indicates that playback should seek back to start once
   *           the end of a media is reached.
   *         - False indicates that playback should not loop back to the start when the
   *           end of the media is reached.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
   */
  "loop",
  /**
   * Get the value of `playsinline` from the media element. `playsinline` indicates
   * to the browser that non-fullscreen playback is preferred when fullscreen
   * playback is the native default, such as in iOS Safari.
   *
   * @method Html5#playsinline
   * @return {boolean}
   *         - The value of `playsinline` from the media element.
   *         - True indicates that the media should play inline.
   *         - False indicates that the media should not play inline.
   *
   * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
   */
  "playsinline"
].forEach(function(prop) {
  Html5.prototype[prop] = function() {
    return this.el_[prop] || this.el_.hasAttribute(prop);
  };
});
[
  /**
   * Set the value of `muted` on the media element. `muted` indicates that the current
   * audio level should be silent.
   *
   * @method Html5#setMuted
   * @param {boolean} muted
   *        - True if the audio should be set to silent
   *        - False otherwise
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
   */
  "muted",
  /**
   * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
   * audio level should be silent, but will only effect the muted level on initial playback..
   *
   * @method Html5.prototype.setDefaultMuted
   * @param {boolean} defaultMuted
   *        - True if the audio should be set to silent
   *        - False otherwise
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
   */
  "defaultMuted",
  /**
   * Set the value of `autoplay` on the media element. `autoplay` indicates
   * that the media should start to play as soon as the page is ready.
   *
   * @method Html5#setAutoplay
   * @param {boolean} autoplay
   *         - True indicates that the media should start as soon as the page loads.
   *         - False indicates that the media should not start as soon as the page loads.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
   */
  "autoplay",
  /**
   * Set the value of `loop` on the media element. `loop` indicates
   * that the media should return to the start of the media and continue playing once
   * it reaches the end.
   *
   * @method Html5#setLoop
   * @param {boolean} loop
   *         - True indicates that playback should seek back to start once
   *           the end of a media is reached.
   *         - False indicates that playback should not loop back to the start when the
   *           end of the media is reached.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
   */
  "loop",
  /**
   * Set the value of `playsinline` from the media element. `playsinline` indicates
   * to the browser that non-fullscreen playback is preferred when fullscreen
   * playback is the native default, such as in iOS Safari.
   *
   * @method Html5#setPlaysinline
   * @param {boolean} playsinline
   *         - True indicates that the media should play inline.
   *         - False indicates that the media should not play inline.
   *
   * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
   */
  "playsinline"
].forEach(function(prop) {
  Html5.prototype["set" + toTitleCase$1(prop)] = function(v) {
    this.el_[prop] = v;
    if (v) {
      this.el_.setAttribute(prop, prop);
    } else {
      this.el_.removeAttribute(prop);
    }
  };
});
[
  /**
   * Get the value of `paused` from the media element. `paused` indicates whether the media element
   * is currently paused or not.
   *
   * @method Html5#paused
   * @return {boolean}
   *         The value of `paused` from the media element.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
   */
  "paused",
  /**
   * Get the value of `currentTime` from the media element. `currentTime` indicates
   * the current second that the media is at in playback.
   *
   * @method Html5#currentTime
   * @return {number}
   *         The value of `currentTime` from the media element.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
   */
  "currentTime",
  /**
   * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
   * object that represents the parts of the media that are already downloaded and
   * available for playback.
   *
   * @method Html5#buffered
   * @return {TimeRange}
   *         The value of `buffered` from the media element.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
   */
  "buffered",
  /**
   * Get the value of `volume` from the media element. `volume` indicates
   * the current playback volume of audio for a media. `volume` will be a value from 0
   * (silent) to 1 (loudest and default).
   *
   * @method Html5#volume
   * @return {number}
   *         The value of `volume` from the media element. Value will be between 0-1.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
   */
  "volume",
  /**
   * Get the value of `poster` from the media element. `poster` indicates
   * that the url of an image file that can/will be shown when no media data is available.
   *
   * @method Html5#poster
   * @return {string}
   *         The value of `poster` from the media element. Value will be a url to an
   *         image.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
   */
  "poster",
  /**
   * Get the value of `preload` from the media element. `preload` indicates
   * what should download before the media is interacted with. It can have the following
   * values:
   * - none: nothing should be downloaded
   * - metadata: poster and the first few frames of the media may be downloaded to get
   *   media dimensions and other metadata
   * - auto: allow the media and metadata for the media to be downloaded before
   *    interaction
   *
   * @method Html5#preload
   * @return {string}
   *         The value of `preload` from the media element. Will be 'none', 'metadata',
   *         or 'auto'.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
   */
  "preload",
  /**
   * Get the value of the `error` from the media element. `error` indicates any
   * MediaError that may have occurred during playback. If error returns null there is no
   * current error.
   *
   * @method Html5#error
   * @return {MediaError|null}
   *         The value of `error` from the media element. Will be `MediaError` if there
   *         is a current error and null otherwise.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
   */
  "error",
  /**
   * Get the value of `seeking` from the media element. `seeking` indicates whether the
   * media is currently seeking to a new position or not.
   *
   * @method Html5#seeking
   * @return {boolean}
   *         - The value of `seeking` from the media element.
   *         - True indicates that the media is currently seeking to a new position.
   *         - False indicates that the media is not seeking to a new position at this time.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
   */
  "seeking",
  /**
   * Get the value of `seekable` from the media element. `seekable` returns a
   * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
   *
   * @method Html5#seekable
   * @return {TimeRange}
   *         The value of `seekable` from the media element. A `TimeRange` object
   *         indicating the current ranges of time that can be seeked to.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
   */
  "seekable",
  /**
   * Get the value of `ended` from the media element. `ended` indicates whether
   * the media has reached the end or not.
   *
   * @method Html5#ended
   * @return {boolean}
   *         - The value of `ended` from the media element.
   *         - True indicates that the media has ended.
   *         - False indicates that the media has not ended.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
   */
  "ended",
  /**
   * Get the value of `playbackRate` from the media element. `playbackRate` indicates
   * the rate at which the media is currently playing back. Examples:
   *   - if playbackRate is set to 2, media will play twice as fast.
   *   - if playbackRate is set to 0.5, media will play half as fast.
   *
   * @method Html5#playbackRate
   * @return {number}
   *         The value of `playbackRate` from the media element. A number indicating
   *         the current playback speed of the media, where 1 is normal speed.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
   */
  "playbackRate",
  /**
   * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
   * the rate at which the media is currently playing back. This value will not indicate the current
   * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
   *
   * Examples:
   *   - if defaultPlaybackRate is set to 2, media will play twice as fast.
   *   - if defaultPlaybackRate is set to 0.5, media will play half as fast.
   *
   * @method Html5.prototype.defaultPlaybackRate
   * @return {number}
   *         The value of `defaultPlaybackRate` from the media element. A number indicating
   *         the current playback speed of the media, where 1 is normal speed.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
   */
  "defaultPlaybackRate",
  /**
   * Get the value of 'disablePictureInPicture' from the video element.
   *
   * @method Html5#disablePictureInPicture
   * @return {boolean} value
   *         - The value of `disablePictureInPicture` from the video element.
   *         - True indicates that the video can't be played in Picture-In-Picture mode
   *         - False indicates that the video can be played in Picture-In-Picture mode
   *
   * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
   */
  "disablePictureInPicture",
  /**
   * Get the value of `played` from the media element. `played` returns a `TimeRange`
   * object representing points in the media timeline that have been played.
   *
   * @method Html5#played
   * @return {TimeRange}
   *         The value of `played` from the media element. A `TimeRange` object indicating
   *         the ranges of time that have been played.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
   */
  "played",
  /**
   * Get the value of `networkState` from the media element. `networkState` indicates
   * the current network state. It returns an enumeration from the following list:
   * - 0: NETWORK_EMPTY
   * - 1: NETWORK_IDLE
   * - 2: NETWORK_LOADING
   * - 3: NETWORK_NO_SOURCE
   *
   * @method Html5#networkState
   * @return {number}
   *         The value of `networkState` from the media element. This will be a number
   *         from the list in the description.
   *
   * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
   */
  "networkState",
  /**
   * Get the value of `readyState` from the media element. `readyState` indicates
   * the current state of the media element. It returns an enumeration from the
   * following list:
   * - 0: HAVE_NOTHING
   * - 1: HAVE_METADATA
   * - 2: HAVE_CURRENT_DATA
   * - 3: HAVE_FUTURE_DATA
   * - 4: HAVE_ENOUGH_DATA
   *
   * @method Html5#readyState
   * @return {number}
   *         The value of `readyState` from the media element. This will be a number
   *         from the list in the description.
   *
   * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
   */
  "readyState",
  /**
   * Get the value of `videoWidth` from the video element. `videoWidth` indicates
   * the current width of the video in css pixels.
   *
   * @method Html5#videoWidth
   * @return {number}
   *         The value of `videoWidth` from the video element. This will be a number
   *         in css pixels.
   *
   * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
   */
  "videoWidth",
  /**
   * Get the value of `videoHeight` from the video element. `videoHeight` indicates
   * the current height of the video in css pixels.
   *
   * @method Html5#videoHeight
   * @return {number}
   *         The value of `videoHeight` from the video element. This will be a number
   *         in css pixels.
   *
   * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
   */
  "videoHeight",
  /**
   * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
   * to the browser that should sent the cookies along with the requests for the
   * different assets/playlists
   *
   * @method Html5#crossOrigin
   * @return {string}
   *         - anonymous indicates that the media should not sent cookies.
   *         - use-credentials indicates that the media should sent cookies along the requests.
   *
   * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
   */
  "crossOrigin"
].forEach(function(prop) {
  Html5.prototype[prop] = function() {
    return this.el_[prop];
  };
});
[
  /**
   * Set the value of `volume` on the media element. `volume` indicates the current
   * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
   * so on.
   *
   * @method Html5#setVolume
   * @param {number} percentAsDecimal
   *        The volume percent as a decimal. Valid range is from 0-1.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
   */
  "volume",
  /**
   * Set the value of `src` on the media element. `src` indicates the current
   * {@link Tech~SourceObject} for the media.
   *
   * @method Html5#setSrc
   * @param {Tech~SourceObject} src
   *        The source object to set as the current source.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
   */
  "src",
  /**
   * Set the value of `poster` on the media element. `poster` is the url to
   * an image file that can/will be shown when no media data is available.
   *
   * @method Html5#setPoster
   * @param {string} poster
   *        The url to an image that should be used as the `poster` for the media
   *        element.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
   */
  "poster",
  /**
   * Set the value of `preload` on the media element. `preload` indicates
   * what should download before the media is interacted with. It can have the following
   * values:
   * - none: nothing should be downloaded
   * - metadata: poster and the first few frames of the media may be downloaded to get
   *   media dimensions and other metadata
   * - auto: allow the media and metadata for the media to be downloaded before
   *    interaction
   *
   * @method Html5#setPreload
   * @param {string} preload
   *         The value of `preload` to set on the media element. Must be 'none', 'metadata',
   *         or 'auto'.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
   */
  "preload",
  /**
   * Set the value of `playbackRate` on the media element. `playbackRate` indicates
   * the rate at which the media should play back. Examples:
   *   - if playbackRate is set to 2, media will play twice as fast.
   *   - if playbackRate is set to 0.5, media will play half as fast.
   *
   * @method Html5#setPlaybackRate
   * @return {number}
   *         The value of `playbackRate` from the media element. A number indicating
   *         the current playback speed of the media, where 1 is normal speed.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
   */
  "playbackRate",
  /**
   * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
   * the rate at which the media should play back upon initial startup. Changing this value
   * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
   *
   * Example Values:
   *   - if playbackRate is set to 2, media will play twice as fast.
   *   - if playbackRate is set to 0.5, media will play half as fast.
   *
   * @method Html5.prototype.setDefaultPlaybackRate
   * @return {number}
   *         The value of `defaultPlaybackRate` from the media element. A number indicating
   *         the current playback speed of the media, where 1 is normal speed.
   *
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
   */
  "defaultPlaybackRate",
  /**
   * Prevents the browser from suggesting a Picture-in-Picture context menu
   * or to request Picture-in-Picture automatically in some cases.
   *
   * @method Html5#setDisablePictureInPicture
   * @param {boolean} value
   *         The true value will disable Picture-in-Picture mode.
   *
   * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
   */
  "disablePictureInPicture",
  /**
   * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
   * to the browser that should sent the cookies along with the requests for the
   * different assets/playlists
   *
   * @method Html5#setCrossOrigin
   * @param {string} crossOrigin
   *         - anonymous indicates that the media should not sent cookies.
   *         - use-credentials indicates that the media should sent cookies along the requests.
   *
   * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
   */
  "crossOrigin"
].forEach(function(prop) {
  Html5.prototype["set" + toTitleCase$1(prop)] = function(v) {
    this.el_[prop] = v;
  };
});
[
  /**
   * A wrapper around the media elements `pause` function. This will call the `HTML5`
   * media elements `pause` function.
   *
   * @method Html5#pause
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
   */
  "pause",
  /**
   * A wrapper around the media elements `load` function. This will call the `HTML5`s
   * media element `load` function.
   *
   * @method Html5#load
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
   */
  "load",
  /**
   * A wrapper around the media elements `play` function. This will call the `HTML5`s
   * media element `play` function.
   *
   * @method Html5#play
   * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
   */
  "play"
].forEach(function(prop) {
  Html5.prototype[prop] = function() {
    return this.el_[prop]();
  };
});
Tech.withSourceHandlers(Html5);
Html5.nativeSourceHandler = {};
Html5.nativeSourceHandler.canPlayType = function(type2) {
  try {
    return Html5.TEST_VID.canPlayType(type2);
  } catch (e) {
    return "";
  }
};
Html5.nativeSourceHandler.canHandleSource = function(source, options) {
  if (source.type) {
    return Html5.nativeSourceHandler.canPlayType(source.type);
  } else if (source.src) {
    var ext = getFileExtension(source.src);
    return Html5.nativeSourceHandler.canPlayType("video/" + ext);
  }
  return "";
};
Html5.nativeSourceHandler.handleSource = function(source, tech, options) {
  tech.setSrc(source.src);
};
Html5.nativeSourceHandler.dispose = function() {
};
Html5.registerSourceHandler(Html5.nativeSourceHandler);
Tech.registerTech("Html5", Html5);
var TECH_EVENTS_RETRIGGER = [
  /**
   * Fired while the user agent is downloading media data.
   *
   * @event Player#progress
   * @type {EventTarget~Event}
   */
  /**
   * Retrigger the `progress` event that was triggered by the {@link Tech}.
   *
   * @private
   * @method Player#handleTechProgress_
   * @fires Player#progress
   * @listens Tech#progress
   */
  "progress",
  /**
   * Fires when the loading of an audio/video is aborted.
   *
   * @event Player#abort
   * @type {EventTarget~Event}
   */
  /**
   * Retrigger the `abort` event that was triggered by the {@link Tech}.
   *
   * @private
   * @method Player#handleTechAbort_
   * @fires Player#abort
   * @listens Tech#abort
   */
  "abort",
  /**
   * Fires when the browser is intentionally not getting media data.
   *
   * @event Player#suspend
   * @type {EventTarget~Event}
   */
  /**
   * Retrigger the `suspend` event that was triggered by the {@link Tech}.
   *
   * @private
   * @method Player#handleTechSuspend_
   * @fires Player#suspend
   * @listens Tech#suspend
   */
  "suspend",
  /**
   * Fires when the current playlist is empty.
   *
   * @event Player#emptied
   * @type {EventTarget~Event}
   */
  /**
   * Retrigger the `emptied` event that was triggered by the {@link Tech}.
   *
   * @private
   * @method Player#handleTechEmptied_
   * @fires Player#emptied
   * @listens Tech#emptied
   */
  "emptied",
  /**
   * Fires when the browser is trying to get media data, but data is not available.
   *
   * @event Player#stalled
   * @type {EventTarget~Event}
   */
  /**
   * Retrigger the `stalled` event that was triggered by the {@link Tech}.
   *
   * @private
   * @method Player#handleTechStalled_
   * @fires Player#stalled
   * @listens Tech#stalled
   */
  "stalled",
  /**
   * Fires when the browser has loaded meta data for the audio/video.
   *
   * @event Player#loadedmetadata
   * @type {EventTarget~Event}
   */
  /**
   * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
   *
   * @private
   * @method Player#handleTechLoadedmetadata_
   * @fires Player#loadedmetadata
   * @listens Tech#loadedmetadata
   */
  "loadedmetadata",
  /**
   * Fires when the browser has loaded the current frame of the audio/video.
   *
   * @event Player#loadeddata
   * @type {event}
   */
  /**
   * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
   *
   * @private
   * @method Player#handleTechLoaddeddata_
   * @fires Player#loadeddata
   * @listens Tech#loadeddata
   */
  "loadeddata",
  /**
   * Fires when the current playback position has changed.
   *
   * @event Player#timeupdate
   * @type {event}
   */
  /**
   * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
   *
   * @private
   * @method Player#handleTechTimeUpdate_
   * @fires Player#timeupdate
   * @listens Tech#timeupdate
   */
  "timeupdate",
  /**
   * Fires when the video's intrinsic dimensions change
   *
   * @event Player#resize
   * @type {event}
   */
  /**
   * Retrigger the `resize` event that was triggered by the {@link Tech}.
   *
   * @private
   * @method Player#handleTechResize_
   * @fires Player#resize
   * @listens Tech#resize
   */
  "resize",
  /**
   * Fires when the volume has been changed
   *
   * @event Player#volumechange
   * @type {event}
   */
  /**
   * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
   *
   * @private
   * @method Player#handleTechVolumechange_
   * @fires Player#volumechange
   * @listens Tech#volumechange
   */
  "volumechange",
  /**
   * Fires when the text track has been changed
   *
   * @event Player#texttrackchange
   * @type {event}
   */
  /**
   * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
   *
   * @private
   * @method Player#handleTechTexttrackchange_
   * @fires Player#texttrackchange
   * @listens Tech#texttrackchange
   */
  "texttrackchange"
];
var TECH_EVENTS_QUEUE = {
  canplay: "CanPlay",
  canplaythrough: "CanPlayThrough",
  playing: "Playing",
  seeked: "Seeked"
};
var BREAKPOINT_ORDER = ["tiny", "xsmall", "small", "medium", "large", "xlarge", "huge"];
var BREAKPOINT_CLASSES = {};
BREAKPOINT_ORDER.forEach(function(k) {
  var v = k.charAt(0) === "x" ? "x-" + k.substring(1) : k;
  BREAKPOINT_CLASSES[k] = "vjs-layout-" + v;
});
var DEFAULT_BREAKPOINTS = {
  tiny: 210,
  xsmall: 320,
  small: 425,
  medium: 768,
  large: 1440,
  xlarge: 2560,
  huge: Infinity
};
var Player = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(Player2, _Component);
  function Player2(tag, options, ready) {
    var _this;
    tag.id = tag.id || options.id || "vjs_video_" + newGUID();
    options = assign(Player2.getTagSettings(tag), options);
    options.initChildren = false;
    options.createEl = false;
    options.evented = false;
    options.reportTouchActivity = false;
    if (!options.language) {
      if (typeof tag.closest === "function") {
        var closest = tag.closest("[lang]");
        if (closest && closest.getAttribute) {
          options.language = closest.getAttribute("lang");
        }
      } else {
        var element = tag;
        while (element && element.nodeType === 1) {
          if (getAttributes(element).hasOwnProperty("lang")) {
            options.language = element.getAttribute("lang");
            break;
          }
          element = element.parentNode;
        }
      }
    }
    _this = _Component.call(this, null, options, ready) || this;
    _this.boundDocumentFullscreenChange_ = function(e) {
      return _this.documentFullscreenChange_(e);
    };
    _this.boundFullWindowOnEscKey_ = function(e) {
      return _this.fullWindowOnEscKey(e);
    };
    _this.boundUpdateStyleEl_ = function(e) {
      return _this.updateStyleEl_(e);
    };
    _this.boundApplyInitTime_ = function(e) {
      return _this.applyInitTime_(e);
    };
    _this.boundUpdateCurrentBreakpoint_ = function(e) {
      return _this.updateCurrentBreakpoint_(e);
    };
    _this.boundHandleTechClick_ = function(e) {
      return _this.handleTechClick_(e);
    };
    _this.boundHandleTechDoubleClick_ = function(e) {
      return _this.handleTechDoubleClick_(e);
    };
    _this.boundHandleTechTouchStart_ = function(e) {
      return _this.handleTechTouchStart_(e);
    };
    _this.boundHandleTechTouchMove_ = function(e) {
      return _this.handleTechTouchMove_(e);
    };
    _this.boundHandleTechTouchEnd_ = function(e) {
      return _this.handleTechTouchEnd_(e);
    };
    _this.boundHandleTechTap_ = function(e) {
      return _this.handleTechTap_(e);
    };
    _this.isFullscreen_ = false;
    _this.log = createLogger2(_this.id_);
    _this.fsApi_ = FullscreenApi;
    _this.isPosterFromTech_ = false;
    _this.queuedCallbacks_ = [];
    _this.isReady_ = false;
    _this.hasStarted_ = false;
    _this.userActive_ = false;
    _this.debugEnabled_ = false;
    _this.audioOnlyMode_ = false;
    _this.audioPosterMode_ = false;
    _this.audioOnlyCache_ = {
      playerHeight: null,
      hiddenChildren: []
    };
    if (!_this.options_ || !_this.options_.techOrder || !_this.options_.techOrder.length) {
      throw new Error("No techOrder specified. Did you overwrite videojs.options instead of just changing the properties you want to override?");
    }
    _this.tag = tag;
    _this.tagAttributes = tag && getAttributes(tag);
    _this.language(_this.options_.language);
    if (options.languages) {
      var languagesToLower = {};
      Object.getOwnPropertyNames(options.languages).forEach(function(name) {
        languagesToLower[name.toLowerCase()] = options.languages[name];
      });
      _this.languages_ = languagesToLower;
    } else {
      _this.languages_ = Player2.prototype.options_.languages;
    }
    _this.resetCache_();
    _this.poster_ = options.poster || "";
    _this.controls_ = !!options.controls;
    tag.controls = false;
    tag.removeAttribute("controls");
    _this.changingSrc_ = false;
    _this.playCallbacks_ = [];
    _this.playTerminatedQueue_ = [];
    if (tag.hasAttribute("autoplay")) {
      _this.autoplay(true);
    } else {
      _this.autoplay(_this.options_.autoplay);
    }
    if (options.plugins) {
      Object.keys(options.plugins).forEach(function(name) {
        if (typeof _this[name] !== "function") {
          throw new Error('plugin "' + name + '" does not exist');
        }
      });
    }
    _this.scrubbing_ = false;
    _this.el_ = _this.createEl();
    evented(_assertThisInitialized(_this), {
      eventBusKey: "el_"
    });
    if (_this.fsApi_.requestFullscreen) {
      on(import_document.default, _this.fsApi_.fullscreenchange, _this.boundDocumentFullscreenChange_);
      _this.on(_this.fsApi_.fullscreenchange, _this.boundDocumentFullscreenChange_);
    }
    if (_this.fluid_) {
      _this.on(["playerreset", "resize"], _this.boundUpdateStyleEl_);
    }
    var playerOptionsCopy = mergeOptions$3(_this.options_);
    if (options.plugins) {
      Object.keys(options.plugins).forEach(function(name) {
        _this[name](options.plugins[name]);
      });
    }
    if (options.debug) {
      _this.debug(true);
    }
    _this.options_.playerOptions = playerOptionsCopy;
    _this.middleware_ = [];
    _this.playbackRates(options.playbackRates);
    _this.initChildren();
    _this.isAudio(tag.nodeName.toLowerCase() === "audio");
    if (_this.controls()) {
      _this.addClass("vjs-controls-enabled");
    } else {
      _this.addClass("vjs-controls-disabled");
    }
    _this.el_.setAttribute("role", "region");
    if (_this.isAudio()) {
      _this.el_.setAttribute("aria-label", _this.localize("Audio Player"));
    } else {
      _this.el_.setAttribute("aria-label", _this.localize("Video Player"));
    }
    if (_this.isAudio()) {
      _this.addClass("vjs-audio");
    }
    if (_this.flexNotSupported_()) {
      _this.addClass("vjs-no-flex");
    }
    if (TOUCH_ENABLED) {
      _this.addClass("vjs-touch-enabled");
    }
    if (!IS_IOS) {
      _this.addClass("vjs-workinghover");
    }
    Player2.players[_this.id_] = _assertThisInitialized(_this);
    var majorVersion = version$5.split(".")[0];
    _this.addClass("vjs-v" + majorVersion);
    _this.userActive(true);
    _this.reportUserActivity();
    _this.one("play", function(e) {
      return _this.listenForUserActivity_(e);
    });
    _this.on("stageclick", function(e) {
      return _this.handleStageClick_(e);
    });
    _this.on("keydown", function(e) {
      return _this.handleKeyDown(e);
    });
    _this.on("languagechange", function(e) {
      return _this.handleLanguagechange(e);
    });
    _this.breakpoints(_this.options_.breakpoints);
    _this.responsive(_this.options_.responsive);
    _this.on("ready", function() {
      _this.audioPosterMode(_this.options_.audioPosterMode);
      _this.audioOnlyMode(_this.options_.audioOnlyMode);
    });
    return _this;
  }
  var _proto = Player2.prototype;
  _proto.dispose = function dispose() {
    var _this2 = this;
    this.trigger("dispose");
    this.off("dispose");
    off(import_document.default, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
    off(import_document.default, "keydown", this.boundFullWindowOnEscKey_);
    if (this.styleEl_ && this.styleEl_.parentNode) {
      this.styleEl_.parentNode.removeChild(this.styleEl_);
      this.styleEl_ = null;
    }
    Player2.players[this.id_] = null;
    if (this.tag && this.tag.player) {
      this.tag.player = null;
    }
    if (this.el_ && this.el_.player) {
      this.el_.player = null;
    }
    if (this.tech_) {
      this.tech_.dispose();
      this.isPosterFromTech_ = false;
      this.poster_ = "";
    }
    if (this.playerElIngest_) {
      this.playerElIngest_ = null;
    }
    if (this.tag) {
      this.tag = null;
    }
    clearCacheForPlayer(this);
    ALL.names.forEach(function(name) {
      var props = ALL[name];
      var list = _this2[props.getterName]();
      if (list && list.off) {
        list.off();
      }
    });
    _Component.prototype.dispose.call(this, {
      restoreEl: this.options_.restoreEl
    });
  };
  _proto.createEl = function createEl2() {
    var tag = this.tag;
    var el;
    var playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute("data-vjs-player");
    var divEmbed = this.tag.tagName.toLowerCase() === "video-js";
    if (playerElIngest) {
      el = this.el_ = tag.parentNode;
    } else if (!divEmbed) {
      el = this.el_ = _Component.prototype.createEl.call(this, "div");
    }
    var attrs = getAttributes(tag);
    if (divEmbed) {
      el = this.el_ = tag;
      tag = this.tag = import_document.default.createElement("video");
      while (el.children.length) {
        tag.appendChild(el.firstChild);
      }
      if (!hasClass(el, "video-js")) {
        addClass(el, "video-js");
      }
      el.appendChild(tag);
      playerElIngest = this.playerElIngest_ = el;
      Object.keys(el).forEach(function(k) {
        try {
          tag[k] = el[k];
        } catch (e) {
        }
      });
    }
    tag.setAttribute("tabindex", "-1");
    attrs.tabindex = "-1";
    if (IE_VERSION || IS_CHROME && IS_WINDOWS) {
      tag.setAttribute("role", "application");
      attrs.role = "application";
    }
    tag.removeAttribute("width");
    tag.removeAttribute("height");
    if ("width" in attrs) {
      delete attrs.width;
    }
    if ("height" in attrs) {
      delete attrs.height;
    }
    Object.getOwnPropertyNames(attrs).forEach(function(attr) {
      if (!(divEmbed && attr === "class")) {
        el.setAttribute(attr, attrs[attr]);
      }
      if (divEmbed) {
        tag.setAttribute(attr, attrs[attr]);
      }
    });
    tag.playerId = tag.id;
    tag.id += "_html5_api";
    tag.className = "vjs-tech";
    tag.player = el.player = this;
    this.addClass("vjs-paused");
    if (import_window6.default.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
      this.styleEl_ = createStyleElement("vjs-styles-dimensions");
      var defaultsStyleEl = $(".vjs-styles-defaults");
      var head = $("head");
      head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
    }
    this.fill_ = false;
    this.fluid_ = false;
    this.width(this.options_.width);
    this.height(this.options_.height);
    this.fill(this.options_.fill);
    this.fluid(this.options_.fluid);
    this.aspectRatio(this.options_.aspectRatio);
    this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin);
    var links = tag.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
      var linkEl = links.item(i);
      addClass(linkEl, "vjs-hidden");
      linkEl.setAttribute("hidden", "hidden");
    }
    tag.initNetworkState_ = tag.networkState;
    if (tag.parentNode && !playerElIngest) {
      tag.parentNode.insertBefore(el, tag);
    }
    prependTo(tag, el);
    this.children_.unshift(tag);
    this.el_.setAttribute("lang", this.language_);
    this.el_.setAttribute("translate", "no");
    this.el_ = el;
    return el;
  };
  _proto.crossOrigin = function crossOrigin(value) {
    if (!value) {
      return this.techGet_("crossOrigin");
    }
    if (value !== "anonymous" && value !== "use-credentials") {
      log$1.warn('crossOrigin must be "anonymous" or "use-credentials", given "' + value + '"');
      return;
    }
    this.techCall_("setCrossOrigin", value);
    return;
  };
  _proto.width = function width2(value) {
    return this.dimension("width", value);
  };
  _proto.height = function height2(value) {
    return this.dimension("height", value);
  };
  _proto.dimension = function dimension(_dimension, value) {
    var privDimension = _dimension + "_";
    if (value === void 0) {
      return this[privDimension] || 0;
    }
    if (value === "" || value === "auto") {
      this[privDimension] = void 0;
      this.updateStyleEl_();
      return;
    }
    var parsedVal = parseFloat(value);
    if (isNaN(parsedVal)) {
      log$1.error('Improper value "' + value + '" supplied for for ' + _dimension);
      return;
    }
    this[privDimension] = parsedVal;
    this.updateStyleEl_();
  };
  _proto.fluid = function fluid(bool) {
    var _this3 = this;
    if (bool === void 0) {
      return !!this.fluid_;
    }
    this.fluid_ = !!bool;
    if (isEvented(this)) {
      this.off(["playerreset", "resize"], this.boundUpdateStyleEl_);
    }
    if (bool) {
      this.addClass("vjs-fluid");
      this.fill(false);
      addEventedCallback(this, function() {
        _this3.on(["playerreset", "resize"], _this3.boundUpdateStyleEl_);
      });
    } else {
      this.removeClass("vjs-fluid");
    }
    this.updateStyleEl_();
  };
  _proto.fill = function fill(bool) {
    if (bool === void 0) {
      return !!this.fill_;
    }
    this.fill_ = !!bool;
    if (bool) {
      this.addClass("vjs-fill");
      this.fluid(false);
    } else {
      this.removeClass("vjs-fill");
    }
  };
  _proto.aspectRatio = function aspectRatio(ratio) {
    if (ratio === void 0) {
      return this.aspectRatio_;
    }
    if (!/^\d+\:\d+$/.test(ratio)) {
      throw new Error("Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.");
    }
    this.aspectRatio_ = ratio;
    this.fluid(true);
    this.updateStyleEl_();
  };
  _proto.updateStyleEl_ = function updateStyleEl_() {
    if (import_window6.default.VIDEOJS_NO_DYNAMIC_STYLE === true) {
      var _width = typeof this.width_ === "number" ? this.width_ : this.options_.width;
      var _height = typeof this.height_ === "number" ? this.height_ : this.options_.height;
      var techEl = this.tech_ && this.tech_.el();
      if (techEl) {
        if (_width >= 0) {
          techEl.width = _width;
        }
        if (_height >= 0) {
          techEl.height = _height;
        }
      }
      return;
    }
    var width2;
    var height2;
    var aspectRatio;
    var idClass;
    if (this.aspectRatio_ !== void 0 && this.aspectRatio_ !== "auto") {
      aspectRatio = this.aspectRatio_;
    } else if (this.videoWidth() > 0) {
      aspectRatio = this.videoWidth() + ":" + this.videoHeight();
    } else {
      aspectRatio = "16:9";
    }
    var ratioParts = aspectRatio.split(":");
    var ratioMultiplier = ratioParts[1] / ratioParts[0];
    if (this.width_ !== void 0) {
      width2 = this.width_;
    } else if (this.height_ !== void 0) {
      width2 = this.height_ / ratioMultiplier;
    } else {
      width2 = this.videoWidth() || 300;
    }
    if (this.height_ !== void 0) {
      height2 = this.height_;
    } else {
      height2 = width2 * ratioMultiplier;
    }
    if (/^[^a-zA-Z]/.test(this.id())) {
      idClass = "dimensions-" + this.id();
    } else {
      idClass = this.id() + "-dimensions";
    }
    this.addClass(idClass);
    setTextContent(this.styleEl_, "\n      ." + idClass + " {\n        width: " + width2 + "px;\n        height: " + height2 + "px;\n      }\n\n      ." + idClass + ".vjs-fluid:not(.vjs-audio-only-mode) {\n        padding-top: " + ratioMultiplier * 100 + "%;\n      }\n    ");
  };
  _proto.loadTech_ = function loadTech_(techName, source) {
    var _this4 = this;
    if (this.tech_) {
      this.unloadTech_();
    }
    var titleTechName = toTitleCase$1(techName);
    var camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1);
    if (titleTechName !== "Html5" && this.tag) {
      Tech.getTech("Html5").disposeMediaElement(this.tag);
      this.tag.player = null;
      this.tag = null;
    }
    this.techName_ = titleTechName;
    this.isReady_ = false;
    var autoplay = this.autoplay();
    if (typeof this.autoplay() === "string" || this.autoplay() === true && this.options_.normalizeAutoplay) {
      autoplay = false;
    }
    var techOptions = {
      source,
      autoplay,
      "nativeControlsForTouch": this.options_.nativeControlsForTouch,
      "playerId": this.id(),
      "techId": this.id() + "_" + camelTechName + "_api",
      "playsinline": this.options_.playsinline,
      "preload": this.options_.preload,
      "loop": this.options_.loop,
      "disablePictureInPicture": this.options_.disablePictureInPicture,
      "muted": this.options_.muted,
      "poster": this.poster(),
      "language": this.language(),
      "playerElIngest": this.playerElIngest_ || false,
      "vtt.js": this.options_["vtt.js"],
      "canOverridePoster": !!this.options_.techCanOverridePoster,
      "enableSourceset": this.options_.enableSourceset,
      "Promise": this.options_.Promise
    };
    ALL.names.forEach(function(name) {
      var props = ALL[name];
      techOptions[props.getterName] = _this4[props.privateName];
    });
    assign(techOptions, this.options_[titleTechName]);
    assign(techOptions, this.options_[camelTechName]);
    assign(techOptions, this.options_[techName.toLowerCase()]);
    if (this.tag) {
      techOptions.tag = this.tag;
    }
    if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
      techOptions.startTime = this.cache_.currentTime;
    }
    var TechClass = Tech.getTech(techName);
    if (!TechClass) {
      throw new Error("No Tech named '" + titleTechName + "' exists! '" + titleTechName + "' should be registered using videojs.registerTech()'");
    }
    this.tech_ = new TechClass(techOptions);
    this.tech_.ready(bind(this, this.handleTechReady_), true);
    textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
    TECH_EVENTS_RETRIGGER.forEach(function(event) {
      _this4.on(_this4.tech_, event, function(e) {
        return _this4["handleTech" + toTitleCase$1(event) + "_"](e);
      });
    });
    Object.keys(TECH_EVENTS_QUEUE).forEach(function(event) {
      _this4.on(_this4.tech_, event, function(eventObj) {
        if (_this4.tech_.playbackRate() === 0 && _this4.tech_.seeking()) {
          _this4.queuedCallbacks_.push({
            callback: _this4["handleTech" + TECH_EVENTS_QUEUE[event] + "_"].bind(_this4),
            event: eventObj
          });
          return;
        }
        _this4["handleTech" + TECH_EVENTS_QUEUE[event] + "_"](eventObj);
      });
    });
    this.on(this.tech_, "loadstart", function(e) {
      return _this4.handleTechLoadStart_(e);
    });
    this.on(this.tech_, "sourceset", function(e) {
      return _this4.handleTechSourceset_(e);
    });
    this.on(this.tech_, "waiting", function(e) {
      return _this4.handleTechWaiting_(e);
    });
    this.on(this.tech_, "ended", function(e) {
      return _this4.handleTechEnded_(e);
    });
    this.on(this.tech_, "seeking", function(e) {
      return _this4.handleTechSeeking_(e);
    });
    this.on(this.tech_, "play", function(e) {
      return _this4.handleTechPlay_(e);
    });
    this.on(this.tech_, "firstplay", function(e) {
      return _this4.handleTechFirstPlay_(e);
    });
    this.on(this.tech_, "pause", function(e) {
      return _this4.handleTechPause_(e);
    });
    this.on(this.tech_, "durationchange", function(e) {
      return _this4.handleTechDurationChange_(e);
    });
    this.on(this.tech_, "fullscreenchange", function(e, data) {
      return _this4.handleTechFullscreenChange_(e, data);
    });
    this.on(this.tech_, "fullscreenerror", function(e, err) {
      return _this4.handleTechFullscreenError_(e, err);
    });
    this.on(this.tech_, "enterpictureinpicture", function(e) {
      return _this4.handleTechEnterPictureInPicture_(e);
    });
    this.on(this.tech_, "leavepictureinpicture", function(e) {
      return _this4.handleTechLeavePictureInPicture_(e);
    });
    this.on(this.tech_, "error", function(e) {
      return _this4.handleTechError_(e);
    });
    this.on(this.tech_, "posterchange", function(e) {
      return _this4.handleTechPosterChange_(e);
    });
    this.on(this.tech_, "textdata", function(e) {
      return _this4.handleTechTextData_(e);
    });
    this.on(this.tech_, "ratechange", function(e) {
      return _this4.handleTechRateChange_(e);
    });
    this.on(this.tech_, "loadedmetadata", this.boundUpdateStyleEl_);
    this.usingNativeControls(this.techGet_("controls"));
    if (this.controls() && !this.usingNativeControls()) {
      this.addTechControlsListeners_();
    }
    if (this.tech_.el().parentNode !== this.el() && (titleTechName !== "Html5" || !this.tag)) {
      prependTo(this.tech_.el(), this.el());
    }
    if (this.tag) {
      this.tag.player = null;
      this.tag = null;
    }
  };
  _proto.unloadTech_ = function unloadTech_() {
    var _this5 = this;
    ALL.names.forEach(function(name) {
      var props = ALL[name];
      _this5[props.privateName] = _this5[props.getterName]();
    });
    this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
    this.isReady_ = false;
    this.tech_.dispose();
    this.tech_ = false;
    if (this.isPosterFromTech_) {
      this.poster_ = "";
      this.trigger("posterchange");
    }
    this.isPosterFromTech_ = false;
  };
  _proto.tech = function tech(safety) {
    if (safety === void 0) {
      log$1.warn("Using the tech directly can be dangerous. I hope you know what you're doing.\nSee https://github.com/videojs/video.js/issues/2617 for more info.\n");
    }
    return this.tech_;
  };
  _proto.addTechControlsListeners_ = function addTechControlsListeners_() {
    this.removeTechControlsListeners_();
    this.on(this.tech_, "click", this.boundHandleTechClick_);
    this.on(this.tech_, "dblclick", this.boundHandleTechDoubleClick_);
    this.on(this.tech_, "touchstart", this.boundHandleTechTouchStart_);
    this.on(this.tech_, "touchmove", this.boundHandleTechTouchMove_);
    this.on(this.tech_, "touchend", this.boundHandleTechTouchEnd_);
    this.on(this.tech_, "tap", this.boundHandleTechTap_);
  };
  _proto.removeTechControlsListeners_ = function removeTechControlsListeners_() {
    this.off(this.tech_, "tap", this.boundHandleTechTap_);
    this.off(this.tech_, "touchstart", this.boundHandleTechTouchStart_);
    this.off(this.tech_, "touchmove", this.boundHandleTechTouchMove_);
    this.off(this.tech_, "touchend", this.boundHandleTechTouchEnd_);
    this.off(this.tech_, "click", this.boundHandleTechClick_);
    this.off(this.tech_, "dblclick", this.boundHandleTechDoubleClick_);
  };
  _proto.handleTechReady_ = function handleTechReady_() {
    this.triggerReady();
    if (this.cache_.volume) {
      this.techCall_("setVolume", this.cache_.volume);
    }
    this.handleTechPosterChange_();
    this.handleTechDurationChange_();
  };
  _proto.handleTechLoadStart_ = function handleTechLoadStart_() {
    this.removeClass("vjs-ended");
    this.removeClass("vjs-seeking");
    this.error(null);
    this.handleTechDurationChange_();
    if (!this.paused()) {
      this.trigger("loadstart");
      this.trigger("firstplay");
    } else {
      this.hasStarted(false);
      this.trigger("loadstart");
    }
    this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? "play" : this.autoplay());
  };
  _proto.manualAutoplay_ = function manualAutoplay_(type2) {
    var _this6 = this;
    if (!this.tech_ || typeof type2 !== "string") {
      return;
    }
    var resolveMuted = function resolveMuted2() {
      var previouslyMuted = _this6.muted();
      _this6.muted(true);
      var restoreMuted = function restoreMuted2() {
        _this6.muted(previouslyMuted);
      };
      _this6.playTerminatedQueue_.push(restoreMuted);
      var mutedPromise = _this6.play();
      if (!isPromise2(mutedPromise)) {
        return;
      }
      return mutedPromise["catch"](function(err) {
        restoreMuted();
        throw new Error("Rejection at manualAutoplay. Restoring muted value. " + (err ? err : ""));
      });
    };
    var promise;
    if (type2 === "any" && !this.muted()) {
      promise = this.play();
      if (isPromise2(promise)) {
        promise = promise["catch"](resolveMuted);
      }
    } else if (type2 === "muted" && !this.muted()) {
      promise = resolveMuted();
    } else {
      promise = this.play();
    }
    if (!isPromise2(promise)) {
      return;
    }
    return promise.then(function() {
      _this6.trigger({
        type: "autoplay-success",
        autoplay: type2
      });
    })["catch"](function() {
      _this6.trigger({
        type: "autoplay-failure",
        autoplay: type2
      });
    });
  };
  _proto.updateSourceCaches_ = function updateSourceCaches_(srcObj) {
    if (srcObj === void 0) {
      srcObj = "";
    }
    var src = srcObj;
    var type2 = "";
    if (typeof src !== "string") {
      src = srcObj.src;
      type2 = srcObj.type;
    }
    this.cache_.source = this.cache_.source || {};
    this.cache_.sources = this.cache_.sources || [];
    if (src && !type2) {
      type2 = findMimetype(this, src);
    }
    this.cache_.source = mergeOptions$3({}, srcObj, {
      src,
      type: type2
    });
    var matchingSources = this.cache_.sources.filter(function(s) {
      return s.src && s.src === src;
    });
    var sourceElSources = [];
    var sourceEls = this.$$("source");
    var matchingSourceEls = [];
    for (var i = 0; i < sourceEls.length; i++) {
      var sourceObj = getAttributes(sourceEls[i]);
      sourceElSources.push(sourceObj);
      if (sourceObj.src && sourceObj.src === src) {
        matchingSourceEls.push(sourceObj.src);
      }
    }
    if (matchingSourceEls.length && !matchingSources.length) {
      this.cache_.sources = sourceElSources;
    } else if (!matchingSources.length) {
      this.cache_.sources = [this.cache_.source];
    }
    this.cache_.src = src;
  };
  _proto.handleTechSourceset_ = function handleTechSourceset_(event) {
    var _this7 = this;
    if (!this.changingSrc_) {
      var updateSourceCaches = function updateSourceCaches2(src) {
        return _this7.updateSourceCaches_(src);
      };
      var playerSrc = this.currentSource().src;
      var eventSrc = event.src;
      if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
        if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
          updateSourceCaches = function updateSourceCaches2() {
          };
        }
      }
      updateSourceCaches(eventSrc);
      if (!event.src) {
        this.tech_.any(["sourceset", "loadstart"], function(e) {
          if (e.type === "sourceset") {
            return;
          }
          var techSrc = _this7.techGet("currentSrc");
          _this7.lastSource_.tech = techSrc;
          _this7.updateSourceCaches_(techSrc);
        });
      }
    }
    this.lastSource_ = {
      player: this.currentSource().src,
      tech: event.src
    };
    this.trigger({
      src: event.src,
      type: "sourceset"
    });
  };
  _proto.hasStarted = function hasStarted(request) {
    if (request === void 0) {
      return this.hasStarted_;
    }
    if (request === this.hasStarted_) {
      return;
    }
    this.hasStarted_ = request;
    if (this.hasStarted_) {
      this.addClass("vjs-has-started");
      this.trigger("firstplay");
    } else {
      this.removeClass("vjs-has-started");
    }
  };
  _proto.handleTechPlay_ = function handleTechPlay_() {
    this.removeClass("vjs-ended");
    this.removeClass("vjs-paused");
    this.addClass("vjs-playing");
    this.hasStarted(true);
    this.trigger("play");
  };
  _proto.handleTechRateChange_ = function handleTechRateChange_() {
    if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
      this.queuedCallbacks_.forEach(function(queued) {
        return queued.callback(queued.event);
      });
      this.queuedCallbacks_ = [];
    }
    this.cache_.lastPlaybackRate = this.tech_.playbackRate();
    this.trigger("ratechange");
  };
  _proto.handleTechWaiting_ = function handleTechWaiting_() {
    var _this8 = this;
    this.addClass("vjs-waiting");
    this.trigger("waiting");
    var timeWhenWaiting = this.currentTime();
    var timeUpdateListener = function timeUpdateListener2() {
      if (timeWhenWaiting !== _this8.currentTime()) {
        _this8.removeClass("vjs-waiting");
        _this8.off("timeupdate", timeUpdateListener2);
      }
    };
    this.on("timeupdate", timeUpdateListener);
  };
  _proto.handleTechCanPlay_ = function handleTechCanPlay_() {
    this.removeClass("vjs-waiting");
    this.trigger("canplay");
  };
  _proto.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() {
    this.removeClass("vjs-waiting");
    this.trigger("canplaythrough");
  };
  _proto.handleTechPlaying_ = function handleTechPlaying_() {
    this.removeClass("vjs-waiting");
    this.trigger("playing");
  };
  _proto.handleTechSeeking_ = function handleTechSeeking_() {
    this.addClass("vjs-seeking");
    this.trigger("seeking");
  };
  _proto.handleTechSeeked_ = function handleTechSeeked_() {
    this.removeClass("vjs-seeking");
    this.removeClass("vjs-ended");
    this.trigger("seeked");
  };
  _proto.handleTechFirstPlay_ = function handleTechFirstPlay_() {
    if (this.options_.starttime) {
      log$1.warn("Passing the `starttime` option to the player will be deprecated in 6.0");
      this.currentTime(this.options_.starttime);
    }
    this.addClass("vjs-has-started");
    this.trigger("firstplay");
  };
  _proto.handleTechPause_ = function handleTechPause_() {
    this.removeClass("vjs-playing");
    this.addClass("vjs-paused");
    this.trigger("pause");
  };
  _proto.handleTechEnded_ = function handleTechEnded_() {
    this.addClass("vjs-ended");
    this.removeClass("vjs-waiting");
    if (this.options_.loop) {
      this.currentTime(0);
      this.play();
    } else if (!this.paused()) {
      this.pause();
    }
    this.trigger("ended");
  };
  _proto.handleTechDurationChange_ = function handleTechDurationChange_() {
    this.duration(this.techGet_("duration"));
  };
  _proto.handleTechClick_ = function handleTechClick_(event) {
    if (!this.controls_) {
      return;
    }
    if (this.options_ === void 0 || this.options_.userActions === void 0 || this.options_.userActions.click === void 0 || this.options_.userActions.click !== false) {
      if (this.options_ !== void 0 && this.options_.userActions !== void 0 && typeof this.options_.userActions.click === "function") {
        this.options_.userActions.click.call(this, event);
      } else if (this.paused()) {
        silencePromise(this.play());
      } else {
        this.pause();
      }
    }
  };
  _proto.handleTechDoubleClick_ = function handleTechDoubleClick_(event) {
    if (!this.controls_) {
      return;
    }
    var inAllowedEls = Array.prototype.some.call(this.$$(".vjs-control-bar, .vjs-modal-dialog"), function(el) {
      return el.contains(event.target);
    });
    if (!inAllowedEls) {
      if (this.options_ === void 0 || this.options_.userActions === void 0 || this.options_.userActions.doubleClick === void 0 || this.options_.userActions.doubleClick !== false) {
        if (this.options_ !== void 0 && this.options_.userActions !== void 0 && typeof this.options_.userActions.doubleClick === "function") {
          this.options_.userActions.doubleClick.call(this, event);
        } else if (this.isFullscreen()) {
          this.exitFullscreen();
        } else {
          this.requestFullscreen();
        }
      }
    }
  };
  _proto.handleTechTap_ = function handleTechTap_() {
    this.userActive(!this.userActive());
  };
  _proto.handleTechTouchStart_ = function handleTechTouchStart_() {
    this.userWasActive = this.userActive();
  };
  _proto.handleTechTouchMove_ = function handleTechTouchMove_() {
    if (this.userWasActive) {
      this.reportUserActivity();
    }
  };
  _proto.handleTechTouchEnd_ = function handleTechTouchEnd_(event) {
    if (event.cancelable) {
      event.preventDefault();
    }
  };
  _proto.handleStageClick_ = function handleStageClick_() {
    this.reportUserActivity();
  };
  _proto.toggleFullscreenClass_ = function toggleFullscreenClass_() {
    if (this.isFullscreen()) {
      this.addClass("vjs-fullscreen");
    } else {
      this.removeClass("vjs-fullscreen");
    }
  };
  _proto.documentFullscreenChange_ = function documentFullscreenChange_(e) {
    var targetPlayer = e.target.player;
    if (targetPlayer && targetPlayer !== this) {
      return;
    }
    var el = this.el();
    var isFs = import_document.default[this.fsApi_.fullscreenElement] === el;
    if (!isFs && el.matches) {
      isFs = el.matches(":" + this.fsApi_.fullscreen);
    } else if (!isFs && el.msMatchesSelector) {
      isFs = el.msMatchesSelector(":" + this.fsApi_.fullscreen);
    }
    this.isFullscreen(isFs);
  };
  _proto.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) {
    var _this9 = this;
    if (data) {
      if (data.nativeIOSFullscreen) {
        this.addClass("vjs-ios-native-fs");
        this.tech_.one("webkitendfullscreen", function() {
          _this9.removeClass("vjs-ios-native-fs");
        });
      }
      this.isFullscreen(data.isFullscreen);
    }
  };
  _proto.handleTechFullscreenError_ = function handleTechFullscreenError_(event, err) {
    this.trigger("fullscreenerror", err);
  };
  _proto.togglePictureInPictureClass_ = function togglePictureInPictureClass_() {
    if (this.isInPictureInPicture()) {
      this.addClass("vjs-picture-in-picture");
    } else {
      this.removeClass("vjs-picture-in-picture");
    }
  };
  _proto.handleTechEnterPictureInPicture_ = function handleTechEnterPictureInPicture_(event) {
    this.isInPictureInPicture(true);
  };
  _proto.handleTechLeavePictureInPicture_ = function handleTechLeavePictureInPicture_(event) {
    this.isInPictureInPicture(false);
  };
  _proto.handleTechError_ = function handleTechError_() {
    var error = this.tech_.error();
    this.error(error);
  };
  _proto.handleTechTextData_ = function handleTechTextData_() {
    var data = null;
    if (arguments.length > 1) {
      data = arguments[1];
    }
    this.trigger("textdata", data);
  };
  _proto.getCache = function getCache() {
    return this.cache_;
  };
  _proto.resetCache_ = function resetCache_() {
    this.cache_ = {
      // Right now, the currentTime is not _really_ cached because it is always
      // retrieved from the tech (see: currentTime). However, for completeness,
      // we set it to zero here to ensure that if we do start actually caching
      // it, we reset it along with everything else.
      currentTime: 0,
      initTime: 0,
      inactivityTimeout: this.options_.inactivityTimeout,
      duration: NaN,
      lastVolume: 1,
      lastPlaybackRate: this.defaultPlaybackRate(),
      media: null,
      src: "",
      source: {},
      sources: [],
      playbackRates: [],
      volume: 1
    };
  };
  _proto.techCall_ = function techCall_(method, arg) {
    this.ready(function() {
      if (method in allowedSetters) {
        return set(this.middleware_, this.tech_, method, arg);
      } else if (method in allowedMediators) {
        return mediate(this.middleware_, this.tech_, method, arg);
      }
      try {
        if (this.tech_) {
          this.tech_[method](arg);
        }
      } catch (e) {
        log$1(e);
        throw e;
      }
    }, true);
  };
  _proto.techGet_ = function techGet_(method) {
    if (!this.tech_ || !this.tech_.isReady_) {
      return;
    }
    if (method in allowedGetters) {
      return get(this.middleware_, this.tech_, method);
    } else if (method in allowedMediators) {
      return mediate(this.middleware_, this.tech_, method);
    }
    try {
      return this.tech_[method]();
    } catch (e) {
      if (this.tech_[method] === void 0) {
        log$1("Video.js: " + method + " method not defined for " + this.techName_ + " playback technology.", e);
        throw e;
      }
      if (e.name === "TypeError") {
        log$1("Video.js: " + method + " unavailable on " + this.techName_ + " playback technology element.", e);
        this.tech_.isReady_ = false;
        throw e;
      }
      log$1(e);
      throw e;
    }
  };
  _proto.play = function play() {
    var _this10 = this;
    var PromiseClass = this.options_.Promise || import_window6.default.Promise;
    if (PromiseClass) {
      return new PromiseClass(function(resolve) {
        _this10.play_(resolve);
      });
    }
    return this.play_();
  };
  _proto.play_ = function play_(callback2) {
    var _this11 = this;
    if (callback2 === void 0) {
      callback2 = silencePromise;
    }
    this.playCallbacks_.push(callback2);
    var isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
    if (this.waitToPlay_) {
      this.off(["ready", "loadstart"], this.waitToPlay_);
      this.waitToPlay_ = null;
    }
    if (!this.isReady_ || !isSrcReady) {
      this.waitToPlay_ = function(e) {
        _this11.play_();
      };
      this.one(["ready", "loadstart"], this.waitToPlay_);
      if (!isSrcReady && (IS_ANY_SAFARI || IS_IOS)) {
        this.load();
      }
      return;
    }
    var val = this.techGet_("play");
    if (val === null) {
      this.runPlayTerminatedQueue_();
    } else {
      this.runPlayCallbacks_(val);
    }
  };
  _proto.runPlayTerminatedQueue_ = function runPlayTerminatedQueue_() {
    var queue = this.playTerminatedQueue_.slice(0);
    this.playTerminatedQueue_ = [];
    queue.forEach(function(q) {
      q();
    });
  };
  _proto.runPlayCallbacks_ = function runPlayCallbacks_(val) {
    var callbacks = this.playCallbacks_.slice(0);
    this.playCallbacks_ = [];
    this.playTerminatedQueue_ = [];
    callbacks.forEach(function(cb) {
      cb(val);
    });
  };
  _proto.pause = function pause() {
    this.techCall_("pause");
  };
  _proto.paused = function paused() {
    return this.techGet_("paused") === false ? false : true;
  };
  _proto.played = function played() {
    return this.techGet_("played") || createTimeRanges(0, 0);
  };
  _proto.scrubbing = function scrubbing(isScrubbing) {
    if (typeof isScrubbing === "undefined") {
      return this.scrubbing_;
    }
    this.scrubbing_ = !!isScrubbing;
    this.techCall_("setScrubbing", this.scrubbing_);
    if (isScrubbing) {
      this.addClass("vjs-scrubbing");
    } else {
      this.removeClass("vjs-scrubbing");
    }
  };
  _proto.currentTime = function currentTime(seconds) {
    if (typeof seconds !== "undefined") {
      if (seconds < 0) {
        seconds = 0;
      }
      if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
        this.cache_.initTime = seconds;
        this.off("canplay", this.boundApplyInitTime_);
        this.one("canplay", this.boundApplyInitTime_);
        return;
      }
      this.techCall_("setCurrentTime", seconds);
      this.cache_.initTime = 0;
      return;
    }
    this.cache_.currentTime = this.techGet_("currentTime") || 0;
    return this.cache_.currentTime;
  };
  _proto.applyInitTime_ = function applyInitTime_() {
    this.currentTime(this.cache_.initTime);
  };
  _proto.duration = function duration5(seconds) {
    if (seconds === void 0) {
      return this.cache_.duration !== void 0 ? this.cache_.duration : NaN;
    }
    seconds = parseFloat(seconds);
    if (seconds < 0) {
      seconds = Infinity;
    }
    if (seconds !== this.cache_.duration) {
      this.cache_.duration = seconds;
      if (seconds === Infinity) {
        this.addClass("vjs-live");
      } else {
        this.removeClass("vjs-live");
      }
      if (!isNaN(seconds)) {
        this.trigger("durationchange");
      }
    }
  };
  _proto.remainingTime = function remainingTime() {
    return this.duration() - this.currentTime();
  };
  _proto.remainingTimeDisplay = function remainingTimeDisplay() {
    return Math.floor(this.duration()) - Math.floor(this.currentTime());
  };
  _proto.buffered = function buffered() {
    var buffered2 = this.techGet_("buffered");
    if (!buffered2 || !buffered2.length) {
      buffered2 = createTimeRanges(0, 0);
    }
    return buffered2;
  };
  _proto.bufferedPercent = function bufferedPercent$1() {
    return bufferedPercent(this.buffered(), this.duration());
  };
  _proto.bufferedEnd = function bufferedEnd() {
    var buffered = this.buffered();
    var duration5 = this.duration();
    var end = buffered.end(buffered.length - 1);
    if (end > duration5) {
      end = duration5;
    }
    return end;
  };
  _proto.volume = function volume(percentAsDecimal) {
    var vol;
    if (percentAsDecimal !== void 0) {
      vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal)));
      this.cache_.volume = vol;
      this.techCall_("setVolume", vol);
      if (vol > 0) {
        this.lastVolume_(vol);
      }
      return;
    }
    vol = parseFloat(this.techGet_("volume"));
    return isNaN(vol) ? 1 : vol;
  };
  _proto.muted = function muted(_muted) {
    if (_muted !== void 0) {
      this.techCall_("setMuted", _muted);
      return;
    }
    return this.techGet_("muted") || false;
  };
  _proto.defaultMuted = function defaultMuted(_defaultMuted) {
    if (_defaultMuted !== void 0) {
      return this.techCall_("setDefaultMuted", _defaultMuted);
    }
    return this.techGet_("defaultMuted") || false;
  };
  _proto.lastVolume_ = function lastVolume_(percentAsDecimal) {
    if (percentAsDecimal !== void 0 && percentAsDecimal !== 0) {
      this.cache_.lastVolume = percentAsDecimal;
      return;
    }
    return this.cache_.lastVolume;
  };
  _proto.supportsFullScreen = function supportsFullScreen() {
    return this.techGet_("supportsFullScreen") || false;
  };
  _proto.isFullscreen = function isFullscreen(isFS) {
    if (isFS !== void 0) {
      var oldValue = this.isFullscreen_;
      this.isFullscreen_ = Boolean(isFS);
      if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
        this.trigger("fullscreenchange");
      }
      this.toggleFullscreenClass_();
      return;
    }
    return this.isFullscreen_;
  };
  _proto.requestFullscreen = function requestFullscreen(fullscreenOptions) {
    var PromiseClass = this.options_.Promise || import_window6.default.Promise;
    if (PromiseClass) {
      var self2 = this;
      return new PromiseClass(function(resolve, reject) {
        function offHandler() {
          self2.off("fullscreenerror", errorHandler);
          self2.off("fullscreenchange", changeHandler);
        }
        function changeHandler() {
          offHandler();
          resolve();
        }
        function errorHandler(e, err) {
          offHandler();
          reject(err);
        }
        self2.one("fullscreenchange", changeHandler);
        self2.one("fullscreenerror", errorHandler);
        var promise = self2.requestFullscreenHelper_(fullscreenOptions);
        if (promise) {
          promise.then(offHandler, offHandler);
          promise.then(resolve, reject);
        }
      });
    }
    return this.requestFullscreenHelper_();
  };
  _proto.requestFullscreenHelper_ = function requestFullscreenHelper_(fullscreenOptions) {
    var _this12 = this;
    var fsOptions;
    if (!this.fsApi_.prefixed) {
      fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
      if (fullscreenOptions !== void 0) {
        fsOptions = fullscreenOptions;
      }
    }
    if (this.fsApi_.requestFullscreen) {
      var promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
      if (promise) {
        promise.then(function() {
          return _this12.isFullscreen(true);
        }, function() {
          return _this12.isFullscreen(false);
        });
      }
      return promise;
    } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
      this.techCall_("enterFullScreen");
    } else {
      this.enterFullWindow();
    }
  };
  _proto.exitFullscreen = function exitFullscreen() {
    var PromiseClass = this.options_.Promise || import_window6.default.Promise;
    if (PromiseClass) {
      var self2 = this;
      return new PromiseClass(function(resolve, reject) {
        function offHandler() {
          self2.off("fullscreenerror", errorHandler);
          self2.off("fullscreenchange", changeHandler);
        }
        function changeHandler() {
          offHandler();
          resolve();
        }
        function errorHandler(e, err) {
          offHandler();
          reject(err);
        }
        self2.one("fullscreenchange", changeHandler);
        self2.one("fullscreenerror", errorHandler);
        var promise = self2.exitFullscreenHelper_();
        if (promise) {
          promise.then(offHandler, offHandler);
          promise.then(resolve, reject);
        }
      });
    }
    return this.exitFullscreenHelper_();
  };
  _proto.exitFullscreenHelper_ = function exitFullscreenHelper_() {
    var _this13 = this;
    if (this.fsApi_.requestFullscreen) {
      var promise = import_document.default[this.fsApi_.exitFullscreen]();
      if (promise) {
        silencePromise(promise.then(function() {
          return _this13.isFullscreen(false);
        }));
      }
      return promise;
    } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
      this.techCall_("exitFullScreen");
    } else {
      this.exitFullWindow();
    }
  };
  _proto.enterFullWindow = function enterFullWindow() {
    this.isFullscreen(true);
    this.isFullWindow = true;
    this.docOrigOverflow = import_document.default.documentElement.style.overflow;
    on(import_document.default, "keydown", this.boundFullWindowOnEscKey_);
    import_document.default.documentElement.style.overflow = "hidden";
    addClass(import_document.default.body, "vjs-full-window");
    this.trigger("enterFullWindow");
  };
  _proto.fullWindowOnEscKey = function fullWindowOnEscKey(event) {
    if (import_keycode.default.isEventKey(event, "Esc")) {
      if (this.isFullscreen() === true) {
        if (!this.isFullWindow) {
          this.exitFullscreen();
        } else {
          this.exitFullWindow();
        }
      }
    }
  };
  _proto.exitFullWindow = function exitFullWindow() {
    this.isFullscreen(false);
    this.isFullWindow = false;
    off(import_document.default, "keydown", this.boundFullWindowOnEscKey_);
    import_document.default.documentElement.style.overflow = this.docOrigOverflow;
    removeClass(import_document.default.body, "vjs-full-window");
    this.trigger("exitFullWindow");
  };
  _proto.disablePictureInPicture = function disablePictureInPicture(value) {
    if (value === void 0) {
      return this.techGet_("disablePictureInPicture");
    }
    this.techCall_("setDisablePictureInPicture", value);
    this.options_.disablePictureInPicture = value;
    this.trigger("disablepictureinpicturechanged");
  };
  _proto.isInPictureInPicture = function isInPictureInPicture(isPiP) {
    if (isPiP !== void 0) {
      this.isInPictureInPicture_ = !!isPiP;
      this.togglePictureInPictureClass_();
      return;
    }
    return !!this.isInPictureInPicture_;
  };
  _proto.requestPictureInPicture = function requestPictureInPicture() {
    if ("pictureInPictureEnabled" in import_document.default && this.disablePictureInPicture() === false) {
      return this.techGet_("requestPictureInPicture");
    }
  };
  _proto.exitPictureInPicture = function exitPictureInPicture() {
    if ("pictureInPictureEnabled" in import_document.default) {
      return import_document.default.exitPictureInPicture();
    }
  };
  _proto.handleKeyDown = function handleKeyDown(event) {
    var userActions = this.options_.userActions;
    if (!userActions || !userActions.hotkeys) {
      return;
    }
    var excludeElement = function excludeElement2(el) {
      var tagName = el.tagName.toLowerCase();
      if (el.isContentEditable) {
        return true;
      }
      var allowedInputTypes = ["button", "checkbox", "hidden", "radio", "reset", "submit"];
      if (tagName === "input") {
        return allowedInputTypes.indexOf(el.type) === -1;
      }
      var excludedTags = ["textarea"];
      return excludedTags.indexOf(tagName) !== -1;
    };
    if (excludeElement(this.el_.ownerDocument.activeElement)) {
      return;
    }
    if (typeof userActions.hotkeys === "function") {
      userActions.hotkeys.call(this, event);
    } else {
      this.handleHotkeys(event);
    }
  };
  _proto.handleHotkeys = function handleHotkeys(event) {
    var hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {};
    var _hotkeys$fullscreenKe = hotkeys.fullscreenKey, fullscreenKey = _hotkeys$fullscreenKe === void 0 ? function(keydownEvent) {
      return import_keycode.default.isEventKey(keydownEvent, "f");
    } : _hotkeys$fullscreenKe, _hotkeys$muteKey = hotkeys.muteKey, muteKey = _hotkeys$muteKey === void 0 ? function(keydownEvent) {
      return import_keycode.default.isEventKey(keydownEvent, "m");
    } : _hotkeys$muteKey, _hotkeys$playPauseKey = hotkeys.playPauseKey, playPauseKey = _hotkeys$playPauseKey === void 0 ? function(keydownEvent) {
      return import_keycode.default.isEventKey(keydownEvent, "k") || import_keycode.default.isEventKey(keydownEvent, "Space");
    } : _hotkeys$playPauseKey;
    if (fullscreenKey.call(this, event)) {
      event.preventDefault();
      event.stopPropagation();
      var FSToggle = Component$1.getComponent("FullscreenToggle");
      if (import_document.default[this.fsApi_.fullscreenEnabled] !== false) {
        FSToggle.prototype.handleClick.call(this, event);
      }
    } else if (muteKey.call(this, event)) {
      event.preventDefault();
      event.stopPropagation();
      var MuteToggle2 = Component$1.getComponent("MuteToggle");
      MuteToggle2.prototype.handleClick.call(this, event);
    } else if (playPauseKey.call(this, event)) {
      event.preventDefault();
      event.stopPropagation();
      var PlayToggle2 = Component$1.getComponent("PlayToggle");
      PlayToggle2.prototype.handleClick.call(this, event);
    }
  };
  _proto.canPlayType = function canPlayType3(type2) {
    var can;
    for (var i = 0, j = this.options_.techOrder; i < j.length; i++) {
      var techName = j[i];
      var tech = Tech.getTech(techName);
      if (!tech) {
        tech = Component$1.getComponent(techName);
      }
      if (!tech) {
        log$1.error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.');
        continue;
      }
      if (tech.isSupported()) {
        can = tech.canPlayType(type2);
        if (can) {
          return can;
        }
      }
    }
    return "";
  };
  _proto.selectSource = function selectSource(sources) {
    var _this14 = this;
    var techs = this.options_.techOrder.map(function(techName) {
      return [techName, Tech.getTech(techName)];
    }).filter(function(_ref) {
      var techName = _ref[0], tech = _ref[1];
      if (tech) {
        return tech.isSupported();
      }
      log$1.error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.');
      return false;
    });
    var findFirstPassingTechSourcePair = function findFirstPassingTechSourcePair2(outerArray, innerArray, tester) {
      var found;
      outerArray.some(function(outerChoice) {
        return innerArray.some(function(innerChoice) {
          found = tester(outerChoice, innerChoice);
          if (found) {
            return true;
          }
        });
      });
      return found;
    };
    var foundSourceAndTech;
    var flip = function flip2(fn) {
      return function(a, b) {
        return fn(b, a);
      };
    };
    var finder = function finder2(_ref2, source) {
      var techName = _ref2[0], tech = _ref2[1];
      if (tech.canPlaySource(source, _this14.options_[techName.toLowerCase()])) {
        return {
          source,
          tech: techName
        };
      }
    };
    if (this.options_.sourceOrder) {
      foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
    } else {
      foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
    }
    return foundSourceAndTech || false;
  };
  _proto.handleSrc_ = function handleSrc_(source, isRetry) {
    var _this15 = this;
    if (typeof source === "undefined") {
      return this.cache_.src || "";
    }
    if (this.resetRetryOnError_) {
      this.resetRetryOnError_();
    }
    var sources = filterSource(source);
    if (!sources.length) {
      this.setTimeout(function() {
        this.error({
          code: 4,
          message: this.options_.notSupportedMessage
        });
      }, 0);
      return;
    }
    this.changingSrc_ = true;
    if (!isRetry) {
      this.cache_.sources = sources;
    }
    this.updateSourceCaches_(sources[0]);
    setSource(this, sources[0], function(middlewareSource, mws) {
      _this15.middleware_ = mws;
      if (!isRetry) {
        _this15.cache_.sources = sources;
      }
      _this15.updateSourceCaches_(middlewareSource);
      var err = _this15.src_(middlewareSource);
      if (err) {
        if (sources.length > 1) {
          return _this15.handleSrc_(sources.slice(1));
        }
        _this15.changingSrc_ = false;
        _this15.setTimeout(function() {
          this.error({
            code: 4,
            message: this.options_.notSupportedMessage
          });
        }, 0);
        _this15.triggerReady();
        return;
      }
      setTech(mws, _this15.tech_);
    });
    if (this.options_.retryOnError && sources.length > 1) {
      var retry = function retry2() {
        _this15.error(null);
        _this15.handleSrc_(sources.slice(1), true);
      };
      var stopListeningForErrors = function stopListeningForErrors2() {
        _this15.off("error", retry);
      };
      this.one("error", retry);
      this.one("playing", stopListeningForErrors);
      this.resetRetryOnError_ = function() {
        _this15.off("error", retry);
        _this15.off("playing", stopListeningForErrors);
      };
    }
  };
  _proto.src = function src(source) {
    return this.handleSrc_(source, false);
  };
  _proto.src_ = function src_(source) {
    var _this16 = this;
    var sourceTech = this.selectSource([source]);
    if (!sourceTech) {
      return true;
    }
    if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
      this.changingSrc_ = true;
      this.loadTech_(sourceTech.tech, sourceTech.source);
      this.tech_.ready(function() {
        _this16.changingSrc_ = false;
      });
      return false;
    }
    this.ready(function() {
      if (this.tech_.constructor.prototype.hasOwnProperty("setSource")) {
        this.techCall_("setSource", source);
      } else {
        this.techCall_("src", source.src);
      }
      this.changingSrc_ = false;
    }, true);
    return false;
  };
  _proto.load = function load() {
    this.techCall_("load");
  };
  _proto.reset = function reset3() {
    var _this17 = this;
    var PromiseClass = this.options_.Promise || import_window6.default.Promise;
    if (this.paused() || !PromiseClass) {
      this.doReset_();
    } else {
      var playPromise = this.play();
      silencePromise(playPromise.then(function() {
        return _this17.doReset_();
      }));
    }
  };
  _proto.doReset_ = function doReset_() {
    if (this.tech_) {
      this.tech_.clearTracks("text");
    }
    this.resetCache_();
    this.poster("");
    this.loadTech_(this.options_.techOrder[0], null);
    this.techCall_("reset");
    this.resetControlBarUI_();
    if (isEvented(this)) {
      this.trigger("playerreset");
    }
  };
  _proto.resetControlBarUI_ = function resetControlBarUI_() {
    this.resetProgressBar_();
    this.resetPlaybackRate_();
    this.resetVolumeBar_();
  };
  _proto.resetProgressBar_ = function resetProgressBar_() {
    this.currentTime(0);
    var _ref3 = this.controlBar || {}, durationDisplay = _ref3.durationDisplay, remainingTimeDisplay = _ref3.remainingTimeDisplay;
    if (durationDisplay) {
      durationDisplay.updateContent();
    }
    if (remainingTimeDisplay) {
      remainingTimeDisplay.updateContent();
    }
  };
  _proto.resetPlaybackRate_ = function resetPlaybackRate_() {
    this.playbackRate(this.defaultPlaybackRate());
    this.handleTechRateChange_();
  };
  _proto.resetVolumeBar_ = function resetVolumeBar_() {
    this.volume(1);
    this.trigger("volumechange");
  };
  _proto.currentSources = function currentSources() {
    var source = this.currentSource();
    var sources = [];
    if (Object.keys(source).length !== 0) {
      sources.push(source);
    }
    return this.cache_.sources || sources;
  };
  _proto.currentSource = function currentSource() {
    return this.cache_.source || {};
  };
  _proto.currentSrc = function currentSrc() {
    return this.currentSource() && this.currentSource().src || "";
  };
  _proto.currentType = function currentType() {
    return this.currentSource() && this.currentSource().type || "";
  };
  _proto.preload = function preload(value) {
    if (value !== void 0) {
      this.techCall_("setPreload", value);
      this.options_.preload = value;
      return;
    }
    return this.techGet_("preload");
  };
  _proto.autoplay = function autoplay(value) {
    if (value === void 0) {
      return this.options_.autoplay || false;
    }
    var techAutoplay;
    if (typeof value === "string" && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
      this.options_.autoplay = value;
      this.manualAutoplay_(typeof value === "string" ? value : "play");
      techAutoplay = false;
    } else if (!value) {
      this.options_.autoplay = false;
    } else {
      this.options_.autoplay = true;
    }
    techAutoplay = typeof techAutoplay === "undefined" ? this.options_.autoplay : techAutoplay;
    if (this.tech_) {
      this.techCall_("setAutoplay", techAutoplay);
    }
  };
  _proto.playsinline = function playsinline(value) {
    if (value !== void 0) {
      this.techCall_("setPlaysinline", value);
      this.options_.playsinline = value;
      return this;
    }
    return this.techGet_("playsinline");
  };
  _proto.loop = function loop(value) {
    if (value !== void 0) {
      this.techCall_("setLoop", value);
      this.options_.loop = value;
      return;
    }
    return this.techGet_("loop");
  };
  _proto.poster = function poster(src) {
    if (src === void 0) {
      return this.poster_;
    }
    if (!src) {
      src = "";
    }
    if (src === this.poster_) {
      return;
    }
    this.poster_ = src;
    this.techCall_("setPoster", src);
    this.isPosterFromTech_ = false;
    this.trigger("posterchange");
  };
  _proto.handleTechPosterChange_ = function handleTechPosterChange_() {
    if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
      var newPoster = this.tech_.poster() || "";
      if (newPoster !== this.poster_) {
        this.poster_ = newPoster;
        this.isPosterFromTech_ = true;
        this.trigger("posterchange");
      }
    }
  };
  _proto.controls = function controls(bool) {
    if (bool === void 0) {
      return !!this.controls_;
    }
    bool = !!bool;
    if (this.controls_ === bool) {
      return;
    }
    this.controls_ = bool;
    if (this.usingNativeControls()) {
      this.techCall_("setControls", bool);
    }
    if (this.controls_) {
      this.removeClass("vjs-controls-disabled");
      this.addClass("vjs-controls-enabled");
      this.trigger("controlsenabled");
      if (!this.usingNativeControls()) {
        this.addTechControlsListeners_();
      }
    } else {
      this.removeClass("vjs-controls-enabled");
      this.addClass("vjs-controls-disabled");
      this.trigger("controlsdisabled");
      if (!this.usingNativeControls()) {
        this.removeTechControlsListeners_();
      }
    }
  };
  _proto.usingNativeControls = function usingNativeControls(bool) {
    if (bool === void 0) {
      return !!this.usingNativeControls_;
    }
    bool = !!bool;
    if (this.usingNativeControls_ === bool) {
      return;
    }
    this.usingNativeControls_ = bool;
    if (this.usingNativeControls_) {
      this.addClass("vjs-using-native-controls");
      this.trigger("usingnativecontrols");
    } else {
      this.removeClass("vjs-using-native-controls");
      this.trigger("usingcustomcontrols");
    }
  };
  _proto.error = function error(err) {
    var _this18 = this;
    if (err === void 0) {
      return this.error_ || null;
    }
    hooks("beforeerror").forEach(function(hookFunction) {
      var newErr = hookFunction(_this18, err);
      if (!(isObject3(newErr) && !Array.isArray(newErr) || typeof newErr === "string" || typeof newErr === "number" || newErr === null)) {
        _this18.log.error("please return a value that MediaError expects in beforeerror hooks");
        return;
      }
      err = newErr;
    });
    if (this.options_.suppressNotSupportedError && err && err.code === 4) {
      var triggerSuppressedError = function triggerSuppressedError2() {
        this.error(err);
      };
      this.options_.suppressNotSupportedError = false;
      this.any(["click", "touchstart"], triggerSuppressedError);
      this.one("loadstart", function() {
        this.off(["click", "touchstart"], triggerSuppressedError);
      });
      return;
    }
    if (err === null) {
      this.error_ = err;
      this.removeClass("vjs-error");
      if (this.errorDisplay) {
        this.errorDisplay.close();
      }
      return;
    }
    this.error_ = new MediaError(err);
    this.addClass("vjs-error");
    log$1.error("(CODE:" + this.error_.code + " " + MediaError.errorTypes[this.error_.code] + ")", this.error_.message, this.error_);
    this.trigger("error");
    hooks("error").forEach(function(hookFunction) {
      return hookFunction(_this18, _this18.error_);
    });
    return;
  };
  _proto.reportUserActivity = function reportUserActivity(event) {
    this.userActivity_ = true;
  };
  _proto.userActive = function userActive(bool) {
    if (bool === void 0) {
      return this.userActive_;
    }
    bool = !!bool;
    if (bool === this.userActive_) {
      return;
    }
    this.userActive_ = bool;
    if (this.userActive_) {
      this.userActivity_ = true;
      this.removeClass("vjs-user-inactive");
      this.addClass("vjs-user-active");
      this.trigger("useractive");
      return;
    }
    if (this.tech_) {
      this.tech_.one("mousemove", function(e) {
        e.stopPropagation();
        e.preventDefault();
      });
    }
    this.userActivity_ = false;
    this.removeClass("vjs-user-active");
    this.addClass("vjs-user-inactive");
    this.trigger("userinactive");
  };
  _proto.listenForUserActivity_ = function listenForUserActivity_() {
    var mouseInProgress;
    var lastMoveX;
    var lastMoveY;
    var handleActivity = bind(this, this.reportUserActivity);
    var handleMouseMove = function handleMouseMove2(e) {
      if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
        lastMoveX = e.screenX;
        lastMoveY = e.screenY;
        handleActivity();
      }
    };
    var handleMouseDown = function handleMouseDown2() {
      handleActivity();
      this.clearInterval(mouseInProgress);
      mouseInProgress = this.setInterval(handleActivity, 250);
    };
    var handleMouseUpAndMouseLeave = function handleMouseUpAndMouseLeave2(event) {
      handleActivity();
      this.clearInterval(mouseInProgress);
    };
    this.on("mousedown", handleMouseDown);
    this.on("mousemove", handleMouseMove);
    this.on("mouseup", handleMouseUpAndMouseLeave);
    this.on("mouseleave", handleMouseUpAndMouseLeave);
    var controlBar = this.getChild("controlBar");
    if (controlBar && !IS_IOS && !IS_ANDROID) {
      controlBar.on("mouseenter", function(event) {
        if (this.player().options_.inactivityTimeout !== 0) {
          this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
        }
        this.player().options_.inactivityTimeout = 0;
      });
      controlBar.on("mouseleave", function(event) {
        this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
      });
    }
    this.on("keydown", handleActivity);
    this.on("keyup", handleActivity);
    var inactivityTimeout;
    this.setInterval(function() {
      if (!this.userActivity_) {
        return;
      }
      this.userActivity_ = false;
      this.userActive(true);
      this.clearTimeout(inactivityTimeout);
      var timeout = this.options_.inactivityTimeout;
      if (timeout <= 0) {
        return;
      }
      inactivityTimeout = this.setTimeout(function() {
        if (!this.userActivity_) {
          this.userActive(false);
        }
      }, timeout);
    }, 250);
  };
  _proto.playbackRate = function playbackRate(rate) {
    if (rate !== void 0) {
      this.techCall_("setPlaybackRate", rate);
      return;
    }
    if (this.tech_ && this.tech_.featuresPlaybackRate) {
      return this.cache_.lastPlaybackRate || this.techGet_("playbackRate");
    }
    return 1;
  };
  _proto.defaultPlaybackRate = function defaultPlaybackRate(rate) {
    if (rate !== void 0) {
      return this.techCall_("setDefaultPlaybackRate", rate);
    }
    if (this.tech_ && this.tech_.featuresPlaybackRate) {
      return this.techGet_("defaultPlaybackRate");
    }
    return 1;
  };
  _proto.isAudio = function isAudio(bool) {
    if (bool !== void 0) {
      this.isAudio_ = !!bool;
      return;
    }
    return !!this.isAudio_;
  };
  _proto.enableAudioOnlyUI_ = function enableAudioOnlyUI_() {
    var _this19 = this;
    this.addClass("vjs-audio-only-mode");
    var playerChildren = this.children();
    var controlBar = this.getChild("ControlBar");
    var controlBarHeight = controlBar && controlBar.currentHeight();
    playerChildren.forEach(function(child) {
      if (child === controlBar) {
        return;
      }
      if (child.el_ && !child.hasClass("vjs-hidden")) {
        child.hide();
        _this19.audioOnlyCache_.hiddenChildren.push(child);
      }
    });
    this.audioOnlyCache_.playerHeight = this.currentHeight();
    this.height(controlBarHeight);
    this.trigger("audioonlymodechange");
  };
  _proto.disableAudioOnlyUI_ = function disableAudioOnlyUI_() {
    this.removeClass("vjs-audio-only-mode");
    this.audioOnlyCache_.hiddenChildren.forEach(function(child) {
      return child.show();
    });
    this.height(this.audioOnlyCache_.playerHeight);
    this.trigger("audioonlymodechange");
  };
  _proto.audioOnlyMode = function audioOnlyMode(value) {
    var _this20 = this;
    if (typeof value !== "boolean" || value === this.audioOnlyMode_) {
      return this.audioOnlyMode_;
    }
    this.audioOnlyMode_ = value;
    var PromiseClass = this.options_.Promise || import_window6.default.Promise;
    if (PromiseClass) {
      if (value) {
        var exitPromises = [];
        if (this.isInPictureInPicture()) {
          exitPromises.push(this.exitPictureInPicture());
        }
        if (this.isFullscreen()) {
          exitPromises.push(this.exitFullscreen());
        }
        if (this.audioPosterMode()) {
          exitPromises.push(this.audioPosterMode(false));
        }
        return PromiseClass.all(exitPromises).then(function() {
          return _this20.enableAudioOnlyUI_();
        });
      }
      return PromiseClass.resolve().then(function() {
        return _this20.disableAudioOnlyUI_();
      });
    }
    if (value) {
      if (this.isInPictureInPicture()) {
        this.exitPictureInPicture();
      }
      if (this.isFullscreen()) {
        this.exitFullscreen();
      }
      this.enableAudioOnlyUI_();
    } else {
      this.disableAudioOnlyUI_();
    }
  };
  _proto.enablePosterModeUI_ = function enablePosterModeUI_() {
    var tech = this.tech_ && this.tech_;
    tech.hide();
    this.addClass("vjs-audio-poster-mode");
    this.trigger("audiopostermodechange");
  };
  _proto.disablePosterModeUI_ = function disablePosterModeUI_() {
    var tech = this.tech_ && this.tech_;
    tech.show();
    this.removeClass("vjs-audio-poster-mode");
    this.trigger("audiopostermodechange");
  };
  _proto.audioPosterMode = function audioPosterMode(value) {
    var _this21 = this;
    if (typeof value !== "boolean" || value === this.audioPosterMode_) {
      return this.audioPosterMode_;
    }
    this.audioPosterMode_ = value;
    var PromiseClass = this.options_.Promise || import_window6.default.Promise;
    if (PromiseClass) {
      if (value) {
        if (this.audioOnlyMode()) {
          var audioOnlyModePromise = this.audioOnlyMode(false);
          return audioOnlyModePromise.then(function() {
            _this21.enablePosterModeUI_();
          });
        }
        return PromiseClass.resolve().then(function() {
          _this21.enablePosterModeUI_();
        });
      }
      return PromiseClass.resolve().then(function() {
        _this21.disablePosterModeUI_();
      });
    }
    if (value) {
      if (this.audioOnlyMode()) {
        this.audioOnlyMode(false);
      }
      this.enablePosterModeUI_();
      return;
    }
    this.disablePosterModeUI_();
  };
  _proto.addTextTrack = function addTextTrack(kind, label, language) {
    if (this.tech_) {
      return this.tech_.addTextTrack(kind, label, language);
    }
  };
  _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
    if (this.tech_) {
      return this.tech_.addRemoteTextTrack(options, manualCleanup);
    }
  };
  _proto.removeRemoteTextTrack = function removeRemoteTextTrack(obj) {
    if (obj === void 0) {
      obj = {};
    }
    var _obj = obj, track = _obj.track;
    if (!track) {
      track = obj;
    }
    if (this.tech_) {
      return this.tech_.removeRemoteTextTrack(track);
    }
  };
  _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
    return this.techGet_("getVideoPlaybackQuality");
  };
  _proto.videoWidth = function videoWidth() {
    return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  };
  _proto.videoHeight = function videoHeight() {
    return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  };
  _proto.language = function language(code) {
    if (code === void 0) {
      return this.language_;
    }
    if (this.language_ !== String(code).toLowerCase()) {
      this.language_ = String(code).toLowerCase();
      if (isEvented(this)) {
        this.trigger("languagechange");
      }
    }
  };
  _proto.languages = function languages() {
    return mergeOptions$3(Player2.prototype.options_.languages, this.languages_);
  };
  _proto.toJSON = function toJSON() {
    var options = mergeOptions$3(this.options_);
    var tracks = options.tracks;
    options.tracks = [];
    for (var i = 0; i < tracks.length; i++) {
      var track = tracks[i];
      track = mergeOptions$3(track);
      track.player = void 0;
      options.tracks[i] = track;
    }
    return options;
  };
  _proto.createModal = function createModal(content, options) {
    var _this22 = this;
    options = options || {};
    options.content = content || "";
    var modal = new ModalDialog(this, options);
    this.addChild(modal);
    modal.on("dispose", function() {
      _this22.removeChild(modal);
    });
    modal.open();
    return modal;
  };
  _proto.updateCurrentBreakpoint_ = function updateCurrentBreakpoint_() {
    if (!this.responsive()) {
      return;
    }
    var currentBreakpoint = this.currentBreakpoint();
    var currentWidth = this.currentWidth();
    for (var i = 0; i < BREAKPOINT_ORDER.length; i++) {
      var candidateBreakpoint = BREAKPOINT_ORDER[i];
      var maxWidth = this.breakpoints_[candidateBreakpoint];
      if (currentWidth <= maxWidth) {
        if (currentBreakpoint === candidateBreakpoint) {
          return;
        }
        if (currentBreakpoint) {
          this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
        }
        this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
        this.breakpoint_ = candidateBreakpoint;
        break;
      }
    }
  };
  _proto.removeCurrentBreakpoint_ = function removeCurrentBreakpoint_() {
    var className = this.currentBreakpointClass();
    this.breakpoint_ = "";
    if (className) {
      this.removeClass(className);
    }
  };
  _proto.breakpoints = function breakpoints(_breakpoints) {
    if (_breakpoints === void 0) {
      return assign(this.breakpoints_);
    }
    this.breakpoint_ = "";
    this.breakpoints_ = assign({}, DEFAULT_BREAKPOINTS, _breakpoints);
    this.updateCurrentBreakpoint_();
    return assign(this.breakpoints_);
  };
  _proto.responsive = function responsive(value) {
    if (value === void 0) {
      return this.responsive_;
    }
    value = Boolean(value);
    var current = this.responsive_;
    if (value === current) {
      return;
    }
    this.responsive_ = value;
    if (value) {
      this.on("playerresize", this.boundUpdateCurrentBreakpoint_);
      this.updateCurrentBreakpoint_();
    } else {
      this.off("playerresize", this.boundUpdateCurrentBreakpoint_);
      this.removeCurrentBreakpoint_();
    }
    return value;
  };
  _proto.currentBreakpoint = function currentBreakpoint() {
    return this.breakpoint_;
  };
  _proto.currentBreakpointClass = function currentBreakpointClass() {
    return BREAKPOINT_CLASSES[this.breakpoint_] || "";
  };
  _proto.loadMedia = function loadMedia(media, ready) {
    var _this23 = this;
    if (!media || typeof media !== "object") {
      return;
    }
    this.reset();
    this.cache_.media = mergeOptions$3(media);
    var _this$cache_$media = this.cache_.media, artwork = _this$cache_$media.artwork, poster = _this$cache_$media.poster, src = _this$cache_$media.src, textTracks = _this$cache_$media.textTracks;
    if (!artwork && poster) {
      this.cache_.media.artwork = [{
        src: poster,
        type: getMimetype(poster)
      }];
    }
    if (src) {
      this.src(src);
    }
    if (poster) {
      this.poster(poster);
    }
    if (Array.isArray(textTracks)) {
      textTracks.forEach(function(tt) {
        return _this23.addRemoteTextTrack(tt, false);
      });
    }
    this.ready(ready);
  };
  _proto.getMedia = function getMedia() {
    if (!this.cache_.media) {
      var poster = this.poster();
      var src = this.currentSources();
      var textTracks = Array.prototype.map.call(this.remoteTextTracks(), function(tt) {
        return {
          kind: tt.kind,
          label: tt.label,
          language: tt.language,
          src: tt.src
        };
      });
      var media = {
        src,
        textTracks
      };
      if (poster) {
        media.poster = poster;
        media.artwork = [{
          src: media.poster,
          type: getMimetype(media.poster)
        }];
      }
      return media;
    }
    return mergeOptions$3(this.cache_.media);
  };
  Player2.getTagSettings = function getTagSettings(tag) {
    var baseOptions = {
      sources: [],
      tracks: []
    };
    var tagOptions = getAttributes(tag);
    var dataSetup = tagOptions["data-setup"];
    if (hasClass(tag, "vjs-fill")) {
      tagOptions.fill = true;
    }
    if (hasClass(tag, "vjs-fluid")) {
      tagOptions.fluid = true;
    }
    if (dataSetup !== null) {
      var _safeParseTuple = (0, import_tuple.default)(dataSetup || "{}"), err = _safeParseTuple[0], data = _safeParseTuple[1];
      if (err) {
        log$1.error(err);
      }
      assign(tagOptions, data);
    }
    assign(baseOptions, tagOptions);
    if (tag.hasChildNodes()) {
      var children = tag.childNodes;
      for (var i = 0, j = children.length; i < j; i++) {
        var child = children[i];
        var childName = child.nodeName.toLowerCase();
        if (childName === "source") {
          baseOptions.sources.push(getAttributes(child));
        } else if (childName === "track") {
          baseOptions.tracks.push(getAttributes(child));
        }
      }
    }
    return baseOptions;
  };
  _proto.flexNotSupported_ = function flexNotSupported_() {
    var elem = import_document.default.createElement("i");
    return !("flexBasis" in elem.style || "webkitFlexBasis" in elem.style || "mozFlexBasis" in elem.style || "msFlexBasis" in elem.style || // IE10-specific (2012 flex spec), available for completeness
    "msFlexOrder" in elem.style);
  };
  _proto.debug = function debug(enabled) {
    if (enabled === void 0) {
      return this.debugEnabled_;
    }
    if (enabled) {
      this.trigger("debugon");
      this.previousLogLevel_ = this.log.level;
      this.log.level("debug");
      this.debugEnabled_ = true;
    } else {
      this.trigger("debugoff");
      this.log.level(this.previousLogLevel_);
      this.previousLogLevel_ = void 0;
      this.debugEnabled_ = false;
    }
  };
  _proto.playbackRates = function playbackRates(newRates) {
    if (newRates === void 0) {
      return this.cache_.playbackRates;
    }
    if (!Array.isArray(newRates)) {
      return;
    }
    if (!newRates.every(function(rate) {
      return typeof rate === "number";
    })) {
      return;
    }
    this.cache_.playbackRates = newRates;
    this.trigger("playbackrateschange");
  };
  return Player2;
}(Component$1);
ALL.names.forEach(function(name) {
  var props = ALL[name];
  Player.prototype[props.getterName] = function() {
    if (this.tech_) {
      return this.tech_[props.getterName]();
    }
    this[props.privateName] = this[props.privateName] || new props.ListClass();
    return this[props.privateName];
  };
});
Player.prototype.crossorigin = Player.prototype.crossOrigin;
Player.players = {};
var navigator2 = import_window6.default.navigator;
Player.prototype.options_ = {
  // Default order of fallback technology
  techOrder: Tech.defaultTechOrder_,
  html5: {},
  // default inactivity timeout
  inactivityTimeout: 2e3,
  // default playback rates
  playbackRates: [],
  // Add playback rate selection by adding rates
  // 'playbackRates': [0.5, 1, 1.5, 2],
  liveui: false,
  // Included control sets
  children: ["mediaLoader", "posterImage", "textTrackDisplay", "loadingSpinner", "bigPlayButton", "liveTracker", "controlBar", "errorDisplay", "textTrackSettings", "resizeManager"],
  language: navigator2 && (navigator2.languages && navigator2.languages[0] || navigator2.userLanguage || navigator2.language) || "en",
  // locales and their language translations
  languages: {},
  // Default message to show when a video cannot be played.
  notSupportedMessage: "No compatible source was found for this media.",
  normalizeAutoplay: false,
  fullscreen: {
    options: {
      navigationUI: "hide"
    }
  },
  breakpoints: {},
  responsive: false,
  audioOnlyMode: false,
  audioPosterMode: false
};
[
  /**
   * Returns whether or not the player is in the "ended" state.
   *
   * @return {Boolean} True if the player is in the ended state, false if not.
   * @method Player#ended
   */
  "ended",
  /**
   * Returns whether or not the player is in the "seeking" state.
   *
   * @return {Boolean} True if the player is in the seeking state, false if not.
   * @method Player#seeking
   */
  "seeking",
  /**
   * Returns the TimeRanges of the media that are currently available
   * for seeking to.
   *
   * @return {TimeRanges} the seekable intervals of the media timeline
   * @method Player#seekable
   */
  "seekable",
  /**
   * Returns the current state of network activity for the element, from
   * the codes in the list below.
   * - NETWORK_EMPTY (numeric value 0)
   *   The element has not yet been initialised. All attributes are in
   *   their initial states.
   * - NETWORK_IDLE (numeric value 1)
   *   The element's resource selection algorithm is active and has
   *   selected a resource, but it is not actually using the network at
   *   this time.
   * - NETWORK_LOADING (numeric value 2)
   *   The user agent is actively trying to download data.
   * - NETWORK_NO_SOURCE (numeric value 3)
   *   The element's resource selection algorithm is active, but it has
   *   not yet found a resource to use.
   *
   * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
   * @return {number} the current network activity state
   * @method Player#networkState
   */
  "networkState",
  /**
   * Returns a value that expresses the current state of the element
   * with respect to rendering the current playback position, from the
   * codes in the list below.
   * - HAVE_NOTHING (numeric value 0)
   *   No information regarding the media resource is available.
   * - HAVE_METADATA (numeric value 1)
   *   Enough of the resource has been obtained that the duration of the
   *   resource is available.
   * - HAVE_CURRENT_DATA (numeric value 2)
   *   Data for the immediate current playback position is available.
   * - HAVE_FUTURE_DATA (numeric value 3)
   *   Data for the immediate current playback position is available, as
   *   well as enough data for the user agent to advance the current
   *   playback position in the direction of playback.
   * - HAVE_ENOUGH_DATA (numeric value 4)
   *   The user agent estimates that enough data is available for
   *   playback to proceed uninterrupted.
   *
   * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
   * @return {number} the current playback rendering state
   * @method Player#readyState
   */
  "readyState"
].forEach(function(fn) {
  Player.prototype[fn] = function() {
    return this.techGet_(fn);
  };
});
TECH_EVENTS_RETRIGGER.forEach(function(event) {
  Player.prototype["handleTech" + toTitleCase$1(event) + "_"] = function() {
    return this.trigger(event);
  };
});
Component$1.registerComponent("Player", Player);
var BASE_PLUGIN_NAME = "plugin";
var PLUGIN_CACHE_KEY = "activePlugins_";
var pluginStorage = {};
var pluginExists = function pluginExists2(name) {
  return pluginStorage.hasOwnProperty(name);
};
var getPlugin = function getPlugin2(name) {
  return pluginExists(name) ? pluginStorage[name] : void 0;
};
var markPluginAsActive = function markPluginAsActive2(player, name) {
  player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  player[PLUGIN_CACHE_KEY][name] = true;
};
var triggerSetupEvent = function triggerSetupEvent2(player, hash2, before) {
  var eventName = (before ? "before" : "") + "pluginsetup";
  player.trigger(eventName, hash2);
  player.trigger(eventName + ":" + hash2.name, hash2);
};
var createBasicPlugin = function createBasicPlugin2(name, plugin) {
  var basicPluginWrapper = function basicPluginWrapper2() {
    triggerSetupEvent(this, {
      name,
      plugin,
      instance: null
    }, true);
    var instance = plugin.apply(this, arguments);
    markPluginAsActive(this, name);
    triggerSetupEvent(this, {
      name,
      plugin,
      instance
    });
    return instance;
  };
  Object.keys(plugin).forEach(function(prop) {
    basicPluginWrapper[prop] = plugin[prop];
  });
  return basicPluginWrapper;
};
var createPluginFactory = function createPluginFactory2(name, PluginSubClass) {
  PluginSubClass.prototype.name = name;
  return function() {
    triggerSetupEvent(this, {
      name,
      plugin: PluginSubClass,
      instance: null
    }, true);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    var instance = _construct(PluginSubClass, [this].concat(args));
    this[name] = function() {
      return instance;
    };
    triggerSetupEvent(this, instance.getEventHash());
    return instance;
  };
};
var Plugin = /* @__PURE__ */ function() {
  function Plugin3(player) {
    if (this.constructor === Plugin3) {
      throw new Error("Plugin must be sub-classed; not directly instantiated.");
    }
    this.player = player;
    if (!this.log) {
      this.log = this.player.log.createLogger(this.name);
    }
    evented(this);
    delete this.trigger;
    stateful(this, this.constructor.defaultState);
    markPluginAsActive(player, this.name);
    this.dispose = this.dispose.bind(this);
    player.on("dispose", this.dispose);
  }
  var _proto = Plugin3.prototype;
  _proto.version = function version6() {
    return this.constructor.VERSION;
  };
  _proto.getEventHash = function getEventHash(hash2) {
    if (hash2 === void 0) {
      hash2 = {};
    }
    hash2.name = this.name;
    hash2.plugin = this.constructor;
    hash2.instance = this;
    return hash2;
  };
  _proto.trigger = function trigger$12(event, hash2) {
    if (hash2 === void 0) {
      hash2 = {};
    }
    return trigger(this.eventBusEl_, event, this.getEventHash(hash2));
  };
  _proto.handleStateChanged = function handleStateChanged(e) {
  };
  _proto.dispose = function dispose() {
    var name = this.name, player = this.player;
    this.trigger("dispose");
    this.off();
    player.off("dispose", this.dispose);
    player[PLUGIN_CACHE_KEY][name] = false;
    this.player = this.state = null;
    player[name] = createPluginFactory(name, pluginStorage[name]);
  };
  Plugin3.isBasic = function isBasic(plugin) {
    var p = typeof plugin === "string" ? getPlugin(plugin) : plugin;
    return typeof p === "function" && !Plugin3.prototype.isPrototypeOf(p.prototype);
  };
  Plugin3.registerPlugin = function registerPlugin3(name, plugin) {
    if (typeof name !== "string") {
      throw new Error('Illegal plugin name, "' + name + '", must be a string, was ' + typeof name + ".");
    }
    if (pluginExists(name)) {
      log$1.warn('A plugin named "' + name + '" already exists. You may want to avoid re-registering plugins!');
    } else if (Player.prototype.hasOwnProperty(name)) {
      throw new Error('Illegal plugin name, "' + name + '", cannot share a name with an existing player method!');
    }
    if (typeof plugin !== "function") {
      throw new Error('Illegal plugin for "' + name + '", must be a function, was ' + typeof plugin + ".");
    }
    pluginStorage[name] = plugin;
    if (name !== BASE_PLUGIN_NAME) {
      if (Plugin3.isBasic(plugin)) {
        Player.prototype[name] = createBasicPlugin(name, plugin);
      } else {
        Player.prototype[name] = createPluginFactory(name, plugin);
      }
    }
    return plugin;
  };
  Plugin3.deregisterPlugin = function deregisterPlugin(name) {
    if (name === BASE_PLUGIN_NAME) {
      throw new Error("Cannot de-register base plugin.");
    }
    if (pluginExists(name)) {
      delete pluginStorage[name];
      delete Player.prototype[name];
    }
  };
  Plugin3.getPlugins = function getPlugins(names) {
    if (names === void 0) {
      names = Object.keys(pluginStorage);
    }
    var result;
    names.forEach(function(name) {
      var plugin = getPlugin(name);
      if (plugin) {
        result = result || {};
        result[name] = plugin;
      }
    });
    return result;
  };
  Plugin3.getPluginVersion = function getPluginVersion(name) {
    var plugin = getPlugin(name);
    return plugin && plugin.VERSION || "";
  };
  return Plugin3;
}();
Plugin.getPlugin = getPlugin;
Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
Player.prototype.usingPlugin = function(name) {
  return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
};
Player.prototype.hasPlugin = function(name) {
  return !!pluginExists(name);
};
var extend = function extend2(superClass, subClassMethods) {
  if (subClassMethods === void 0) {
    subClassMethods = {};
  }
  var subClass = function subClass2() {
    superClass.apply(this, arguments);
  };
  var methods = {};
  if (typeof subClassMethods === "object") {
    if (subClassMethods.constructor !== Object.prototype.constructor) {
      subClass = subClassMethods.constructor;
    }
    methods = subClassMethods;
  } else if (typeof subClassMethods === "function") {
    subClass = subClassMethods;
  }
  _inherits(subClass, superClass);
  if (superClass) {
    subClass.super_ = superClass;
  }
  for (var name in methods) {
    if (methods.hasOwnProperty(name)) {
      subClass.prototype[name] = methods[name];
    }
  }
  return subClass;
};
var normalizeId = function normalizeId2(id) {
  return id.indexOf("#") === 0 ? id.slice(1) : id;
};
function videojs(id, options, ready) {
  var player = videojs.getPlayer(id);
  if (player) {
    if (options) {
      log$1.warn('Player "' + id + '" is already initialised. Options will not be applied.');
    }
    if (ready) {
      player.ready(ready);
    }
    return player;
  }
  var el = typeof id === "string" ? $("#" + normalizeId(id)) : id;
  if (!isEl(el)) {
    throw new TypeError("The element or ID supplied is not valid. (videojs)");
  }
  if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) {
    log$1.warn("The element supplied is not included in the DOM");
  }
  options = options || {};
  if (options.restoreEl === true) {
    options.restoreEl = (el.parentNode && el.parentNode.hasAttribute("data-vjs-player") ? el.parentNode : el).cloneNode(true);
  }
  hooks("beforesetup").forEach(function(hookFunction) {
    var opts = hookFunction(el, mergeOptions$3(options));
    if (!isObject3(opts) || Array.isArray(opts)) {
      log$1.error("please return an object in beforesetup hooks");
      return;
    }
    options = mergeOptions$3(options, opts);
  });
  var PlayerComponent = Component$1.getComponent("Player");
  player = new PlayerComponent(el, options, ready);
  hooks("setup").forEach(function(hookFunction) {
    return hookFunction(player);
  });
  return player;
}
videojs.hooks_ = hooks_;
videojs.hooks = hooks;
videojs.hook = hook;
videojs.hookOnce = hookOnce;
videojs.removeHook = removeHook;
if (import_window6.default.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  style = $(".vjs-styles-defaults");
  if (!style) {
    style = createStyleElement("vjs-styles-defaults");
    head = $("head");
    if (head) {
      head.insertBefore(style, head.firstChild);
    }
    setTextContent(style, "\n      .video-js {\n        width: 300px;\n        height: 150px;\n      }\n\n      .vjs-fluid:not(.vjs-audio-only-mode) {\n        padding-top: 56.25%\n      }\n    ");
  }
}
var style;
var head;
autoSetupTimeout(1, videojs);
videojs.VERSION = version$5;
videojs.options = Player.prototype.options_;
videojs.getPlayers = function() {
  return Player.players;
};
videojs.getPlayer = function(id) {
  var players = Player.players;
  var tag;
  if (typeof id === "string") {
    var nId = normalizeId(id);
    var player = players[nId];
    if (player) {
      return player;
    }
    tag = $("#" + nId);
  } else {
    tag = id;
  }
  if (isEl(tag)) {
    var _tag = tag, _player = _tag.player, playerId = _tag.playerId;
    if (_player || players[playerId]) {
      return _player || players[playerId];
    }
  }
};
videojs.getAllPlayers = function() {
  return (
    // Disposed players leave a key with a `null` value, so we need to make sure
    // we filter those out.
    Object.keys(Player.players).map(function(k) {
      return Player.players[k];
    }).filter(Boolean)
  );
};
videojs.players = Player.players;
videojs.getComponent = Component$1.getComponent;
videojs.registerComponent = function(name, comp) {
  if (Tech.isTech(comp)) {
    log$1.warn("The " + name + " tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)");
  }
  Component$1.registerComponent.call(Component$1, name, comp);
};
videojs.getTech = Tech.getTech;
videojs.registerTech = Tech.registerTech;
videojs.use = use;
Object.defineProperty(videojs, "middleware", {
  value: {},
  writeable: false,
  enumerable: true
});
Object.defineProperty(videojs.middleware, "TERMINATOR", {
  value: TERMINATOR,
  writeable: false,
  enumerable: true
});
videojs.browser = browser;
videojs.TOUCH_ENABLED = TOUCH_ENABLED;
videojs.extend = extend;
videojs.mergeOptions = mergeOptions$3;
videojs.bind = bind;
videojs.registerPlugin = Plugin.registerPlugin;
videojs.deregisterPlugin = Plugin.deregisterPlugin;
videojs.plugin = function(name, plugin) {
  log$1.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead");
  return Plugin.registerPlugin(name, plugin);
};
videojs.getPlugins = Plugin.getPlugins;
videojs.getPlugin = Plugin.getPlugin;
videojs.getPluginVersion = Plugin.getPluginVersion;
videojs.addLanguage = function(code, data) {
  var _mergeOptions;
  code = ("" + code).toLowerCase();
  videojs.options.languages = mergeOptions$3(videojs.options.languages, (_mergeOptions = {}, _mergeOptions[code] = data, _mergeOptions));
  return videojs.options.languages[code];
};
videojs.log = log$1;
videojs.createLogger = createLogger2;
videojs.createTimeRange = videojs.createTimeRanges = createTimeRanges;
videojs.formatTime = formatTime;
videojs.setFormatTime = setFormatTime;
videojs.resetFormatTime = resetFormatTime;
videojs.parseUrl = parseUrl;
videojs.isCrossOrigin = isCrossOrigin;
videojs.EventTarget = EventTarget$2;
videojs.on = on;
videojs.one = one;
videojs.off = off;
videojs.trigger = trigger;
videojs.xhr = import_xhr.default;
videojs.TextTrack = TextTrack;
videojs.AudioTrack = AudioTrack;
videojs.VideoTrack = VideoTrack;
["isEl", "isTextNode", "createEl", "hasClass", "addClass", "removeClass", "toggleClass", "setAttributes", "getAttributes", "emptyEl", "appendContent", "insertContent"].forEach(function(k) {
  videojs[k] = function() {
    log$1.warn("videojs." + k + "() is deprecated; use videojs.dom." + k + "() instead");
    return Dom[k].apply(null, arguments);
  };
});
videojs.computedStyle = computedStyle;
videojs.dom = Dom;
videojs.url = Url;
videojs.defineLazyProperty = defineLazyProperty;
videojs.addLanguage("en", {
  "Non-Fullscreen": "Exit Fullscreen"
});
var resolveUrl3 = resolve_url_default;
var resolveManifestRedirect = function resolveManifestRedirect2(handleManifestRedirect, url, req) {
  if (handleManifestRedirect && req && req.responseURL && url !== req.responseURL) {
    return req.responseURL;
  }
  return url;
};
var logger2 = function logger3(source) {
  if (videojs.log.debug) {
    return videojs.log.debug.bind(videojs, "VHS:", source + " >");
  }
  return function() {
  };
};
var TIME_FUDGE_FACTOR = 1 / 30;
var SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
var filterRanges = function filterRanges2(timeRanges, predicate) {
  var results = [];
  var i;
  if (timeRanges && timeRanges.length) {
    for (i = 0; i < timeRanges.length; i++) {
      if (predicate(timeRanges.start(i), timeRanges.end(i))) {
        results.push([timeRanges.start(i), timeRanges.end(i)]);
      }
    }
  }
  return videojs.createTimeRanges(results);
};
var findRange = function findRange2(buffered, time) {
  return filterRanges(buffered, function(start2, end) {
    return start2 - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  });
};
var findNextRange = function findNextRange2(timeRanges, time) {
  return filterRanges(timeRanges, function(start2) {
    return start2 - TIME_FUDGE_FACTOR >= time;
  });
};
var findGaps = function findGaps2(buffered) {
  if (buffered.length < 2) {
    return videojs.createTimeRanges();
  }
  var ranges = [];
  for (var i = 1; i < buffered.length; i++) {
    var start2 = buffered.end(i - 1);
    var end = buffered.start(i);
    ranges.push([start2, end]);
  }
  return videojs.createTimeRanges(ranges);
};
var bufferIntersection = function bufferIntersection2(bufferA, bufferB) {
  var start2 = null;
  var end = null;
  var arity = 0;
  var extents = [];
  var ranges = [];
  if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
    return videojs.createTimeRange();
  }
  var count = bufferA.length;
  while (count--) {
    extents.push({
      time: bufferA.start(count),
      type: "start"
    });
    extents.push({
      time: bufferA.end(count),
      type: "end"
    });
  }
  count = bufferB.length;
  while (count--) {
    extents.push({
      time: bufferB.start(count),
      type: "start"
    });
    extents.push({
      time: bufferB.end(count),
      type: "end"
    });
  }
  extents.sort(function(a, b) {
    return a.time - b.time;
  });
  for (count = 0; count < extents.length; count++) {
    if (extents[count].type === "start") {
      arity++;
      if (arity === 2) {
        start2 = extents[count].time;
      }
    } else if (extents[count].type === "end") {
      arity--;
      if (arity === 1) {
        end = extents[count].time;
      }
    }
    if (start2 !== null && end !== null) {
      ranges.push([start2, end]);
      start2 = null;
      end = null;
    }
  }
  return videojs.createTimeRanges(ranges);
};
var printableRange = function printableRange2(range3) {
  var strArr = [];
  if (!range3 || !range3.length) {
    return "";
  }
  for (var i = 0; i < range3.length; i++) {
    strArr.push(range3.start(i) + " => " + range3.end(i));
  }
  return strArr.join(", ");
};
var timeUntilRebuffer = function timeUntilRebuffer2(buffered, currentTime, playbackRate) {
  if (playbackRate === void 0) {
    playbackRate = 1;
  }
  var bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  return (bufferedEnd - currentTime) / playbackRate;
};
var timeRangesToArray = function timeRangesToArray2(timeRanges) {
  var timeRangesList = [];
  for (var i = 0; i < timeRanges.length; i++) {
    timeRangesList.push({
      start: timeRanges.start(i),
      end: timeRanges.end(i)
    });
  }
  return timeRangesList;
};
var isRangeDifferent = function isRangeDifferent2(a, b) {
  if (a === b) {
    return false;
  }
  if (!a && b || !b && a) {
    return true;
  }
  if (a.length !== b.length) {
    return true;
  }
  for (var i = 0; i < a.length; i++) {
    if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
      return true;
    }
  }
  return false;
};
var lastBufferedEnd = function lastBufferedEnd2(a) {
  if (!a || !a.length || !a.end) {
    return;
  }
  return a.end(a.length - 1);
};
var timeAheadOf = function timeAheadOf2(range3, startTime) {
  var time = 0;
  if (!range3 || !range3.length) {
    return time;
  }
  for (var i = 0; i < range3.length; i++) {
    var start2 = range3.start(i);
    var end = range3.end(i);
    if (startTime > end) {
      continue;
    }
    if (startTime > start2 && startTime <= end) {
      time += end - startTime;
      continue;
    }
    time += end - start2;
  }
  return time;
};
var createTimeRange = videojs.createTimeRange;
var segmentDurationWithParts = function segmentDurationWithParts2(playlist, segment) {
  if (!segment.preload) {
    return segment.duration;
  }
  var result = 0;
  (segment.parts || []).forEach(function(p) {
    result += p.duration;
  });
  (segment.preloadHints || []).forEach(function(p) {
    if (p.type === "PART") {
      result += playlist.partTargetDuration;
    }
  });
  return result;
};
var getPartsAndSegments = function getPartsAndSegments2(playlist) {
  return (playlist.segments || []).reduce(function(acc, segment, si) {
    if (segment.parts) {
      segment.parts.forEach(function(part, pi) {
        acc.push({
          duration: part.duration,
          segmentIndex: si,
          partIndex: pi,
          part,
          segment
        });
      });
    } else {
      acc.push({
        duration: segment.duration,
        segmentIndex: si,
        partIndex: null,
        segment,
        part: null
      });
    }
    return acc;
  }, []);
};
var getLastParts = function getLastParts2(media) {
  var lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  return lastSegment && lastSegment.parts || [];
};
var getKnownPartCount = function getKnownPartCount2(_ref) {
  var preloadSegment = _ref.preloadSegment;
  if (!preloadSegment) {
    return;
  }
  var parts = preloadSegment.parts, preloadHints = preloadSegment.preloadHints;
  var partCount = (preloadHints || []).reduce(function(count, hint) {
    return count + (hint.type === "PART" ? 1 : 0);
  }, 0);
  partCount += parts && parts.length ? parts.length : 0;
  return partCount;
};
var liveEdgeDelay = function liveEdgeDelay2(master, media) {
  if (media.endList) {
    return 0;
  }
  if (master && master.suggestedPresentationDelay) {
    return master.suggestedPresentationDelay;
  }
  var hasParts = getLastParts(media).length > 0;
  if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
    return media.serverControl.partHoldBack;
  } else if (hasParts && media.partTargetDuration) {
    return media.partTargetDuration * 3;
  } else if (media.serverControl && media.serverControl.holdBack) {
    return media.serverControl.holdBack;
  } else if (media.targetDuration) {
    return media.targetDuration * 3;
  }
  return 0;
};
var backwardDuration = function backwardDuration2(playlist, endSequence) {
  var result = 0;
  var i = endSequence - playlist.mediaSequence;
  var segment = playlist.segments[i];
  if (segment) {
    if (typeof segment.start !== "undefined") {
      return {
        result: segment.start,
        precise: true
      };
    }
    if (typeof segment.end !== "undefined") {
      return {
        result: segment.end - segment.duration,
        precise: true
      };
    }
  }
  while (i--) {
    segment = playlist.segments[i];
    if (typeof segment.end !== "undefined") {
      return {
        result: result + segment.end,
        precise: true
      };
    }
    result += segmentDurationWithParts(playlist, segment);
    if (typeof segment.start !== "undefined") {
      return {
        result: result + segment.start,
        precise: true
      };
    }
  }
  return {
    result,
    precise: false
  };
};
var forwardDuration = function forwardDuration2(playlist, endSequence) {
  var result = 0;
  var segment;
  var i = endSequence - playlist.mediaSequence;
  for (; i < playlist.segments.length; i++) {
    segment = playlist.segments[i];
    if (typeof segment.start !== "undefined") {
      return {
        result: segment.start - result,
        precise: true
      };
    }
    result += segmentDurationWithParts(playlist, segment);
    if (typeof segment.end !== "undefined") {
      return {
        result: segment.end - result,
        precise: true
      };
    }
  }
  return {
    result: -1,
    precise: false
  };
};
var intervalDuration = function intervalDuration2(playlist, endSequence, expired) {
  if (typeof endSequence === "undefined") {
    endSequence = playlist.mediaSequence + playlist.segments.length;
  }
  if (endSequence < playlist.mediaSequence) {
    return 0;
  }
  var backward = backwardDuration(playlist, endSequence);
  if (backward.precise) {
    return backward.result;
  }
  var forward = forwardDuration(playlist, endSequence);
  if (forward.precise) {
    return forward.result;
  }
  return backward.result + expired;
};
var duration2 = function duration3(playlist, endSequence, expired) {
  if (!playlist) {
    return 0;
  }
  if (typeof expired !== "number") {
    expired = 0;
  }
  if (typeof endSequence === "undefined") {
    if (playlist.totalDuration) {
      return playlist.totalDuration;
    }
    if (!playlist.endList) {
      return import_window6.default.Infinity;
    }
  }
  return intervalDuration(playlist, endSequence, expired);
};
var sumDurations = function sumDurations2(_ref2) {
  var defaultDuration = _ref2.defaultDuration, durationList = _ref2.durationList, startIndex = _ref2.startIndex, endIndex = _ref2.endIndex;
  var durations = 0;
  if (startIndex > endIndex) {
    var _ref3 = [endIndex, startIndex];
    startIndex = _ref3[0];
    endIndex = _ref3[1];
  }
  if (startIndex < 0) {
    for (var i = startIndex; i < Math.min(0, endIndex); i++) {
      durations += defaultDuration;
    }
    startIndex = 0;
  }
  for (var _i = startIndex; _i < endIndex; _i++) {
    durations += durationList[_i].duration;
  }
  return durations;
};
var playlistEnd = function playlistEnd2(playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  if (!playlist || !playlist.segments) {
    return null;
  }
  if (playlist.endList) {
    return duration2(playlist);
  }
  if (expired === null) {
    return null;
  }
  expired = expired || 0;
  var lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  if (useSafeLiveEnd) {
    liveEdgePadding = typeof liveEdgePadding === "number" ? liveEdgePadding : liveEdgeDelay(null, playlist);
    lastSegmentEndTime -= liveEdgePadding;
  }
  return Math.max(0, lastSegmentEndTime);
};
var seekable = function seekable2(playlist, expired, liveEdgePadding) {
  var useSafeLiveEnd = true;
  var seekableStart = expired || 0;
  var seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  if (seekableEnd === null) {
    return createTimeRange();
  }
  return createTimeRange(seekableStart, seekableEnd);
};
var getMediaInfoForTime = function getMediaInfoForTime2(_ref4) {
  var playlist = _ref4.playlist, currentTime = _ref4.currentTime, startingSegmentIndex = _ref4.startingSegmentIndex, startingPartIndex = _ref4.startingPartIndex, startTime = _ref4.startTime, experimentalExactManifestTimings = _ref4.experimentalExactManifestTimings;
  var time = currentTime - startTime;
  var partsAndSegments = getPartsAndSegments(playlist);
  var startIndex = 0;
  for (var i = 0; i < partsAndSegments.length; i++) {
    var partAndSegment = partsAndSegments[i];
    if (startingSegmentIndex !== partAndSegment.segmentIndex) {
      continue;
    }
    if (typeof startingPartIndex === "number" && typeof partAndSegment.partIndex === "number" && startingPartIndex !== partAndSegment.partIndex) {
      continue;
    }
    startIndex = i;
    break;
  }
  if (time < 0) {
    if (startIndex > 0) {
      for (var _i2 = startIndex - 1; _i2 >= 0; _i2--) {
        var _partAndSegment = partsAndSegments[_i2];
        time += _partAndSegment.duration;
        if (experimentalExactManifestTimings) {
          if (time < 0) {
            continue;
          }
        } else if (time + TIME_FUDGE_FACTOR <= 0) {
          continue;
        }
        return {
          partIndex: _partAndSegment.partIndex,
          segmentIndex: _partAndSegment.segmentIndex,
          startTime: startTime - sumDurations({
            defaultDuration: playlist.targetDuration,
            durationList: partsAndSegments,
            startIndex,
            endIndex: _i2
          })
        };
      }
    }
    return {
      partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
      segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
      startTime: currentTime
    };
  }
  if (startIndex < 0) {
    for (var _i3 = startIndex; _i3 < 0; _i3++) {
      time -= playlist.targetDuration;
      if (time < 0) {
        return {
          partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
          segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
          startTime: currentTime
        };
      }
    }
    startIndex = 0;
  }
  for (var _i4 = startIndex; _i4 < partsAndSegments.length; _i4++) {
    var _partAndSegment2 = partsAndSegments[_i4];
    time -= _partAndSegment2.duration;
    if (experimentalExactManifestTimings) {
      if (time > 0) {
        continue;
      }
    } else if (time - TIME_FUDGE_FACTOR >= 0) {
      continue;
    }
    return {
      partIndex: _partAndSegment2.partIndex,
      segmentIndex: _partAndSegment2.segmentIndex,
      startTime: startTime + sumDurations({
        defaultDuration: playlist.targetDuration,
        durationList: partsAndSegments,
        startIndex,
        endIndex: _i4
      })
    };
  }
  return {
    segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
    partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
    startTime: currentTime
  };
};
var isBlacklisted = function isBlacklisted2(playlist) {
  return playlist.excludeUntil && playlist.excludeUntil > Date.now();
};
var isIncompatible = function isIncompatible2(playlist) {
  return playlist.excludeUntil && playlist.excludeUntil === Infinity;
};
var isEnabled = function isEnabled2(playlist) {
  var blacklisted = isBlacklisted(playlist);
  return !playlist.disabled && !blacklisted;
};
var isDisabled = function isDisabled2(playlist) {
  return playlist.disabled;
};
var isAes = function isAes2(media) {
  for (var i = 0; i < media.segments.length; i++) {
    if (media.segments[i].key) {
      return true;
    }
  }
  return false;
};
var hasAttribute = function hasAttribute2(attr, playlist) {
  return playlist.attributes && playlist.attributes[attr];
};
var estimateSegmentRequestTime = function estimateSegmentRequestTime2(segmentDuration, bandwidth2, playlist, bytesReceived) {
  if (bytesReceived === void 0) {
    bytesReceived = 0;
  }
  if (!hasAttribute("BANDWIDTH", playlist)) {
    return NaN;
  }
  var size = segmentDuration * playlist.attributes.BANDWIDTH;
  return (size - bytesReceived * 8) / bandwidth2;
};
var isLowestEnabledRendition = function isLowestEnabledRendition2(master, media) {
  if (master.playlists.length === 1) {
    return true;
  }
  var currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  return master.playlists.filter(function(playlist) {
    if (!isEnabled(playlist)) {
      return false;
    }
    return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  }).length === 0;
};
var playlistMatch = function playlistMatch2(a, b) {
  if (!a && !b || !a && b || a && !b) {
    return false;
  }
  if (a === b) {
    return true;
  }
  if (a.id && b.id && a.id === b.id) {
    return true;
  }
  if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
    return true;
  }
  if (a.uri && b.uri && a.uri === b.uri) {
    return true;
  }
  return false;
};
var someAudioVariant = function someAudioVariant2(master, callback2) {
  var AUDIO5 = master && master.mediaGroups && master.mediaGroups.AUDIO || {};
  var found = false;
  for (var groupName in AUDIO5) {
    for (var label in AUDIO5[groupName]) {
      found = callback2(AUDIO5[groupName][label]);
      if (found) {
        break;
      }
    }
    if (found) {
      break;
    }
  }
  return !!found;
};
var isAudioOnly = function isAudioOnly2(master) {
  if (!master || !master.playlists || !master.playlists.length) {
    var found = someAudioVariant(master, function(variant) {
      return variant.playlists && variant.playlists.length || variant.uri;
    });
    return found;
  }
  var _loop = function _loop2(i2) {
    var playlist = master.playlists[i2];
    var CODECS = playlist.attributes && playlist.attributes.CODECS;
    if (CODECS && CODECS.split(",").every(function(c) {
      return isAudioCodec(c);
    })) {
      return "continue";
    }
    var found2 = someAudioVariant(master, function(variant) {
      return playlistMatch(playlist, variant);
    });
    if (found2) {
      return "continue";
    }
    return {
      v: false
    };
  };
  for (var i = 0; i < master.playlists.length; i++) {
    var _ret = _loop(i);
    if (_ret === "continue") continue;
    if (typeof _ret === "object") return _ret.v;
  }
  return true;
};
var Playlist = {
  liveEdgeDelay,
  duration: duration2,
  seekable,
  getMediaInfoForTime,
  isEnabled,
  isDisabled,
  isBlacklisted,
  isIncompatible,
  playlistEnd,
  isAes,
  hasAttribute,
  estimateSegmentRequestTime,
  isLowestEnabledRendition,
  isAudioOnly,
  playlistMatch,
  segmentDurationWithParts
};
var log = videojs.log;
var createPlaylistID = function createPlaylistID2(index, uri) {
  return index + "-" + uri;
};
var parseManifest = function parseManifest2(_ref) {
  var onwarn = _ref.onwarn, oninfo = _ref.oninfo, manifestString = _ref.manifestString, _ref$customTagParsers = _ref.customTagParsers, customTagParsers = _ref$customTagParsers === void 0 ? [] : _ref$customTagParsers, _ref$customTagMappers = _ref.customTagMappers, customTagMappers = _ref$customTagMappers === void 0 ? [] : _ref$customTagMappers, experimentalLLHLS = _ref.experimentalLLHLS;
  var parser6 = new Parser();
  if (onwarn) {
    parser6.on("warn", onwarn);
  }
  if (oninfo) {
    parser6.on("info", oninfo);
  }
  customTagParsers.forEach(function(customParser) {
    return parser6.addParser(customParser);
  });
  customTagMappers.forEach(function(mapper) {
    return parser6.addTagMapper(mapper);
  });
  parser6.push(manifestString);
  parser6.end();
  var manifest = parser6.manifest;
  if (!experimentalLLHLS) {
    ["preloadSegment", "skip", "serverControl", "renditionReports", "partInf", "partTargetDuration"].forEach(function(k) {
      if (manifest.hasOwnProperty(k)) {
        delete manifest[k];
      }
    });
    if (manifest.segments) {
      manifest.segments.forEach(function(segment) {
        ["parts", "preloadHints"].forEach(function(k) {
          if (segment.hasOwnProperty(k)) {
            delete segment[k];
          }
        });
      });
    }
  }
  if (!manifest.targetDuration) {
    var targetDuration = 10;
    if (manifest.segments && manifest.segments.length) {
      targetDuration = manifest.segments.reduce(function(acc, s) {
        return Math.max(acc, s.duration);
      }, 0);
    }
    if (onwarn) {
      onwarn("manifest has no targetDuration defaulting to " + targetDuration);
    }
    manifest.targetDuration = targetDuration;
  }
  var parts = getLastParts(manifest);
  if (parts.length && !manifest.partTargetDuration) {
    var partTargetDuration = parts.reduce(function(acc, p) {
      return Math.max(acc, p.duration);
    }, 0);
    if (onwarn) {
      onwarn("manifest has no partTargetDuration defaulting to " + partTargetDuration);
      log.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.");
    }
    manifest.partTargetDuration = partTargetDuration;
  }
  return manifest;
};
var forEachMediaGroup3 = function forEachMediaGroup4(master, callback2) {
  if (!master.mediaGroups) {
    return;
  }
  ["AUDIO", "SUBTITLES"].forEach(function(mediaType) {
    if (!master.mediaGroups[mediaType]) {
      return;
    }
    for (var groupKey in master.mediaGroups[mediaType]) {
      for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
        var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
        callback2(mediaProperties, mediaType, groupKey, labelKey);
      }
    }
  });
};
var setupMediaPlaylist = function setupMediaPlaylist2(_ref2) {
  var playlist = _ref2.playlist, uri = _ref2.uri, id = _ref2.id;
  playlist.id = id;
  playlist.playlistErrors_ = 0;
  if (uri) {
    playlist.uri = uri;
  }
  playlist.attributes = playlist.attributes || {};
};
var setupMediaPlaylists = function setupMediaPlaylists2(master) {
  var i = master.playlists.length;
  while (i--) {
    var playlist = master.playlists[i];
    setupMediaPlaylist({
      playlist,
      id: createPlaylistID(i, playlist.uri)
    });
    playlist.resolvedUri = resolveUrl3(master.uri, playlist.uri);
    master.playlists[playlist.id] = playlist;
    master.playlists[playlist.uri] = playlist;
    if (!playlist.attributes.BANDWIDTH) {
      log.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.");
    }
  }
};
var resolveMediaGroupUris = function resolveMediaGroupUris2(master) {
  forEachMediaGroup3(master, function(properties) {
    if (properties.uri) {
      properties.resolvedUri = resolveUrl3(master.uri, properties.uri);
    }
  });
};
var masterForMedia = function masterForMedia2(media, uri) {
  var id = createPlaylistID(0, uri);
  var master = {
    mediaGroups: {
      "AUDIO": {},
      "VIDEO": {},
      "CLOSED-CAPTIONS": {},
      "SUBTITLES": {}
    },
    uri: import_window6.default.location.href,
    resolvedUri: import_window6.default.location.href,
    playlists: [{
      uri,
      id,
      resolvedUri: uri,
      // m3u8-parser does not attach an attributes property to media playlists so make
      // sure that the property is attached to avoid undefined reference errors
      attributes: {}
    }]
  };
  master.playlists[id] = master.playlists[0];
  master.playlists[uri] = master.playlists[0];
  return master;
};
var addPropertiesToMaster = function addPropertiesToMaster2(master, uri) {
  master.uri = uri;
  for (var i = 0; i < master.playlists.length; i++) {
    if (!master.playlists[i].uri) {
      var phonyUri = "placeholder-uri-" + i;
      master.playlists[i].uri = phonyUri;
    }
  }
  var audioOnlyMaster = isAudioOnly(master);
  forEachMediaGroup3(master, function(properties, mediaType, groupKey, labelKey) {
    var groupId = "placeholder-uri-" + mediaType + "-" + groupKey + "-" + labelKey;
    if (!properties.playlists || !properties.playlists.length) {
      if (audioOnlyMaster && mediaType === "AUDIO" && !properties.uri) {
        for (var _i = 0; _i < master.playlists.length; _i++) {
          var p = master.playlists[_i];
          if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
            return;
          }
        }
      }
      properties.playlists = [_extends2({}, properties)];
    }
    properties.playlists.forEach(function(p2, i2) {
      var id = createPlaylistID(i2, groupId);
      if (p2.uri) {
        p2.resolvedUri = p2.resolvedUri || resolveUrl3(master.uri, p2.uri);
      } else {
        p2.uri = i2 === 0 ? groupId : id;
        p2.resolvedUri = p2.uri;
      }
      p2.id = p2.id || id;
      p2.attributes = p2.attributes || {};
      master.playlists[p2.id] = p2;
      master.playlists[p2.uri] = p2;
    });
  });
  setupMediaPlaylists(master);
  resolveMediaGroupUris(master);
};
var mergeOptions$2 = videojs.mergeOptions;
var EventTarget$1 = videojs.EventTarget;
var addLLHLSQueryDirectives = function addLLHLSQueryDirectives2(uri, media) {
  if (media.endList || !media.serverControl) {
    return uri;
  }
  var parameters = {};
  if (media.serverControl.canBlockReload) {
    var preloadSegment = media.preloadSegment;
    var nextMSN = media.mediaSequence + media.segments.length;
    if (preloadSegment) {
      var parts = preloadSegment.parts || [];
      var nextPart = getKnownPartCount(media) - 1;
      if (nextPart > -1 && nextPart !== parts.length - 1) {
        parameters._HLS_part = nextPart;
      }
      if (nextPart > -1 || parts.length) {
        nextMSN--;
      }
    }
    parameters._HLS_msn = nextMSN;
  }
  if (media.serverControl && media.serverControl.canSkipUntil) {
    parameters._HLS_skip = media.serverControl.canSkipDateranges ? "v2" : "YES";
  }
  if (Object.keys(parameters).length) {
    var parsedUri = new import_window6.default.URL(uri);
    ["_HLS_skip", "_HLS_msn", "_HLS_part"].forEach(function(name) {
      if (!parameters.hasOwnProperty(name)) {
        return;
      }
      parsedUri.searchParams.set(name, parameters[name]);
    });
    uri = parsedUri.toString();
  }
  return uri;
};
var updateSegment = function updateSegment2(a, b) {
  if (!a) {
    return b;
  }
  var result = mergeOptions$2(a, b);
  if (a.preloadHints && !b.preloadHints) {
    delete result.preloadHints;
  }
  if (a.parts && !b.parts) {
    delete result.parts;
  } else if (a.parts && b.parts) {
    for (var i = 0; i < b.parts.length; i++) {
      if (a.parts && a.parts[i]) {
        result.parts[i] = mergeOptions$2(a.parts[i], b.parts[i]);
      }
    }
  }
  if (!a.skipped && b.skipped) {
    result.skipped = false;
  }
  if (a.preload && !b.preload) {
    result.preload = false;
  }
  return result;
};
var updateSegments = function updateSegments2(original, update, offset) {
  var oldSegments = original.slice();
  var newSegments = update.slice();
  offset = offset || 0;
  var result = [];
  var currentMap;
  for (var newIndex = 0; newIndex < newSegments.length; newIndex++) {
    var oldSegment = oldSegments[newIndex + offset];
    var newSegment = newSegments[newIndex];
    if (oldSegment) {
      currentMap = oldSegment.map || currentMap;
      result.push(updateSegment(oldSegment, newSegment));
    } else {
      if (currentMap && !newSegment.map) {
        newSegment.map = currentMap;
      }
      result.push(newSegment);
    }
  }
  return result;
};
var resolveSegmentUris = function resolveSegmentUris2(segment, baseUri) {
  if (!segment.resolvedUri && segment.uri) {
    segment.resolvedUri = resolveUrl3(baseUri, segment.uri);
  }
  if (segment.key && !segment.key.resolvedUri) {
    segment.key.resolvedUri = resolveUrl3(baseUri, segment.key.uri);
  }
  if (segment.map && !segment.map.resolvedUri) {
    segment.map.resolvedUri = resolveUrl3(baseUri, segment.map.uri);
  }
  if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
    segment.map.key.resolvedUri = resolveUrl3(baseUri, segment.map.key.uri);
  }
  if (segment.parts && segment.parts.length) {
    segment.parts.forEach(function(p) {
      if (p.resolvedUri) {
        return;
      }
      p.resolvedUri = resolveUrl3(baseUri, p.uri);
    });
  }
  if (segment.preloadHints && segment.preloadHints.length) {
    segment.preloadHints.forEach(function(p) {
      if (p.resolvedUri) {
        return;
      }
      p.resolvedUri = resolveUrl3(baseUri, p.uri);
    });
  }
};
var getAllSegments = function getAllSegments2(media) {
  var segments = media.segments || [];
  var preloadSegment = media.preloadSegment;
  if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
    if (preloadSegment.preloadHints) {
      for (var i = 0; i < preloadSegment.preloadHints.length; i++) {
        if (preloadSegment.preloadHints[i].type === "MAP") {
          return segments;
        }
      }
    }
    preloadSegment.duration = media.targetDuration;
    preloadSegment.preload = true;
    segments.push(preloadSegment);
  }
  return segments;
};
var isPlaylistUnchanged = function isPlaylistUnchanged2(a, b) {
  return a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endList === b.endList && a.mediaSequence === b.mediaSequence && a.preloadSegment === b.preloadSegment;
};
var updateMaster$1 = function updateMaster(master, newMedia, unchangedCheck) {
  if (unchangedCheck === void 0) {
    unchangedCheck = isPlaylistUnchanged;
  }
  var result = mergeOptions$2(master, {});
  var oldMedia = result.playlists[newMedia.id];
  if (!oldMedia) {
    return null;
  }
  if (unchangedCheck(oldMedia, newMedia)) {
    return null;
  }
  newMedia.segments = getAllSegments(newMedia);
  var mergedPlaylist = mergeOptions$2(oldMedia, newMedia);
  if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
    delete mergedPlaylist.preloadSegment;
  }
  if (oldMedia.segments) {
    if (newMedia.skip) {
      newMedia.segments = newMedia.segments || [];
      for (var i = 0; i < newMedia.skip.skippedSegments; i++) {
        newMedia.segments.unshift({
          skipped: true
        });
      }
    }
    mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  }
  mergedPlaylist.segments.forEach(function(segment) {
    resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  });
  for (var _i = 0; _i < result.playlists.length; _i++) {
    if (result.playlists[_i].id === newMedia.id) {
      result.playlists[_i] = mergedPlaylist;
    }
  }
  result.playlists[newMedia.id] = mergedPlaylist;
  result.playlists[newMedia.uri] = mergedPlaylist;
  forEachMediaGroup3(master, function(properties, mediaType, groupKey, labelKey) {
    if (!properties.playlists) {
      return;
    }
    for (var _i2 = 0; _i2 < properties.playlists.length; _i2++) {
      if (newMedia.id === properties.playlists[_i2].id) {
        properties.playlists[_i2] = mergedPlaylist;
      }
    }
  });
  return result;
};
var refreshDelay = function refreshDelay2(media, update) {
  var segments = media.segments || [];
  var lastSegment = segments[segments.length - 1];
  var lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  var lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  if (update && lastDuration) {
    return lastDuration * 1e3;
  }
  return (media.partTargetDuration || media.targetDuration || 10) * 500;
};
var PlaylistLoader2 = /* @__PURE__ */ function(_EventTarget) {
  _inheritsLoose(PlaylistLoader3, _EventTarget);
  function PlaylistLoader3(src, vhs, options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    _this = _EventTarget.call(this) || this;
    if (!src) {
      throw new Error("A non-empty playlist URL or object is required");
    }
    _this.logger_ = logger2("PlaylistLoader");
    var _options = options, _options$withCredenti = _options.withCredentials, withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti, _options$handleManife = _options.handleManifestRedirects, handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
    _this.src = src;
    _this.vhs_ = vhs;
    _this.withCredentials = withCredentials;
    _this.handleManifestRedirects = handleManifestRedirects;
    var vhsOptions = vhs.options_;
    _this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
    _this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
    _this.experimentalLLHLS = vhsOptions && vhsOptions.experimentalLLHLS || false;
    if (videojs.browser.IE_VERSION) {
      _this.experimentalLLHLS = false;
    }
    _this.state = "HAVE_NOTHING";
    _this.handleMediaupdatetimeout_ = _this.handleMediaupdatetimeout_.bind(_assertThisInitialized(_this));
    _this.on("mediaupdatetimeout", _this.handleMediaupdatetimeout_);
    return _this;
  }
  var _proto = PlaylistLoader3.prototype;
  _proto.handleMediaupdatetimeout_ = function handleMediaupdatetimeout_() {
    var _this2 = this;
    if (this.state !== "HAVE_METADATA") {
      return;
    }
    var media = this.media();
    var uri = resolveUrl3(this.master.uri, media.uri);
    if (this.experimentalLLHLS) {
      uri = addLLHLSQueryDirectives(uri, media);
    }
    this.state = "HAVE_CURRENT_METADATA";
    this.request = this.vhs_.xhr({
      uri,
      withCredentials: this.withCredentials
    }, function(error, req) {
      if (!_this2.request) {
        return;
      }
      if (error) {
        return _this2.playlistRequestError(_this2.request, _this2.media(), "HAVE_METADATA");
      }
      _this2.haveMetadata({
        playlistString: _this2.request.responseText,
        url: _this2.media().uri,
        id: _this2.media().id
      });
    });
  };
  _proto.playlistRequestError = function playlistRequestError(xhr, playlist, startingState) {
    var uri = playlist.uri, id = playlist.id;
    this.request = null;
    if (startingState) {
      this.state = startingState;
    }
    this.error = {
      playlist: this.master.playlists[id],
      status: xhr.status,
      message: "HLS playlist request error at URL: " + uri + ".",
      responseText: xhr.responseText,
      code: xhr.status >= 500 ? 4 : 2
    };
    this.trigger("error");
  };
  _proto.parseManifest_ = function parseManifest_(_ref) {
    var _this3 = this;
    var url = _ref.url, manifestString = _ref.manifestString;
    return parseManifest({
      onwarn: function onwarn(_ref2) {
        var message = _ref2.message;
        return _this3.logger_("m3u8-parser warn for " + url + ": " + message);
      },
      oninfo: function oninfo(_ref3) {
        var message = _ref3.message;
        return _this3.logger_("m3u8-parser info for " + url + ": " + message);
      },
      manifestString,
      customTagParsers: this.customTagParsers,
      customTagMappers: this.customTagMappers,
      experimentalLLHLS: this.experimentalLLHLS
    });
  };
  _proto.haveMetadata = function haveMetadata(_ref4) {
    var playlistString = _ref4.playlistString, playlistObject = _ref4.playlistObject, url = _ref4.url, id = _ref4.id;
    this.request = null;
    this.state = "HAVE_METADATA";
    var playlist = playlistObject || this.parseManifest_({
      url,
      manifestString: playlistString
    });
    playlist.lastRequest = Date.now();
    setupMediaPlaylist({
      playlist,
      uri: url,
      id
    });
    var update = updateMaster$1(this.master, playlist);
    this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
    this.pendingMedia_ = null;
    if (update) {
      this.master = update;
      this.media_ = this.master.playlists[id];
    } else {
      this.trigger("playlistunchanged");
    }
    this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
    this.trigger("loadedplaylist");
  };
  _proto.dispose = function dispose() {
    this.trigger("dispose");
    this.stopRequest();
    import_window6.default.clearTimeout(this.mediaUpdateTimeout);
    import_window6.default.clearTimeout(this.finalRenditionTimeout);
    this.off();
  };
  _proto.stopRequest = function stopRequest() {
    if (this.request) {
      var oldRequest = this.request;
      this.request = null;
      oldRequest.onreadystatechange = null;
      oldRequest.abort();
    }
  };
  _proto.media = function media(playlist, shouldDelay) {
    var _this4 = this;
    if (!playlist) {
      return this.media_;
    }
    if (this.state === "HAVE_NOTHING") {
      throw new Error("Cannot switch media playlist from " + this.state);
    }
    if (typeof playlist === "string") {
      if (!this.master.playlists[playlist]) {
        throw new Error("Unknown playlist URI: " + playlist);
      }
      playlist = this.master.playlists[playlist];
    }
    import_window6.default.clearTimeout(this.finalRenditionTimeout);
    if (shouldDelay) {
      var delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1e3 || 5 * 1e3;
      this.finalRenditionTimeout = import_window6.default.setTimeout(this.media.bind(this, playlist, false), delay);
      return;
    }
    var startingState = this.state;
    var mediaChange = !this.media_ || playlist.id !== this.media_.id;
    var masterPlaylistRef = this.master.playlists[playlist.id];
    if (masterPlaylistRef && masterPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
    // media playlist or, for the case of demuxed audio, a resolved audio media group)
    playlist.endList && playlist.segments.length) {
      if (this.request) {
        this.request.onreadystatechange = null;
        this.request.abort();
        this.request = null;
      }
      this.state = "HAVE_METADATA";
      this.media_ = playlist;
      if (mediaChange) {
        this.trigger("mediachanging");
        if (startingState === "HAVE_MASTER") {
          this.trigger("loadedmetadata");
        } else {
          this.trigger("mediachange");
        }
      }
      return;
    }
    this.updateMediaUpdateTimeout_(refreshDelay(playlist, true));
    if (!mediaChange) {
      return;
    }
    this.state = "SWITCHING_MEDIA";
    if (this.request) {
      if (playlist.resolvedUri === this.request.url) {
        return;
      }
      this.request.onreadystatechange = null;
      this.request.abort();
      this.request = null;
    }
    if (this.media_) {
      this.trigger("mediachanging");
    }
    this.pendingMedia_ = playlist;
    this.request = this.vhs_.xhr({
      uri: playlist.resolvedUri,
      withCredentials: this.withCredentials
    }, function(error, req) {
      if (!_this4.request) {
        return;
      }
      playlist.lastRequest = Date.now();
      playlist.resolvedUri = resolveManifestRedirect(_this4.handleManifestRedirects, playlist.resolvedUri, req);
      if (error) {
        return _this4.playlistRequestError(_this4.request, playlist, startingState);
      }
      _this4.haveMetadata({
        playlistString: req.responseText,
        url: playlist.uri,
        id: playlist.id
      });
      if (startingState === "HAVE_MASTER") {
        _this4.trigger("loadedmetadata");
      } else {
        _this4.trigger("mediachange");
      }
    });
  };
  _proto.pause = function pause() {
    if (this.mediaUpdateTimeout) {
      import_window6.default.clearTimeout(this.mediaUpdateTimeout);
      this.mediaUpdateTimeout = null;
    }
    this.stopRequest();
    if (this.state === "HAVE_NOTHING") {
      this.started = false;
    }
    if (this.state === "SWITCHING_MEDIA") {
      if (this.media_) {
        this.state = "HAVE_METADATA";
      } else {
        this.state = "HAVE_MASTER";
      }
    } else if (this.state === "HAVE_CURRENT_METADATA") {
      this.state = "HAVE_METADATA";
    }
  };
  _proto.load = function load(shouldDelay) {
    var _this5 = this;
    if (this.mediaUpdateTimeout) {
      import_window6.default.clearTimeout(this.mediaUpdateTimeout);
      this.mediaUpdateTimeout = null;
    }
    var media = this.media();
    if (shouldDelay) {
      var delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1e3 : 5 * 1e3;
      this.mediaUpdateTimeout = import_window6.default.setTimeout(function() {
        _this5.mediaUpdateTimeout = null;
        _this5.load();
      }, delay);
      return;
    }
    if (!this.started) {
      this.start();
      return;
    }
    if (media && !media.endList) {
      this.trigger("mediaupdatetimeout");
    } else {
      this.trigger("loadedplaylist");
    }
  };
  _proto.updateMediaUpdateTimeout_ = function updateMediaUpdateTimeout_(delay) {
    var _this6 = this;
    if (this.mediaUpdateTimeout) {
      import_window6.default.clearTimeout(this.mediaUpdateTimeout);
      this.mediaUpdateTimeout = null;
    }
    if (!this.media() || this.media().endList) {
      return;
    }
    this.mediaUpdateTimeout = import_window6.default.setTimeout(function() {
      _this6.mediaUpdateTimeout = null;
      _this6.trigger("mediaupdatetimeout");
      _this6.updateMediaUpdateTimeout_(delay);
    }, delay);
  };
  _proto.start = function start2() {
    var _this7 = this;
    this.started = true;
    if (typeof this.src === "object") {
      if (!this.src.uri) {
        this.src.uri = import_window6.default.location.href;
      }
      this.src.resolvedUri = this.src.uri;
      setTimeout(function() {
        _this7.setupInitialPlaylist(_this7.src);
      }, 0);
      return;
    }
    this.request = this.vhs_.xhr({
      uri: this.src,
      withCredentials: this.withCredentials
    }, function(error, req) {
      if (!_this7.request) {
        return;
      }
      _this7.request = null;
      if (error) {
        _this7.error = {
          status: req.status,
          message: "HLS playlist request error at URL: " + _this7.src + ".",
          responseText: req.responseText,
          // MEDIA_ERR_NETWORK
          code: 2
        };
        if (_this7.state === "HAVE_NOTHING") {
          _this7.started = false;
        }
        return _this7.trigger("error");
      }
      _this7.src = resolveManifestRedirect(_this7.handleManifestRedirects, _this7.src, req);
      var manifest = _this7.parseManifest_({
        manifestString: req.responseText,
        url: _this7.src
      });
      _this7.setupInitialPlaylist(manifest);
    });
  };
  _proto.srcUri = function srcUri() {
    return typeof this.src === "string" ? this.src : this.src.uri;
  };
  _proto.setupInitialPlaylist = function setupInitialPlaylist(manifest) {
    this.state = "HAVE_MASTER";
    if (manifest.playlists) {
      this.master = manifest;
      addPropertiesToMaster(this.master, this.srcUri());
      manifest.playlists.forEach(function(playlist) {
        playlist.segments = getAllSegments(playlist);
        playlist.segments.forEach(function(segment) {
          resolveSegmentUris(segment, playlist.resolvedUri);
        });
      });
      this.trigger("loadedplaylist");
      if (!this.request) {
        this.media(this.master.playlists[0]);
      }
      return;
    }
    var uri = this.srcUri() || import_window6.default.location.href;
    this.master = masterForMedia(manifest, uri);
    this.haveMetadata({
      playlistObject: manifest,
      url: uri,
      id: this.master.playlists[0].id
    });
    this.trigger("loadedmetadata");
  };
  return PlaylistLoader3;
}(EventTarget$1);
var videojsXHR = videojs.xhr;
var mergeOptions$1 = videojs.mergeOptions;
var callbackWrapper = function callbackWrapper2(request, error, response, callback2) {
  var reqResponse = request.responseType === "arraybuffer" ? request.response : request.responseText;
  if (!error && reqResponse) {
    request.responseTime = Date.now();
    request.roundTripTime = request.responseTime - request.requestTime;
    request.bytesReceived = reqResponse.byteLength || reqResponse.length;
    if (!request.bandwidth) {
      request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1e3);
    }
  }
  if (response.headers) {
    request.responseHeaders = response.headers;
  }
  if (error && error.code === "ETIMEDOUT") {
    request.timedout = true;
  }
  if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
    error = new Error("XHR Failed with a response of: " + (request && (reqResponse || request.responseText)));
  }
  callback2(error, request);
};
var xhrFactory = function xhrFactory2() {
  var xhr = function XhrFunction(options, callback2) {
    options = mergeOptions$1({
      timeout: 45e3
    }, options);
    var beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest;
    if (beforeRequest && typeof beforeRequest === "function") {
      var newOptions = beforeRequest(options);
      if (newOptions) {
        options = newOptions;
      }
    }
    var xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr;
    var request = xhrMethod(options, function(error, response) {
      return callbackWrapper(request, error, response, callback2);
    });
    var originalAbort = request.abort;
    request.abort = function() {
      request.aborted = true;
      return originalAbort.apply(request, arguments);
    };
    request.uri = options.uri;
    request.requestTime = Date.now();
    return request;
  };
  xhr.original = true;
  return xhr;
};
var byterangeStr = function byterangeStr2(byterange) {
  var byterangeEnd;
  var byterangeStart = byterange.offset;
  if (typeof byterange.offset === "bigint" || typeof byterange.length === "bigint") {
    byterangeEnd = import_window6.default.BigInt(byterange.offset) + import_window6.default.BigInt(byterange.length) - import_window6.default.BigInt(1);
  } else {
    byterangeEnd = byterange.offset + byterange.length - 1;
  }
  return "bytes=" + byterangeStart + "-" + byterangeEnd;
};
var segmentXhrHeaders = function segmentXhrHeaders2(segment) {
  var headers = {};
  if (segment.byterange) {
    headers.Range = byterangeStr(segment.byterange);
  }
  return headers;
};
var textRange = function textRange2(range3, i) {
  return range3.start(i) + "-" + range3.end(i);
};
var formatHexString = function formatHexString2(e, i) {
  var value = e.toString(16);
  return "00".substring(0, 2 - value.length) + value + (i % 2 ? " " : "");
};
var formatAsciiString = function formatAsciiString2(e) {
  if (e >= 32 && e < 126) {
    return String.fromCharCode(e);
  }
  return ".";
};
var createTransferableMessage = function createTransferableMessage2(message) {
  var transferable = {};
  Object.keys(message).forEach(function(key) {
    var value = message[key];
    if (isArrayBufferView2(value)) {
      transferable[key] = {
        bytes: value.buffer,
        byteOffset: value.byteOffset,
        byteLength: value.byteLength
      };
    } else {
      transferable[key] = value;
    }
  });
  return transferable;
};
var initSegmentId = function initSegmentId2(initSegment) {
  var byterange = initSegment.byterange || {
    length: Infinity,
    offset: 0
  };
  return [byterange.length, byterange.offset, initSegment.resolvedUri].join(",");
};
var segmentKeyId = function segmentKeyId2(key) {
  return key.resolvedUri;
};
var hexDump = function hexDump2(data) {
  var bytes = Array.prototype.slice.call(data);
  var step = 16;
  var result = "";
  var hex;
  var ascii;
  for (var j = 0; j < bytes.length / step; j++) {
    hex = bytes.slice(j * step, j * step + step).map(formatHexString).join("");
    ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join("");
    result += hex + " " + ascii + "\n";
  }
  return result;
};
var tagDump = function tagDump2(_ref) {
  var bytes = _ref.bytes;
  return hexDump(bytes);
};
var textRanges = function textRanges2(ranges) {
  var result = "";
  var i;
  for (i = 0; i < ranges.length; i++) {
    result += textRange(ranges, i) + " ";
  }
  return result;
};
var utils = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  createTransferableMessage,
  initSegmentId,
  segmentKeyId,
  hexDump,
  tagDump,
  textRanges
});
var SEGMENT_END_FUDGE_PERCENT = 0.25;
var playerTimeToProgramTime = function playerTimeToProgramTime2(playerTime, segment) {
  if (!segment.dateTimeObject) {
    return null;
  }
  var transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  var transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart;
  var startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  var offsetFromSegmentStart = playerTime - startOfSegment;
  return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1e3);
};
var originalSegmentVideoDuration = function originalSegmentVideoDuration2(videoTimingInfo) {
  return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
};
var findSegmentForProgramTime = function findSegmentForProgramTime2(programTime, playlist) {
  var dateTimeObject;
  try {
    dateTimeObject = new Date(programTime);
  } catch (e) {
    return null;
  }
  if (!playlist || !playlist.segments || playlist.segments.length === 0) {
    return null;
  }
  var segment = playlist.segments[0];
  if (dateTimeObject < segment.dateTimeObject) {
    return null;
  }
  for (var i = 0; i < playlist.segments.length - 1; i++) {
    segment = playlist.segments[i];
    var nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
    if (dateTimeObject < nextSegmentStart) {
      break;
    }
  }
  var lastSegment = playlist.segments[playlist.segments.length - 1];
  var lastSegmentStart = lastSegment.dateTimeObject;
  var lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  var lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1e3);
  if (dateTimeObject > lastSegmentEnd) {
    return null;
  }
  if (dateTimeObject > lastSegmentStart) {
    segment = lastSegment;
  }
  return {
    segment,
    estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
    // Although, given that all segments have accurate date time objects, the segment
    // selected should be accurate, unless the video has been transmuxed at some point
    // (determined by the presence of the videoTimingInfo object), the segment's "player
    // time" (the start time in the player) can't be considered accurate.
    type: segment.videoTimingInfo ? "accurate" : "estimate"
  };
};
var findSegmentForPlayerTime = function findSegmentForPlayerTime2(time, playlist) {
  if (!playlist || !playlist.segments || playlist.segments.length === 0) {
    return null;
  }
  var segmentEnd = 0;
  var segment;
  for (var i = 0; i < playlist.segments.length; i++) {
    segment = playlist.segments[i];
    segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
    if (time <= segmentEnd) {
      break;
    }
  }
  var lastSegment = playlist.segments[playlist.segments.length - 1];
  if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
    return null;
  }
  if (time > segmentEnd) {
    if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
      return null;
    }
    segment = lastSegment;
  }
  return {
    segment,
    estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
    // Because videoTimingInfo is only set after transmux, it is the only way to get
    // accurate timing values.
    type: segment.videoTimingInfo ? "accurate" : "estimate"
  };
};
var getOffsetFromTimestamp = function getOffsetFromTimestamp2(comparisonTimeStamp, programTime) {
  var segmentDateTime;
  var programDateTime;
  try {
    segmentDateTime = new Date(comparisonTimeStamp);
    programDateTime = new Date(programTime);
  } catch (e) {
  }
  var segmentTimeEpoch = segmentDateTime.getTime();
  var programTimeEpoch = programDateTime.getTime();
  return (programTimeEpoch - segmentTimeEpoch) / 1e3;
};
var verifyProgramDateTimeTags = function verifyProgramDateTimeTags2(playlist) {
  if (!playlist.segments || playlist.segments.length === 0) {
    return false;
  }
  for (var i = 0; i < playlist.segments.length; i++) {
    var segment = playlist.segments[i];
    if (!segment.dateTimeObject) {
      return false;
    }
  }
  return true;
};
var getProgramTime = function getProgramTime2(_ref) {
  var playlist = _ref.playlist, _ref$time = _ref.time, time = _ref$time === void 0 ? void 0 : _ref$time, callback2 = _ref.callback;
  if (!callback2) {
    throw new Error("getProgramTime: callback must be provided");
  }
  if (!playlist || time === void 0) {
    return callback2({
      message: "getProgramTime: playlist and time must be provided"
    });
  }
  var matchedSegment = findSegmentForPlayerTime(time, playlist);
  if (!matchedSegment) {
    return callback2({
      message: "valid programTime was not found"
    });
  }
  if (matchedSegment.type === "estimate") {
    return callback2({
      message: "Accurate programTime could not be determined. Please seek to e.seekTime and try again",
      seekTime: matchedSegment.estimatedStart
    });
  }
  var programTimeObject = {
    mediaSeconds: time
  };
  var programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  if (programTime) {
    programTimeObject.programDateTime = programTime.toISOString();
  }
  return callback2(null, programTimeObject);
};
var seekToProgramTime = function seekToProgramTime2(_ref2) {
  var programTime = _ref2.programTime, playlist = _ref2.playlist, _ref2$retryCount = _ref2.retryCount, retryCount = _ref2$retryCount === void 0 ? 2 : _ref2$retryCount, seekTo = _ref2.seekTo, _ref2$pauseAfterSeek = _ref2.pauseAfterSeek, pauseAfterSeek = _ref2$pauseAfterSeek === void 0 ? true : _ref2$pauseAfterSeek, tech = _ref2.tech, callback2 = _ref2.callback;
  if (!callback2) {
    throw new Error("seekToProgramTime: callback must be provided");
  }
  if (typeof programTime === "undefined" || !playlist || !seekTo) {
    return callback2({
      message: "seekToProgramTime: programTime, seekTo and playlist must be provided"
    });
  }
  if (!playlist.endList && !tech.hasStarted_) {
    return callback2({
      message: "player must be playing a live stream to start buffering"
    });
  }
  if (!verifyProgramDateTimeTags(playlist)) {
    return callback2({
      message: "programDateTime tags must be provided in the manifest " + playlist.resolvedUri
    });
  }
  var matchedSegment = findSegmentForProgramTime(programTime, playlist);
  if (!matchedSegment) {
    return callback2({
      message: programTime + " was not found in the stream"
    });
  }
  var segment = matchedSegment.segment;
  var mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  if (matchedSegment.type === "estimate") {
    if (retryCount === 0) {
      return callback2({
        message: programTime + " is not buffered yet. Try again"
      });
    }
    seekTo(matchedSegment.estimatedStart + mediaOffset);
    tech.one("seeked", function() {
      seekToProgramTime2({
        programTime,
        playlist,
        retryCount: retryCount - 1,
        seekTo,
        pauseAfterSeek,
        tech,
        callback: callback2
      });
    });
    return;
  }
  var seekToTime = segment.start + mediaOffset;
  var seekedCallback = function seekedCallback2() {
    return callback2(null, tech.currentTime());
  };
  tech.one("seeked", seekedCallback);
  if (pauseAfterSeek) {
    tech.pause();
  }
  seekTo(seekToTime);
};
var callbackOnCompleted = function callbackOnCompleted2(request, cb) {
  if (request.readyState === 4) {
    return cb();
  }
  return;
};
var containerRequest = function containerRequest2(uri, xhr, cb) {
  var bytes = [];
  var id3Offset;
  var finished = false;
  var endRequestAndCallback = function endRequestAndCallback2(err, req, type2, _bytes) {
    req.abort();
    finished = true;
    return cb(err, req, type2, _bytes);
  };
  var progressListener = function progressListener2(error, request2) {
    if (finished) {
      return;
    }
    if (error) {
      return endRequestAndCallback(error, request2, "", bytes);
    }
    var newPart = request2.responseText.substring(bytes && bytes.byteLength || 0, request2.responseText.length);
    bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
    id3Offset = id3Offset || getId3Offset(bytes);
    if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
      return callbackOnCompleted(request2, function() {
        return endRequestAndCallback(error, request2, "", bytes);
      });
    }
    var type2 = detectContainerForBytes(bytes);
    if (type2 === "ts" && bytes.length < 188) {
      return callbackOnCompleted(request2, function() {
        return endRequestAndCallback(error, request2, "", bytes);
      });
    }
    if (!type2 && bytes.length < 376) {
      return callbackOnCompleted(request2, function() {
        return endRequestAndCallback(error, request2, "", bytes);
      });
    }
    return endRequestAndCallback(null, request2, type2, bytes);
  };
  var options = {
    uri,
    beforeSend: function beforeSend(request2) {
      request2.overrideMimeType("text/plain; charset=x-user-defined");
      request2.addEventListener("progress", function(_ref) {
        _ref.total;
        _ref.loaded;
        return callbackWrapper(request2, null, {
          statusCode: request2.status
        }, progressListener);
      });
    }
  };
  var request = xhr(options, function(error, response) {
    return callbackWrapper(request, error, response, progressListener);
  });
  return request;
};
var EventTarget2 = videojs.EventTarget;
var mergeOptions = videojs.mergeOptions;
var dashPlaylistUnchanged = function dashPlaylistUnchanged2(a, b) {
  if (!isPlaylistUnchanged(a, b)) {
    return false;
  }
  if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
    return false;
  } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
    return false;
  }
  if (a.segments && !b.segments || !a.segments && b.segments) {
    return false;
  }
  if (!a.segments && !b.segments) {
    return true;
  }
  for (var i = 0; i < a.segments.length; i++) {
    var aSegment = a.segments[i];
    var bSegment = b.segments[i];
    if (aSegment.uri !== bSegment.uri) {
      return false;
    }
    if (!aSegment.byterange && !bSegment.byterange) {
      continue;
    }
    var aByterange = aSegment.byterange;
    var bByterange = bSegment.byterange;
    if (aByterange && !bByterange || !aByterange && bByterange) {
      return false;
    }
    if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
      return false;
    }
  }
  return true;
};
var parseMasterXml = function parseMasterXml2(_ref) {
  var masterXml = _ref.masterXml, srcUrl = _ref.srcUrl, clientOffset = _ref.clientOffset, sidxMapping = _ref.sidxMapping, previousManifest = _ref.previousManifest;
  var manifest = parse(masterXml, {
    manifestUri: srcUrl,
    clientOffset,
    sidxMapping,
    previousManifest
  });
  addPropertiesToMaster(manifest, srcUrl);
  return manifest;
};
var updateMaster2 = function updateMaster3(oldMaster, newMaster, sidxMapping) {
  var noChanges = true;
  var update = mergeOptions(oldMaster, {
    // These are top level properties that can be updated
    duration: newMaster.duration,
    minimumUpdatePeriod: newMaster.minimumUpdatePeriod,
    timelineStarts: newMaster.timelineStarts
  });
  for (var i = 0; i < newMaster.playlists.length; i++) {
    var playlist = newMaster.playlists[i];
    if (playlist.sidx) {
      var sidxKey = generateSidxKey(playlist.sidx);
      if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
        addSidxSegmentsToPlaylist$1(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
      }
    }
    var playlistUpdate = updateMaster$1(update, playlist, dashPlaylistUnchanged);
    if (playlistUpdate) {
      update = playlistUpdate;
      noChanges = false;
    }
  }
  forEachMediaGroup3(newMaster, function(properties, type2, group, label) {
    if (properties.playlists && properties.playlists.length) {
      var id = properties.playlists[0].id;
      var _playlistUpdate = updateMaster$1(update, properties.playlists[0], dashPlaylistUnchanged);
      if (_playlistUpdate) {
        update = _playlistUpdate;
        update.mediaGroups[type2][group][label].playlists[0] = update.playlists[id];
        noChanges = false;
      }
    }
  });
  if (newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
    noChanges = false;
  }
  if (noChanges) {
    return null;
  }
  return update;
};
var equivalentSidx = function equivalentSidx2(a, b) {
  var neitherMap = Boolean(!a.map && !b.map);
  var equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
};
var compareSidxEntry = function compareSidxEntry2(playlists, oldSidxMapping) {
  var newSidxMapping = {};
  for (var id in playlists) {
    var playlist = playlists[id];
    var currentSidxInfo = playlist.sidx;
    if (currentSidxInfo) {
      var key = generateSidxKey(currentSidxInfo);
      if (!oldSidxMapping[key]) {
        break;
      }
      var savedSidxInfo = oldSidxMapping[key].sidxInfo;
      if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
        newSidxMapping[key] = oldSidxMapping[key];
      }
    }
  }
  return newSidxMapping;
};
var filterChangedSidxMappings = function filterChangedSidxMappings2(master, oldSidxMapping) {
  var videoSidx = compareSidxEntry(master.playlists, oldSidxMapping);
  var mediaGroupSidx = videoSidx;
  forEachMediaGroup3(master, function(properties, mediaType, groupKey, labelKey) {
    if (properties.playlists && properties.playlists.length) {
      var playlists = properties.playlists;
      mediaGroupSidx = mergeOptions(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
    }
  });
  return mediaGroupSidx;
};
var DashPlaylistLoader = /* @__PURE__ */ function(_EventTarget) {
  _inheritsLoose(DashPlaylistLoader2, _EventTarget);
  function DashPlaylistLoader2(srcUrlOrPlaylist, vhs, options, masterPlaylistLoader) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    _this = _EventTarget.call(this) || this;
    _this.masterPlaylistLoader_ = masterPlaylistLoader || _assertThisInitialized(_this);
    if (!masterPlaylistLoader) {
      _this.isMaster_ = true;
    }
    var _options = options, _options$withCredenti = _options.withCredentials, withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti, _options$handleManife = _options.handleManifestRedirects, handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
    _this.vhs_ = vhs;
    _this.withCredentials = withCredentials;
    _this.handleManifestRedirects = handleManifestRedirects;
    if (!srcUrlOrPlaylist) {
      throw new Error("A non-empty playlist URL or object is required");
    }
    _this.on("minimumUpdatePeriod", function() {
      _this.refreshXml_();
    });
    _this.on("mediaupdatetimeout", function() {
      _this.refreshMedia_(_this.media().id);
    });
    _this.state = "HAVE_NOTHING";
    _this.loadedPlaylists_ = {};
    _this.logger_ = logger2("DashPlaylistLoader");
    if (_this.isMaster_) {
      _this.masterPlaylistLoader_.srcUrl = srcUrlOrPlaylist;
      _this.masterPlaylistLoader_.sidxMapping_ = {};
    } else {
      _this.childPlaylist_ = srcUrlOrPlaylist;
    }
    return _this;
  }
  var _proto = DashPlaylistLoader2.prototype;
  _proto.requestErrored_ = function requestErrored_(err, request, startingState) {
    if (!this.request) {
      return true;
    }
    this.request = null;
    if (err) {
      this.error = typeof err === "object" && !(err instanceof Error) ? err : {
        status: request.status,
        message: "DASH request error at URL: " + request.uri,
        response: request.response,
        // MEDIA_ERR_NETWORK
        code: 2
      };
      if (startingState) {
        this.state = startingState;
      }
      this.trigger("error");
      return true;
    }
  };
  _proto.addSidxSegments_ = function addSidxSegments_(playlist, startingState, cb) {
    var _this2 = this;
    var sidxKey = playlist.sidx && generateSidxKey(playlist.sidx);
    if (!playlist.sidx || !sidxKey || this.masterPlaylistLoader_.sidxMapping_[sidxKey]) {
      this.mediaRequest_ = import_window6.default.setTimeout(function() {
        return cb(false);
      }, 0);
      return;
    }
    var uri = resolveManifestRedirect(this.handleManifestRedirects, playlist.sidx.resolvedUri);
    var fin = function fin2(err, request) {
      if (_this2.requestErrored_(err, request, startingState)) {
        return;
      }
      var sidxMapping = _this2.masterPlaylistLoader_.sidxMapping_;
      var sidx;
      try {
        sidx = (0, import_parse_sidx.default)(toUint82(request.response).subarray(8));
      } catch (e) {
        _this2.requestErrored_(e, request, startingState);
        return;
      }
      sidxMapping[sidxKey] = {
        sidxInfo: playlist.sidx,
        sidx
      };
      addSidxSegmentsToPlaylist$1(playlist, sidx, playlist.sidx.resolvedUri);
      return cb(true);
    };
    this.request = containerRequest(uri, this.vhs_.xhr, function(err, request, container, bytes) {
      if (err) {
        return fin(err, request);
      }
      if (!container || container !== "mp4") {
        return fin({
          status: request.status,
          message: "Unsupported " + (container || "unknown") + " container type for sidx segment at URL: " + uri,
          // response is just bytes in this case
          // but we really don't want to return that.
          response: "",
          playlist,
          internal: true,
          blacklistDuration: Infinity,
          // MEDIA_ERR_NETWORK
          code: 2
        }, request);
      }
      var _playlist$sidx$bytera = playlist.sidx.byterange, offset = _playlist$sidx$bytera.offset, length = _playlist$sidx$bytera.length;
      if (bytes.length >= length + offset) {
        return fin(err, {
          response: bytes.subarray(offset, offset + length),
          status: request.status,
          uri: request.uri
        });
      }
      _this2.request = _this2.vhs_.xhr({
        uri,
        responseType: "arraybuffer",
        headers: segmentXhrHeaders({
          byterange: playlist.sidx.byterange
        })
      }, fin);
    });
  };
  _proto.dispose = function dispose() {
    this.trigger("dispose");
    this.stopRequest();
    this.loadedPlaylists_ = {};
    import_window6.default.clearTimeout(this.minimumUpdatePeriodTimeout_);
    import_window6.default.clearTimeout(this.mediaRequest_);
    import_window6.default.clearTimeout(this.mediaUpdateTimeout);
    this.mediaUpdateTimeout = null;
    this.mediaRequest_ = null;
    this.minimumUpdatePeriodTimeout_ = null;
    if (this.masterPlaylistLoader_.createMupOnMedia_) {
      this.off("loadedmetadata", this.masterPlaylistLoader_.createMupOnMedia_);
      this.masterPlaylistLoader_.createMupOnMedia_ = null;
    }
    this.off();
  };
  _proto.hasPendingRequest = function hasPendingRequest() {
    return this.request || this.mediaRequest_;
  };
  _proto.stopRequest = function stopRequest() {
    if (this.request) {
      var oldRequest = this.request;
      this.request = null;
      oldRequest.onreadystatechange = null;
      oldRequest.abort();
    }
  };
  _proto.media = function media(playlist) {
    var _this3 = this;
    if (!playlist) {
      return this.media_;
    }
    if (this.state === "HAVE_NOTHING") {
      throw new Error("Cannot switch media playlist from " + this.state);
    }
    var startingState = this.state;
    if (typeof playlist === "string") {
      if (!this.masterPlaylistLoader_.master.playlists[playlist]) {
        throw new Error("Unknown playlist URI: " + playlist);
      }
      playlist = this.masterPlaylistLoader_.master.playlists[playlist];
    }
    var mediaChange = !this.media_ || playlist.id !== this.media_.id;
    if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
      this.state = "HAVE_METADATA";
      this.media_ = playlist;
      if (mediaChange) {
        this.trigger("mediachanging");
        this.trigger("mediachange");
      }
      return;
    }
    if (!mediaChange) {
      return;
    }
    if (this.media_) {
      this.trigger("mediachanging");
    }
    this.addSidxSegments_(playlist, startingState, function(sidxChanged) {
      _this3.haveMetadata({
        startingState,
        playlist
      });
    });
  };
  _proto.haveMetadata = function haveMetadata(_ref2) {
    var startingState = _ref2.startingState, playlist = _ref2.playlist;
    this.state = "HAVE_METADATA";
    this.loadedPlaylists_[playlist.id] = playlist;
    this.mediaRequest_ = null;
    this.refreshMedia_(playlist.id);
    if (startingState === "HAVE_MASTER") {
      this.trigger("loadedmetadata");
    } else {
      this.trigger("mediachange");
    }
  };
  _proto.pause = function pause() {
    if (this.masterPlaylistLoader_.createMupOnMedia_) {
      this.off("loadedmetadata", this.masterPlaylistLoader_.createMupOnMedia_);
      this.masterPlaylistLoader_.createMupOnMedia_ = null;
    }
    this.stopRequest();
    import_window6.default.clearTimeout(this.mediaUpdateTimeout);
    this.mediaUpdateTimeout = null;
    if (this.isMaster_) {
      import_window6.default.clearTimeout(this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_);
      this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
    }
    if (this.state === "HAVE_NOTHING") {
      this.started = false;
    }
  };
  _proto.load = function load(isFinalRendition) {
    var _this4 = this;
    import_window6.default.clearTimeout(this.mediaUpdateTimeout);
    this.mediaUpdateTimeout = null;
    var media = this.media();
    if (isFinalRendition) {
      var delay = media ? media.targetDuration / 2 * 1e3 : 5 * 1e3;
      this.mediaUpdateTimeout = import_window6.default.setTimeout(function() {
        return _this4.load();
      }, delay);
      return;
    }
    if (!this.started) {
      this.start();
      return;
    }
    if (media && !media.endList) {
      if (this.isMaster_ && !this.minimumUpdatePeriodTimeout_) {
        this.trigger("minimumUpdatePeriod");
        this.updateMinimumUpdatePeriodTimeout_();
      }
      this.trigger("mediaupdatetimeout");
    } else {
      this.trigger("loadedplaylist");
    }
  };
  _proto.start = function start2() {
    var _this5 = this;
    this.started = true;
    if (!this.isMaster_) {
      this.mediaRequest_ = import_window6.default.setTimeout(function() {
        return _this5.haveMaster_();
      }, 0);
      return;
    }
    this.requestMaster_(function(req, masterChanged) {
      _this5.haveMaster_();
      if (!_this5.hasPendingRequest() && !_this5.media_) {
        _this5.media(_this5.masterPlaylistLoader_.master.playlists[0]);
      }
    });
  };
  _proto.requestMaster_ = function requestMaster_(cb) {
    var _this6 = this;
    this.request = this.vhs_.xhr({
      uri: this.masterPlaylistLoader_.srcUrl,
      withCredentials: this.withCredentials
    }, function(error, req) {
      if (_this6.requestErrored_(error, req)) {
        if (_this6.state === "HAVE_NOTHING") {
          _this6.started = false;
        }
        return;
      }
      var masterChanged = req.responseText !== _this6.masterPlaylistLoader_.masterXml_;
      _this6.masterPlaylistLoader_.masterXml_ = req.responseText;
      if (req.responseHeaders && req.responseHeaders.date) {
        _this6.masterLoaded_ = Date.parse(req.responseHeaders.date);
      } else {
        _this6.masterLoaded_ = Date.now();
      }
      _this6.masterPlaylistLoader_.srcUrl = resolveManifestRedirect(_this6.handleManifestRedirects, _this6.masterPlaylistLoader_.srcUrl, req);
      if (masterChanged) {
        _this6.handleMaster_();
        _this6.syncClientServerClock_(function() {
          return cb(req, masterChanged);
        });
        return;
      }
      return cb(req, masterChanged);
    });
  };
  _proto.syncClientServerClock_ = function syncClientServerClock_(done) {
    var _this7 = this;
    var utcTiming = parseUTCTiming(this.masterPlaylistLoader_.masterXml_);
    if (utcTiming === null) {
      this.masterPlaylistLoader_.clientOffset_ = this.masterLoaded_ - Date.now();
      return done();
    }
    if (utcTiming.method === "DIRECT") {
      this.masterPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
      return done();
    }
    this.request = this.vhs_.xhr({
      uri: resolveUrl3(this.masterPlaylistLoader_.srcUrl, utcTiming.value),
      method: utcTiming.method,
      withCredentials: this.withCredentials
    }, function(error, req) {
      if (!_this7.request) {
        return;
      }
      if (error) {
        _this7.masterPlaylistLoader_.clientOffset_ = _this7.masterLoaded_ - Date.now();
        return done();
      }
      var serverTime;
      if (utcTiming.method === "HEAD") {
        if (!req.responseHeaders || !req.responseHeaders.date) {
          serverTime = _this7.masterLoaded_;
        } else {
          serverTime = Date.parse(req.responseHeaders.date);
        }
      } else {
        serverTime = Date.parse(req.responseText);
      }
      _this7.masterPlaylistLoader_.clientOffset_ = serverTime - Date.now();
      done();
    });
  };
  _proto.haveMaster_ = function haveMaster_() {
    this.state = "HAVE_MASTER";
    if (this.isMaster_) {
      this.trigger("loadedplaylist");
    } else if (!this.media_) {
      this.media(this.childPlaylist_);
    }
  };
  _proto.handleMaster_ = function handleMaster_() {
    this.mediaRequest_ = null;
    var oldMaster = this.masterPlaylistLoader_.master;
    var newMaster = parseMasterXml({
      masterXml: this.masterPlaylistLoader_.masterXml_,
      srcUrl: this.masterPlaylistLoader_.srcUrl,
      clientOffset: this.masterPlaylistLoader_.clientOffset_,
      sidxMapping: this.masterPlaylistLoader_.sidxMapping_,
      previousManifest: oldMaster
    });
    if (oldMaster) {
      newMaster = updateMaster2(oldMaster, newMaster, this.masterPlaylistLoader_.sidxMapping_);
    }
    this.masterPlaylistLoader_.master = newMaster ? newMaster : oldMaster;
    var location2 = this.masterPlaylistLoader_.master.locations && this.masterPlaylistLoader_.master.locations[0];
    if (location2 && location2 !== this.masterPlaylistLoader_.srcUrl) {
      this.masterPlaylistLoader_.srcUrl = location2;
    }
    if (!oldMaster || newMaster && newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
      this.updateMinimumUpdatePeriodTimeout_();
    }
    return Boolean(newMaster);
  };
  _proto.updateMinimumUpdatePeriodTimeout_ = function updateMinimumUpdatePeriodTimeout_() {
    var mpl = this.masterPlaylistLoader_;
    if (mpl.createMupOnMedia_) {
      mpl.off("loadedmetadata", mpl.createMupOnMedia_);
      mpl.createMupOnMedia_ = null;
    }
    if (mpl.minimumUpdatePeriodTimeout_) {
      import_window6.default.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
      mpl.minimumUpdatePeriodTimeout_ = null;
    }
    var mup = mpl.master && mpl.master.minimumUpdatePeriod;
    if (mup === 0) {
      if (mpl.media()) {
        mup = mpl.media().targetDuration * 1e3;
      } else {
        mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
        mpl.one("loadedmetadata", mpl.createMupOnMedia_);
      }
    }
    if (typeof mup !== "number" || mup <= 0) {
      if (mup < 0) {
        this.logger_("found invalid minimumUpdatePeriod of " + mup + ", not setting a timeout");
      }
      return;
    }
    this.createMUPTimeout_(mup);
  };
  _proto.createMUPTimeout_ = function createMUPTimeout_(mup) {
    var mpl = this.masterPlaylistLoader_;
    mpl.minimumUpdatePeriodTimeout_ = import_window6.default.setTimeout(function() {
      mpl.minimumUpdatePeriodTimeout_ = null;
      mpl.trigger("minimumUpdatePeriod");
      mpl.createMUPTimeout_(mup);
    }, mup);
  };
  _proto.refreshXml_ = function refreshXml_() {
    var _this8 = this;
    this.requestMaster_(function(req, masterChanged) {
      if (!masterChanged) {
        return;
      }
      if (_this8.media_) {
        _this8.media_ = _this8.masterPlaylistLoader_.master.playlists[_this8.media_.id];
      }
      _this8.masterPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(_this8.masterPlaylistLoader_.master, _this8.masterPlaylistLoader_.sidxMapping_);
      _this8.addSidxSegments_(_this8.media(), _this8.state, function(sidxChanged) {
        _this8.refreshMedia_(_this8.media().id);
      });
    });
  };
  _proto.refreshMedia_ = function refreshMedia_(mediaID) {
    var _this9 = this;
    if (!mediaID) {
      throw new Error("refreshMedia_ must take a media id");
    }
    if (this.media_ && this.isMaster_) {
      this.handleMaster_();
    }
    var playlists = this.masterPlaylistLoader_.master.playlists;
    var mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
    if (mediaChanged) {
      this.media_ = playlists[mediaID];
    } else {
      this.trigger("playlistunchanged");
    }
    if (!this.mediaUpdateTimeout) {
      var createMediaUpdateTimeout = function createMediaUpdateTimeout2() {
        if (_this9.media().endList) {
          return;
        }
        _this9.mediaUpdateTimeout = import_window6.default.setTimeout(function() {
          _this9.trigger("mediaupdatetimeout");
          createMediaUpdateTimeout2();
        }, refreshDelay(_this9.media(), Boolean(mediaChanged)));
      };
      createMediaUpdateTimeout();
    }
    this.trigger("loadedplaylist");
  };
  return DashPlaylistLoader2;
}(EventTarget2);
var Config = {
  GOAL_BUFFER_LENGTH: 30,
  MAX_GOAL_BUFFER_LENGTH: 60,
  BACK_BUFFER_LENGTH: 30,
  GOAL_BUFFER_LENGTH_RATE: 1,
  // 0.5 MB/s
  INITIAL_BANDWIDTH: 4194304,
  // A fudge factor to apply to advertised playlist bitrates to account for
  // temporary flucations in client bandwidth
  BANDWIDTH_VARIANCE: 1.2,
  // How much of the buffer must be filled before we consider upswitching
  BUFFER_LOW_WATER_LINE: 0,
  MAX_BUFFER_LOW_WATER_LINE: 30,
  // TODO: Remove this when experimentalBufferBasedABR is removed
  EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  BUFFER_LOW_WATER_LINE_RATE: 1,
  // If the buffer is greater than the high water line, we won't switch down
  BUFFER_HIGH_WATER_LINE: 30
};
var stringToArrayBuffer = function stringToArrayBuffer2(string) {
  var view2 = new Uint8Array(new ArrayBuffer(string.length));
  for (var i = 0; i < string.length; i++) {
    view2[i] = string.charCodeAt(i);
  }
  return view2.buffer;
};
var browserWorkerPolyFill = function browserWorkerPolyFill2(workerObj) {
  workerObj.on = workerObj.addEventListener;
  workerObj.off = workerObj.removeEventListener;
  return workerObj;
};
var createObjectURL = function createObjectURL2(str) {
  try {
    return URL.createObjectURL(new Blob([str], {
      type: "application/javascript"
    }));
  } catch (e) {
    var blob = new BlobBuilder();
    blob.append(str);
    return URL.createObjectURL(blob.getBlob());
  }
};
var factory = function factory2(code) {
  return function() {
    var objectUrl = createObjectURL(code);
    var worker = browserWorkerPolyFill(new Worker(objectUrl));
    worker.objURL = objectUrl;
    var terminate = worker.terminate;
    worker.on = worker.addEventListener;
    worker.off = worker.removeEventListener;
    worker.terminate = function() {
      URL.revokeObjectURL(objectUrl);
      return terminate.call(this);
    };
    return worker;
  };
};
var transform = function transform2(code) {
  return "var browserWorkerPolyFill = " + browserWorkerPolyFill.toString() + ";\nbrowserWorkerPolyFill(self);\n" + code;
};
var getWorkerString = function getWorkerString2(fn) {
  return fn.toString().replace(/^function.+?{/, "").slice(0, -1);
};
var workerCode$1 = transform(getWorkerString(function() {
  var Stream2 = function Stream3() {
    this.init = function() {
      var listeners = {};
      this.on = function(type3, listener) {
        if (!listeners[type3]) {
          listeners[type3] = [];
        }
        listeners[type3] = listeners[type3].concat(listener);
      };
      this.off = function(type3, listener) {
        var index;
        if (!listeners[type3]) {
          return false;
        }
        index = listeners[type3].indexOf(listener);
        listeners[type3] = listeners[type3].slice();
        listeners[type3].splice(index, 1);
        return index > -1;
      };
      this.trigger = function(type3) {
        var callbacks, i, length, args;
        callbacks = listeners[type3];
        if (!callbacks) {
          return;
        }
        if (arguments.length === 2) {
          length = callbacks.length;
          for (i = 0; i < length; ++i) {
            callbacks[i].call(this, arguments[1]);
          }
        } else {
          args = [];
          i = arguments.length;
          for (i = 1; i < arguments.length; ++i) {
            args.push(arguments[i]);
          }
          length = callbacks.length;
          for (i = 0; i < length; ++i) {
            callbacks[i].apply(this, args);
          }
        }
      };
      this.dispose = function() {
        listeners = {};
      };
    };
  };
  Stream2.prototype.pipe = function(destination) {
    this.on("data", function(data) {
      destination.push(data);
    });
    this.on("done", function(flushSource) {
      destination.flush(flushSource);
    });
    this.on("partialdone", function(flushSource) {
      destination.partialFlush(flushSource);
    });
    this.on("endedtimeline", function(flushSource) {
      destination.endTimeline(flushSource);
    });
    this.on("reset", function(flushSource) {
      destination.reset(flushSource);
    });
    return destination;
  };
  Stream2.prototype.push = function(data) {
    this.trigger("data", data);
  };
  Stream2.prototype.flush = function(flushSource) {
    this.trigger("done", flushSource);
  };
  Stream2.prototype.partialFlush = function(flushSource) {
    this.trigger("partialdone", flushSource);
  };
  Stream2.prototype.endTimeline = function(flushSource) {
    this.trigger("endedtimeline", flushSource);
  };
  Stream2.prototype.reset = function(flushSource) {
    this.trigger("reset", flushSource);
  };
  var stream = Stream2;
  var MAX_UINT32$1 = Math.pow(2, 32);
  var getUint64$2 = function getUint642(uint8) {
    var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
    var value;
    if (dv.getBigUint64) {
      value = dv.getBigUint64(0);
      if (value < Number.MAX_SAFE_INTEGER) {
        return Number(value);
      }
      return value;
    }
    return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  };
  var numbers = {
    getUint64: getUint64$2,
    MAX_UINT32: MAX_UINT32$1
  };
  var MAX_UINT32 = numbers.MAX_UINT32;
  var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex, trun$1, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR, AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS;
  (function() {
    var i;
    types = {
      avc1: [],
      // codingname
      avcC: [],
      btrt: [],
      dinf: [],
      dref: [],
      esds: [],
      ftyp: [],
      hdlr: [],
      mdat: [],
      mdhd: [],
      mdia: [],
      mfhd: [],
      minf: [],
      moof: [],
      moov: [],
      mp4a: [],
      // codingname
      mvex: [],
      mvhd: [],
      pasp: [],
      sdtp: [],
      smhd: [],
      stbl: [],
      stco: [],
      stsc: [],
      stsd: [],
      stsz: [],
      stts: [],
      styp: [],
      tfdt: [],
      tfhd: [],
      traf: [],
      trak: [],
      trun: [],
      trex: [],
      tkhd: [],
      vmhd: []
    };
    if (typeof Uint8Array === "undefined") {
      return;
    }
    for (i in types) {
      if (types.hasOwnProperty(i)) {
        types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
      }
    }
    MAJOR_BRAND = new Uint8Array(["i".charCodeAt(0), "s".charCodeAt(0), "o".charCodeAt(0), "m".charCodeAt(0)]);
    AVC1_BRAND = new Uint8Array(["a".charCodeAt(0), "v".charCodeAt(0), "c".charCodeAt(0), "1".charCodeAt(0)]);
    MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
    VIDEO_HDLR = 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'
    ]);
    AUDIO_HDLR = 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'
    ]);
    HDLR_TYPES = {
      video: VIDEO_HDLR,
      audio: AUDIO_HDLR
    };
    DREF = 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
    ]);
    SMHD = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      // balance, 0 means centered
      0,
      0
      // reserved
    ]);
    STCO = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0
      // entry_count
    ]);
    STSC = STCO;
    STSZ = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0,
      // sample_size
      0,
      0,
      0,
      0
      // sample_count
    ]);
    STTS = STCO;
    VMHD = new Uint8Array([
      0,
      // version
      0,
      0,
      1,
      // flags
      0,
      0,
      // graphicsmode
      0,
      0,
      0,
      0,
      0,
      0
      // opcolor
    ]);
  })();
  box = function box2(type3) {
    var payload = [], size = 0, i, result, view2;
    for (i = 1; i < arguments.length; i++) {
      payload.push(arguments[i]);
    }
    i = payload.length;
    while (i--) {
      size += payload[i].byteLength;
    }
    result = new Uint8Array(size + 8);
    view2 = new DataView(result.buffer, result.byteOffset, result.byteLength);
    view2.setUint32(0, result.byteLength);
    result.set(type3, 4);
    for (i = 0, size = 8; i < payload.length; i++) {
      result.set(payload[i], size);
      size += payload[i].byteLength;
    }
    return result;
  };
  dinf = function dinf2() {
    return box(types.dinf, box(types.dref, DREF));
  };
  esds = function esds2(track) {
    return box(types.esds, new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      // ES_Descriptor
      3,
      // tag, ES_DescrTag
      25,
      // length
      0,
      0,
      // ES_ID
      0,
      // streamDependenceFlag, URL_flag, reserved, streamPriority
      // DecoderConfigDescriptor
      4,
      // tag, DecoderConfigDescrTag
      17,
      // length
      64,
      // object type
      21,
      // streamType
      0,
      6,
      0,
      // bufferSizeDB
      0,
      0,
      218,
      192,
      // maxBitrate
      0,
      0,
      218,
      192,
      // avgBitrate
      // DecoderSpecificInfo
      5,
      // tag, DecoderSpecificInfoTag
      2,
      // length
      // ISO/IEC 14496-3, AudioSpecificConfig
      // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
      track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1,
      track.samplingfrequencyindex << 7 | track.channelcount << 3,
      6,
      1,
      2
      // GASpecificConfig
    ]));
  };
  ftyp = function ftyp2() {
    return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  };
  hdlr = function hdlr2(type3) {
    return box(types.hdlr, HDLR_TYPES[type3]);
  };
  mdat = function mdat2(data) {
    return box(types.mdat, data);
  };
  mdhd = function mdhd2(track) {
    var result = new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      2,
      // creation_time
      0,
      0,
      0,
      3,
      // modification_time
      0,
      1,
      95,
      144,
      // timescale, 90,000 "ticks" per second
      track.duration >>> 24 & 255,
      track.duration >>> 16 & 255,
      track.duration >>> 8 & 255,
      track.duration & 255,
      // duration
      85,
      196,
      // 'und' language (undetermined)
      0,
      0
    ]);
    if (track.samplerate) {
      result[12] = track.samplerate >>> 24 & 255;
      result[13] = track.samplerate >>> 16 & 255;
      result[14] = track.samplerate >>> 8 & 255;
      result[15] = track.samplerate & 255;
    }
    return box(types.mdhd, result);
  };
  mdia = function mdia2(track) {
    return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  };
  mfhd = function mfhd2(sequenceNumber) {
    return box(types.mfhd, new Uint8Array([
      0,
      0,
      0,
      0,
      // flags
      (sequenceNumber & 4278190080) >> 24,
      (sequenceNumber & 16711680) >> 16,
      (sequenceNumber & 65280) >> 8,
      sequenceNumber & 255
      // sequence_number
    ]));
  };
  minf = function minf2(track) {
    return box(types.minf, track.type === "video" ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  };
  moof = function moof2(sequenceNumber, tracks) {
    var trackFragments = [], i = tracks.length;
    while (i--) {
      trackFragments[i] = traf(tracks[i]);
    }
    return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  };
  moov = function moov2(tracks) {
    var i = tracks.length, boxes = [];
    while (i--) {
      boxes[i] = trak(tracks[i]);
    }
    return box.apply(null, [types.moov, mvhd(4294967295)].concat(boxes).concat(mvex(tracks)));
  };
  mvex = function mvex2(tracks) {
    var i = tracks.length, boxes = [];
    while (i--) {
      boxes[i] = trex(tracks[i]);
    }
    return box.apply(null, [types.mvex].concat(boxes));
  };
  mvhd = function mvhd2(duration5) {
    var bytes = new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      1,
      // creation_time
      0,
      0,
      0,
      2,
      // modification_time
      0,
      1,
      95,
      144,
      // timescale, 90,000 "ticks" per second
      (duration5 & 4278190080) >> 24,
      (duration5 & 16711680) >> 16,
      (duration5 & 65280) >> 8,
      duration5 & 255,
      // duration
      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 box(types.mvhd, bytes);
  };
  sdtp = function sdtp2(track) {
    var samples = track.samples || [], bytes = new Uint8Array(4 + samples.length), flags, i;
    for (i = 0; i < samples.length; i++) {
      flags = samples[i].flags;
      bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
    }
    return box(types.sdtp, bytes);
  };
  stbl = function stbl2(track) {
    return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  };
  (function() {
    var videoSample, audioSample;
    stsd = function stsd2(track) {
      return box(types.stsd, new Uint8Array([
        0,
        // version 0
        0,
        0,
        0,
        // flags
        0,
        0,
        0,
        1
      ]), track.type === "video" ? videoSample(track) : audioSample(track));
    };
    videoSample = function videoSample2(track) {
      var sps = track.sps || [], pps = track.pps || [], sequenceParameterSets = [], pictureParameterSets = [], i, avc1Box;
      for (i = 0; i < sps.length; i++) {
        sequenceParameterSets.push((sps[i].byteLength & 65280) >>> 8);
        sequenceParameterSets.push(sps[i].byteLength & 255);
        sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i]));
      }
      for (i = 0; i < pps.length; i++) {
        pictureParameterSets.push((pps[i].byteLength & 65280) >>> 8);
        pictureParameterSets.push(pps[i].byteLength & 255);
        pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
      }
      avc1Box = [types.avc1, new Uint8Array([
        0,
        0,
        0,
        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
        (track.width & 65280) >> 8,
        track.width & 255,
        // width
        (track.height & 65280) >> 8,
        track.height & 255,
        // height
        0,
        72,
        0,
        0,
        // horizresolution
        0,
        72,
        0,
        0,
        // vertresolution
        0,
        0,
        0,
        0,
        // reserved
        0,
        1,
        // frame_count
        19,
        118,
        105,
        100,
        101,
        111,
        106,
        115,
        45,
        99,
        111,
        110,
        116,
        114,
        105,
        98,
        45,
        104,
        108,
        115,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        // compressorname
        0,
        24,
        // depth = 24
        17,
        17
        // pre_defined = -1
      ]), box(types.avcC, new Uint8Array([
        1,
        // configurationVersion
        track.profileIdc,
        // AVCProfileIndication
        track.profileCompatibility,
        // profile_compatibility
        track.levelIdc,
        // AVCLevelIndication
        255
        // lengthSizeMinusOne, hard-coded to 4 bytes
      ].concat(
        [sps.length],
        // numOfSequenceParameterSets
        sequenceParameterSets,
        // "SPS"
        [pps.length],
        // numOfPictureParameterSets
        pictureParameterSets
        // "PPS"
      ))), box(types.btrt, new Uint8Array([
        0,
        28,
        156,
        128,
        // bufferSizeDB
        0,
        45,
        198,
        192,
        // maxBitrate
        0,
        45,
        198,
        192
        // avgBitrate
      ]))];
      if (track.sarRatio) {
        var hSpacing = track.sarRatio[0], vSpacing = track.sarRatio[1];
        avc1Box.push(box(types.pasp, new Uint8Array([(hSpacing & 4278190080) >> 24, (hSpacing & 16711680) >> 16, (hSpacing & 65280) >> 8, hSpacing & 255, (vSpacing & 4278190080) >> 24, (vSpacing & 16711680) >> 16, (vSpacing & 65280) >> 8, vSpacing & 255])));
      }
      return box.apply(null, avc1Box);
    };
    audioSample = function audioSample2(track) {
      return box(types.mp4a, new Uint8Array([
        // SampleEntry, ISO/IEC 14496-12
        0,
        0,
        0,
        0,
        0,
        0,
        // reserved
        0,
        1,
        // data_reference_index
        // AudioSampleEntry, ISO/IEC 14496-12
        0,
        0,
        0,
        0,
        // reserved
        0,
        0,
        0,
        0,
        // reserved
        (track.channelcount & 65280) >> 8,
        track.channelcount & 255,
        // channelcount
        (track.samplesize & 65280) >> 8,
        track.samplesize & 255,
        // samplesize
        0,
        0,
        // pre_defined
        0,
        0,
        // reserved
        (track.samplerate & 65280) >> 8,
        track.samplerate & 255,
        0,
        0
        // samplerate, 16.16
        // MP4AudioSampleEntry, ISO/IEC 14496-14
      ]), esds(track));
    };
  })();
  tkhd = function tkhd2(track) {
    var result = new Uint8Array([
      0,
      // version 0
      0,
      0,
      7,
      // flags
      0,
      0,
      0,
      0,
      // creation_time
      0,
      0,
      0,
      0,
      // modification_time
      (track.id & 4278190080) >> 24,
      (track.id & 16711680) >> 16,
      (track.id & 65280) >> 8,
      track.id & 255,
      // track_ID
      0,
      0,
      0,
      0,
      // reserved
      (track.duration & 4278190080) >> 24,
      (track.duration & 16711680) >> 16,
      (track.duration & 65280) >> 8,
      track.duration & 255,
      // duration
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // reserved
      0,
      0,
      // layer
      0,
      0,
      // alternate_group
      1,
      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
      (track.width & 65280) >> 8,
      track.width & 255,
      0,
      0,
      // width
      (track.height & 65280) >> 8,
      track.height & 255,
      0,
      0
      // height
    ]);
    return box(types.tkhd, result);
  };
  traf = function traf2(track) {
    var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
    trackFragmentHeader = box(types.tfhd, new Uint8Array([
      0,
      // version 0
      0,
      0,
      58,
      // flags
      (track.id & 4278190080) >> 24,
      (track.id & 16711680) >> 16,
      (track.id & 65280) >> 8,
      track.id & 255,
      // track_ID
      0,
      0,
      0,
      1,
      // sample_description_index
      0,
      0,
      0,
      0,
      // default_sample_duration
      0,
      0,
      0,
      0,
      // default_sample_size
      0,
      0,
      0,
      0
      // default_sample_flags
    ]));
    upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
    lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
    trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([
      1,
      // version 1
      0,
      0,
      0,
      // flags
      // baseMediaDecodeTime
      upperWordBaseMediaDecodeTime >>> 24 & 255,
      upperWordBaseMediaDecodeTime >>> 16 & 255,
      upperWordBaseMediaDecodeTime >>> 8 & 255,
      upperWordBaseMediaDecodeTime & 255,
      lowerWordBaseMediaDecodeTime >>> 24 & 255,
      lowerWordBaseMediaDecodeTime >>> 16 & 255,
      lowerWordBaseMediaDecodeTime >>> 8 & 255,
      lowerWordBaseMediaDecodeTime & 255
    ]));
    dataOffset = 32 + // tfhd
    20 + // tfdt
    8 + // traf header
    16 + // mfhd
    8 + // moof header
    8;
    if (track.type === "audio") {
      trackFragmentRun = trun$1(track, dataOffset);
      return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
    }
    sampleDependencyTable = sdtp(track);
    trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
    return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  };
  trak = function trak2(track) {
    track.duration = track.duration || 4294967295;
    return box(types.trak, tkhd(track), mdia(track));
  };
  trex = function trex2(track) {
    var result = new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      (track.id & 4278190080) >> 24,
      (track.id & 16711680) >> 16,
      (track.id & 65280) >> 8,
      track.id & 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
    ]);
    if (track.type !== "video") {
      result[result.length - 1] = 0;
    }
    return box(types.trex, result);
  };
  (function() {
    var audioTrun, videoTrun, trunHeader;
    trunHeader = function trunHeader2(samples, offset) {
      var durationPresent = 0, sizePresent = 0, flagsPresent = 0, compositionTimeOffset = 0;
      if (samples.length) {
        if (samples[0].duration !== void 0) {
          durationPresent = 1;
        }
        if (samples[0].size !== void 0) {
          sizePresent = 2;
        }
        if (samples[0].flags !== void 0) {
          flagsPresent = 4;
        }
        if (samples[0].compositionTimeOffset !== void 0) {
          compositionTimeOffset = 8;
        }
      }
      return [
        0,
        // version 0
        0,
        durationPresent | sizePresent | flagsPresent | compositionTimeOffset,
        1,
        // flags
        (samples.length & 4278190080) >>> 24,
        (samples.length & 16711680) >>> 16,
        (samples.length & 65280) >>> 8,
        samples.length & 255,
        // sample_count
        (offset & 4278190080) >>> 24,
        (offset & 16711680) >>> 16,
        (offset & 65280) >>> 8,
        offset & 255
        // data_offset
      ];
    };
    videoTrun = function videoTrun2(track, offset) {
      var bytesOffest, bytes, header, samples, sample, i;
      samples = track.samples || [];
      offset += 8 + 12 + 16 * samples.length;
      header = trunHeader(samples, offset);
      bytes = new Uint8Array(header.length + samples.length * 16);
      bytes.set(header);
      bytesOffest = header.length;
      for (i = 0; i < samples.length; i++) {
        sample = samples[i];
        bytes[bytesOffest++] = (sample.duration & 4278190080) >>> 24;
        bytes[bytesOffest++] = (sample.duration & 16711680) >>> 16;
        bytes[bytesOffest++] = (sample.duration & 65280) >>> 8;
        bytes[bytesOffest++] = sample.duration & 255;
        bytes[bytesOffest++] = (sample.size & 4278190080) >>> 24;
        bytes[bytesOffest++] = (sample.size & 16711680) >>> 16;
        bytes[bytesOffest++] = (sample.size & 65280) >>> 8;
        bytes[bytesOffest++] = sample.size & 255;
        bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
        bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
        bytes[bytesOffest++] = sample.flags.degradationPriority & 240 << 8;
        bytes[bytesOffest++] = sample.flags.degradationPriority & 15;
        bytes[bytesOffest++] = (sample.compositionTimeOffset & 4278190080) >>> 24;
        bytes[bytesOffest++] = (sample.compositionTimeOffset & 16711680) >>> 16;
        bytes[bytesOffest++] = (sample.compositionTimeOffset & 65280) >>> 8;
        bytes[bytesOffest++] = sample.compositionTimeOffset & 255;
      }
      return box(types.trun, bytes);
    };
    audioTrun = function audioTrun2(track, offset) {
      var bytes, bytesOffest, header, samples, sample, i;
      samples = track.samples || [];
      offset += 8 + 12 + 8 * samples.length;
      header = trunHeader(samples, offset);
      bytes = new Uint8Array(header.length + samples.length * 8);
      bytes.set(header);
      bytesOffest = header.length;
      for (i = 0; i < samples.length; i++) {
        sample = samples[i];
        bytes[bytesOffest++] = (sample.duration & 4278190080) >>> 24;
        bytes[bytesOffest++] = (sample.duration & 16711680) >>> 16;
        bytes[bytesOffest++] = (sample.duration & 65280) >>> 8;
        bytes[bytesOffest++] = sample.duration & 255;
        bytes[bytesOffest++] = (sample.size & 4278190080) >>> 24;
        bytes[bytesOffest++] = (sample.size & 16711680) >>> 16;
        bytes[bytesOffest++] = (sample.size & 65280) >>> 8;
        bytes[bytesOffest++] = sample.size & 255;
      }
      return box(types.trun, bytes);
    };
    trun$1 = function trun2(track, offset) {
      if (track.type === "audio") {
        return audioTrun(track, offset);
      }
      return videoTrun(track, offset);
    };
  })();
  var mp4Generator = {
    ftyp,
    mdat,
    moof,
    moov,
    initSegment: function initSegment(tracks) {
      var fileType = ftyp(), movie = moov(tracks), result;
      result = new Uint8Array(fileType.byteLength + movie.byteLength);
      result.set(fileType);
      result.set(movie, fileType.byteLength);
      return result;
    }
  };
  var groupNalsIntoFrames = function groupNalsIntoFrames2(nalUnits) {
    var i, currentNal, currentFrame = [], frames = [];
    frames.byteLength = 0;
    frames.nalCount = 0;
    frames.duration = 0;
    currentFrame.byteLength = 0;
    for (i = 0; i < nalUnits.length; i++) {
      currentNal = nalUnits[i];
      if (currentNal.nalUnitType === "access_unit_delimiter_rbsp") {
        if (currentFrame.length) {
          currentFrame.duration = currentNal.dts - currentFrame.dts;
          frames.byteLength += currentFrame.byteLength;
          frames.nalCount += currentFrame.length;
          frames.duration += currentFrame.duration;
          frames.push(currentFrame);
        }
        currentFrame = [currentNal];
        currentFrame.byteLength = currentNal.data.byteLength;
        currentFrame.pts = currentNal.pts;
        currentFrame.dts = currentNal.dts;
      } else {
        if (currentNal.nalUnitType === "slice_layer_without_partitioning_rbsp_idr") {
          currentFrame.keyFrame = true;
        }
        currentFrame.duration = currentNal.dts - currentFrame.dts;
        currentFrame.byteLength += currentNal.data.byteLength;
        currentFrame.push(currentNal);
      }
    }
    if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
      currentFrame.duration = frames[frames.length - 1].duration;
    }
    frames.byteLength += currentFrame.byteLength;
    frames.nalCount += currentFrame.length;
    frames.duration += currentFrame.duration;
    frames.push(currentFrame);
    return frames;
  };
  var groupFramesIntoGops = function groupFramesIntoGops2(frames) {
    var i, currentFrame, currentGop = [], gops = [];
    currentGop.byteLength = 0;
    currentGop.nalCount = 0;
    currentGop.duration = 0;
    currentGop.pts = frames[0].pts;
    currentGop.dts = frames[0].dts;
    gops.byteLength = 0;
    gops.nalCount = 0;
    gops.duration = 0;
    gops.pts = frames[0].pts;
    gops.dts = frames[0].dts;
    for (i = 0; i < frames.length; i++) {
      currentFrame = frames[i];
      if (currentFrame.keyFrame) {
        if (currentGop.length) {
          gops.push(currentGop);
          gops.byteLength += currentGop.byteLength;
          gops.nalCount += currentGop.nalCount;
          gops.duration += currentGop.duration;
        }
        currentGop = [currentFrame];
        currentGop.nalCount = currentFrame.length;
        currentGop.byteLength = currentFrame.byteLength;
        currentGop.pts = currentFrame.pts;
        currentGop.dts = currentFrame.dts;
        currentGop.duration = currentFrame.duration;
      } else {
        currentGop.duration += currentFrame.duration;
        currentGop.nalCount += currentFrame.length;
        currentGop.byteLength += currentFrame.byteLength;
        currentGop.push(currentFrame);
      }
    }
    if (gops.length && currentGop.duration <= 0) {
      currentGop.duration = gops[gops.length - 1].duration;
    }
    gops.byteLength += currentGop.byteLength;
    gops.nalCount += currentGop.nalCount;
    gops.duration += currentGop.duration;
    gops.push(currentGop);
    return gops;
  };
  var extendFirstKeyFrame = function extendFirstKeyFrame2(gops) {
    var currentGop;
    if (!gops[0][0].keyFrame && gops.length > 1) {
      currentGop = gops.shift();
      gops.byteLength -= currentGop.byteLength;
      gops.nalCount -= currentGop.nalCount;
      gops[0][0].dts = currentGop.dts;
      gops[0][0].pts = currentGop.pts;
      gops[0][0].duration += currentGop.duration;
    }
    return gops;
  };
  var createDefaultSample = function createDefaultSample2() {
    return {
      size: 0,
      flags: {
        isLeading: 0,
        dependsOn: 1,
        isDependedOn: 0,
        hasRedundancy: 0,
        degradationPriority: 0,
        isNonSyncSample: 1
      }
    };
  };
  var sampleForFrame = function sampleForFrame2(frame, dataOffset) {
    var sample = createDefaultSample();
    sample.dataOffset = dataOffset;
    sample.compositionTimeOffset = frame.pts - frame.dts;
    sample.duration = frame.duration;
    sample.size = 4 * frame.length;
    sample.size += frame.byteLength;
    if (frame.keyFrame) {
      sample.flags.dependsOn = 2;
      sample.flags.isNonSyncSample = 0;
    }
    return sample;
  };
  var generateSampleTable$1 = function generateSampleTable2(gops, baseDataOffset) {
    var h, i, sample, currentGop, currentFrame, dataOffset = baseDataOffset || 0, samples = [];
    for (h = 0; h < gops.length; h++) {
      currentGop = gops[h];
      for (i = 0; i < currentGop.length; i++) {
        currentFrame = currentGop[i];
        sample = sampleForFrame(currentFrame, dataOffset);
        dataOffset += sample.size;
        samples.push(sample);
      }
    }
    return samples;
  };
  var concatenateNalData = function concatenateNalData2(gops) {
    var h, i, j, currentGop, currentFrame, currentNal, dataOffset = 0, nalsByteLength = gops.byteLength, numberOfNals = gops.nalCount, totalByteLength = nalsByteLength + 4 * numberOfNals, data = new Uint8Array(totalByteLength), view2 = new DataView(data.buffer);
    for (h = 0; h < gops.length; h++) {
      currentGop = gops[h];
      for (i = 0; i < currentGop.length; i++) {
        currentFrame = currentGop[i];
        for (j = 0; j < currentFrame.length; j++) {
          currentNal = currentFrame[j];
          view2.setUint32(dataOffset, currentNal.data.byteLength);
          dataOffset += 4;
          data.set(currentNal.data, dataOffset);
          dataOffset += currentNal.data.byteLength;
        }
      }
    }
    return data;
  };
  var generateSampleTableForFrame = function generateSampleTableForFrame2(frame, baseDataOffset) {
    var sample, dataOffset = baseDataOffset || 0, samples = [];
    sample = sampleForFrame(frame, dataOffset);
    samples.push(sample);
    return samples;
  };
  var concatenateNalDataForFrame = function concatenateNalDataForFrame2(frame) {
    var i, currentNal, dataOffset = 0, nalsByteLength = frame.byteLength, numberOfNals = frame.length, totalByteLength = nalsByteLength + 4 * numberOfNals, data = new Uint8Array(totalByteLength), view2 = new DataView(data.buffer);
    for (i = 0; i < frame.length; i++) {
      currentNal = frame[i];
      view2.setUint32(dataOffset, currentNal.data.byteLength);
      dataOffset += 4;
      data.set(currentNal.data, dataOffset);
      dataOffset += currentNal.data.byteLength;
    }
    return data;
  };
  var frameUtils = {
    groupNalsIntoFrames,
    groupFramesIntoGops,
    extendFirstKeyFrame,
    generateSampleTable: generateSampleTable$1,
    concatenateNalData,
    generateSampleTableForFrame,
    concatenateNalDataForFrame
  };
  var highPrefix = [33, 16, 5, 32, 164, 27];
  var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  var zeroFill = function zeroFill2(count) {
    var a = [];
    while (count--) {
      a.push(0);
    }
    return a;
  };
  var makeTable = function makeTable2(metaTable) {
    return Object.keys(metaTable).reduce(function(obj, key) {
      obj[key] = new Uint8Array(metaTable[key].reduce(function(arr, part) {
        return arr.concat(part);
      }, []));
      return obj;
    }, {});
  };
  var silence;
  var silence_1 = function silence_12() {
    if (!silence) {
      var coneOfSilence = {
        96e3: [highPrefix, [227, 64], zeroFill(154), [56]],
        88200: [highPrefix, [231], zeroFill(170), [56]],
        64e3: [highPrefix, [248, 192], zeroFill(240), [56]],
        48e3: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
        44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
        32e3: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
        24e3: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
        16e3: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
        12e3: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
        11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
        8e3: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
      };
      silence = makeTable(coneOfSilence);
    }
    return silence;
  };
  var ONE_SECOND_IN_TS$4 = 9e4, secondsToVideoTs, secondsToAudioTs, videoTsToSeconds, audioTsToSeconds, audioTsToVideoTs, videoTsToAudioTs, metadataTsToSeconds;
  secondsToVideoTs = function secondsToVideoTs2(seconds) {
    return seconds * ONE_SECOND_IN_TS$4;
  };
  secondsToAudioTs = function secondsToAudioTs2(seconds, sampleRate) {
    return seconds * sampleRate;
  };
  videoTsToSeconds = function videoTsToSeconds2(timestamp) {
    return timestamp / ONE_SECOND_IN_TS$4;
  };
  audioTsToSeconds = function audioTsToSeconds2(timestamp, sampleRate) {
    return timestamp / sampleRate;
  };
  audioTsToVideoTs = function audioTsToVideoTs2(timestamp, sampleRate) {
    return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  };
  videoTsToAudioTs = function videoTsToAudioTs2(timestamp, sampleRate) {
    return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  };
  metadataTsToSeconds = function metadataTsToSeconds2(timestamp, timelineStartPts, keepOriginalTimestamps) {
    return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  };
  var clock = {
    ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
    secondsToVideoTs,
    secondsToAudioTs,
    videoTsToSeconds,
    audioTsToSeconds,
    audioTsToVideoTs,
    videoTsToAudioTs,
    metadataTsToSeconds
  };
  var sumFrameByteLengths = function sumFrameByteLengths2(array) {
    var i, currentObj, sum = 0;
    for (i = 0; i < array.length; i++) {
      currentObj = array[i];
      sum += currentObj.data.byteLength;
    }
    return sum;
  };
  var prefixWithSilence = function prefixWithSilence2(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
    var baseMediaDecodeTimeTs, frameDuration = 0, audioGapDuration = 0, audioFillFrameCount = 0, audioFillDuration = 0, silentFrame, i, firstFrame;
    if (!frames.length) {
      return;
    }
    baseMediaDecodeTimeTs = clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate);
    frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
    if (audioAppendStartTs && videoBaseMediaDecodeTime) {
      audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime);
      audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
      audioFillDuration = audioFillFrameCount * frameDuration;
    }
    if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
      return;
    }
    silentFrame = silence_1()[track.samplerate];
    if (!silentFrame) {
      silentFrame = frames[0].data;
    }
    for (i = 0; i < audioFillFrameCount; i++) {
      firstFrame = frames[0];
      frames.splice(0, 0, {
        data: silentFrame,
        dts: firstFrame.dts - frameDuration,
        pts: firstFrame.pts - frameDuration
      });
    }
    track.baseMediaDecodeTime -= Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
    return audioFillDuration;
  };
  var trimAdtsFramesByEarliestDts = function trimAdtsFramesByEarliestDts2(adtsFrames, track, earliestAllowedDts) {
    if (track.minSegmentDts >= earliestAllowedDts) {
      return adtsFrames;
    }
    track.minSegmentDts = Infinity;
    return adtsFrames.filter(function(currentFrame) {
      if (currentFrame.dts >= earliestAllowedDts) {
        track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
        track.minSegmentPts = track.minSegmentDts;
        return true;
      }
      return false;
    });
  };
  var generateSampleTable = function generateSampleTable2(frames) {
    var i, currentFrame, samples = [];
    for (i = 0; i < frames.length; i++) {
      currentFrame = frames[i];
      samples.push({
        size: currentFrame.data.byteLength,
        duration: 1024
        // For AAC audio, all samples contain 1024 samples
      });
    }
    return samples;
  };
  var concatenateFrameData = function concatenateFrameData2(frames) {
    var i, currentFrame, dataOffset = 0, data = new Uint8Array(sumFrameByteLengths(frames));
    for (i = 0; i < frames.length; i++) {
      currentFrame = frames[i];
      data.set(currentFrame.data, dataOffset);
      dataOffset += currentFrame.data.byteLength;
    }
    return data;
  };
  var audioFrameUtils = {
    prefixWithSilence,
    trimAdtsFramesByEarliestDts,
    generateSampleTable,
    concatenateFrameData
  };
  var ONE_SECOND_IN_TS$3 = clock.ONE_SECOND_IN_TS;
  var collectDtsInfo = function collectDtsInfo2(track, data) {
    if (typeof data.pts === "number") {
      if (track.timelineStartInfo.pts === void 0) {
        track.timelineStartInfo.pts = data.pts;
      }
      if (track.minSegmentPts === void 0) {
        track.minSegmentPts = data.pts;
      } else {
        track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
      }
      if (track.maxSegmentPts === void 0) {
        track.maxSegmentPts = data.pts;
      } else {
        track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
      }
    }
    if (typeof data.dts === "number") {
      if (track.timelineStartInfo.dts === void 0) {
        track.timelineStartInfo.dts = data.dts;
      }
      if (track.minSegmentDts === void 0) {
        track.minSegmentDts = data.dts;
      } else {
        track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
      }
      if (track.maxSegmentDts === void 0) {
        track.maxSegmentDts = data.dts;
      } else {
        track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
      }
    }
  };
  var clearDtsInfo = function clearDtsInfo2(track) {
    delete track.minSegmentDts;
    delete track.maxSegmentDts;
    delete track.minSegmentPts;
    delete track.maxSegmentPts;
  };
  var calculateTrackBaseMediaDecodeTime = function calculateTrackBaseMediaDecodeTime2(track, keepOriginalTimestamps) {
    var baseMediaDecodeTime, scale, minSegmentDts = track.minSegmentDts;
    if (!keepOriginalTimestamps) {
      minSegmentDts -= track.timelineStartInfo.dts;
    }
    baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime;
    baseMediaDecodeTime += minSegmentDts;
    baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
    if (track.type === "audio") {
      scale = track.samplerate / ONE_SECOND_IN_TS$3;
      baseMediaDecodeTime *= scale;
      baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
    }
    return baseMediaDecodeTime;
  };
  var trackDecodeInfo = {
    clearDtsInfo,
    calculateTrackBaseMediaDecodeTime,
    collectDtsInfo
  };
  var USER_DATA_REGISTERED_ITU_T_T35 = 4, RBSP_TRAILING_BITS = 128;
  var parseSei = function parseSei2(bytes) {
    var i = 0, result = {
      payloadType: -1,
      payloadSize: 0
    }, payloadType = 0, payloadSize = 0;
    while (i < bytes.byteLength) {
      if (bytes[i] === RBSP_TRAILING_BITS) {
        break;
      }
      while (bytes[i] === 255) {
        payloadType += 255;
        i++;
      }
      payloadType += bytes[i++];
      while (bytes[i] === 255) {
        payloadSize += 255;
        i++;
      }
      payloadSize += bytes[i++];
      if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
        var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
        if (userIdentifier === "GA94") {
          result.payloadType = payloadType;
          result.payloadSize = payloadSize;
          result.payload = bytes.subarray(i, i + payloadSize);
          break;
        } else {
          result.payload = void 0;
        }
      }
      i += payloadSize;
      payloadType = 0;
      payloadSize = 0;
    }
    return result;
  };
  var parseUserData = function parseUserData2(sei) {
    if (sei.payload[0] !== 181) {
      return null;
    }
    if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
      return null;
    }
    if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== "GA94") {
      return null;
    }
    if (sei.payload[7] !== 3) {
      return null;
    }
    return sei.payload.subarray(8, sei.payload.length - 1);
  };
  var parseCaptionPackets = function parseCaptionPackets2(pts, userData) {
    var results = [], i, count, offset, data;
    if (!(userData[0] & 64)) {
      return results;
    }
    count = userData[0] & 31;
    for (i = 0; i < count; i++) {
      offset = i * 3;
      data = {
        type: userData[offset + 2] & 3,
        pts
      };
      if (userData[offset + 2] & 4) {
        data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
        results.push(data);
      }
    }
    return results;
  };
  var discardEmulationPreventionBytes$1 = function discardEmulationPreventionBytes4(data) {
    var length = data.byteLength, emulationPreventionBytesPositions = [], i = 1, newLength, newData;
    while (i < length - 2) {
      if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 3) {
        emulationPreventionBytesPositions.push(i + 2);
        i += 2;
      } else {
        i++;
      }
    }
    if (emulationPreventionBytesPositions.length === 0) {
      return data;
    }
    newLength = length - emulationPreventionBytesPositions.length;
    newData = new Uint8Array(newLength);
    var sourceIndex = 0;
    for (i = 0; i < newLength; sourceIndex++, i++) {
      if (sourceIndex === emulationPreventionBytesPositions[0]) {
        sourceIndex++;
        emulationPreventionBytesPositions.shift();
      }
      newData[i] = data[sourceIndex];
    }
    return newData;
  };
  var captionPacketParser = {
    parseSei,
    parseUserData,
    parseCaptionPackets,
    discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
    USER_DATA_REGISTERED_ITU_T_T35
  };
  var CaptionStream$1 = function CaptionStream2(options) {
    options = options || {};
    CaptionStream2.prototype.init.call(this);
    this.parse708captions_ = typeof options.parse708captions === "boolean" ? options.parse708captions : true;
    this.captionPackets_ = [];
    this.ccStreams_ = [
      new Cea608Stream(0, 0),
       
      new Cea608Stream(0, 1),
       
      new Cea608Stream(1, 0),
       
      new Cea608Stream(1, 1)
       
    ];
    if (this.parse708captions_) {
      this.cc708Stream_ = new Cea708Stream({
        captionServices: options.captionServices
      });
    }
    this.reset();
    this.ccStreams_.forEach(function(cc) {
      cc.on("data", this.trigger.bind(this, "data"));
      cc.on("partialdone", this.trigger.bind(this, "partialdone"));
      cc.on("done", this.trigger.bind(this, "done"));
    }, this);
    if (this.parse708captions_) {
      this.cc708Stream_.on("data", this.trigger.bind(this, "data"));
      this.cc708Stream_.on("partialdone", this.trigger.bind(this, "partialdone"));
      this.cc708Stream_.on("done", this.trigger.bind(this, "done"));
    }
  };
  CaptionStream$1.prototype = new stream();
  CaptionStream$1.prototype.push = function(event) {
    var sei, userData, newCaptionPackets;
    if (event.nalUnitType !== "sei_rbsp") {
      return;
    }
    sei = captionPacketParser.parseSei(event.escapedRBSP);
    if (!sei.payload) {
      return;
    }
    if (sei.payloadType !== captionPacketParser.USER_DATA_REGISTERED_ITU_T_T35) {
      return;
    }
    userData = captionPacketParser.parseUserData(sei);
    if (!userData) {
      return;
    }
    if (event.dts < this.latestDts_) {
      this.ignoreNextEqualDts_ = true;
      return;
    } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
      this.numSameDts_--;
      if (!this.numSameDts_) {
        this.ignoreNextEqualDts_ = false;
      }
      return;
    }
    newCaptionPackets = captionPacketParser.parseCaptionPackets(event.pts, userData);
    this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
    if (this.latestDts_ !== event.dts) {
      this.numSameDts_ = 0;
    }
    this.numSameDts_++;
    this.latestDts_ = event.dts;
  };
  CaptionStream$1.prototype.flushCCStreams = function(flushType) {
    this.ccStreams_.forEach(function(cc) {
      return flushType === "flush" ? cc.flush() : cc.partialFlush();
    }, this);
  };
  CaptionStream$1.prototype.flushStream = function(flushType) {
    if (!this.captionPackets_.length) {
      this.flushCCStreams(flushType);
      return;
    }
    this.captionPackets_.forEach(function(elem, idx) {
      elem.presortIndex = idx;
    });
    this.captionPackets_.sort(function(a, b) {
      if (a.pts === b.pts) {
        return a.presortIndex - b.presortIndex;
      }
      return a.pts - b.pts;
    });
    this.captionPackets_.forEach(function(packet) {
      if (packet.type < 2) {
        this.dispatchCea608Packet(packet);
      } else {
        this.dispatchCea708Packet(packet);
      }
    }, this);
    this.captionPackets_.length = 0;
    this.flushCCStreams(flushType);
  };
  CaptionStream$1.prototype.flush = function() {
    return this.flushStream("flush");
  };
  CaptionStream$1.prototype.partialFlush = function() {
    return this.flushStream("partialFlush");
  };
  CaptionStream$1.prototype.reset = function() {
    this.latestDts_ = null;
    this.ignoreNextEqualDts_ = false;
    this.numSameDts_ = 0;
    this.activeCea608Channel_ = [null, null];
    this.ccStreams_.forEach(function(ccStream) {
      ccStream.reset();
    });
  };
  CaptionStream$1.prototype.dispatchCea608Packet = function(packet) {
    if (this.setsTextOrXDSActive(packet)) {
      this.activeCea608Channel_[packet.type] = null;
    } else if (this.setsChannel1Active(packet)) {
      this.activeCea608Channel_[packet.type] = 0;
    } else if (this.setsChannel2Active(packet)) {
      this.activeCea608Channel_[packet.type] = 1;
    }
    if (this.activeCea608Channel_[packet.type] === null) {
      return;
    }
    this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  };
  CaptionStream$1.prototype.setsChannel1Active = function(packet) {
    return (packet.ccData & 30720) === 4096;
  };
  CaptionStream$1.prototype.setsChannel2Active = function(packet) {
    return (packet.ccData & 30720) === 6144;
  };
  CaptionStream$1.prototype.setsTextOrXDSActive = function(packet) {
    return (packet.ccData & 28928) === 256 || (packet.ccData & 30974) === 4138 || (packet.ccData & 30974) === 6186;
  };
  CaptionStream$1.prototype.dispatchCea708Packet = function(packet) {
    if (this.parse708captions_) {
      this.cc708Stream_.push(packet);
    }
  };
  var CHARACTER_TRANSLATION_708 = {
    127: 9834,
    // ♪
    4128: 32,
    // Transparent Space
    4129: 160,
    // Nob-breaking Transparent Space
    4133: 8230,
    // …
    4138: 352,
    // Š
    4140: 338,
    // Œ
    4144: 9608,
    // █
    4145: 8216,
    // ‘
    4146: 8217,
    // ’
    4147: 8220,
    // “
    4148: 8221,
    // ”
    4149: 8226,
    // •
    4153: 8482,
    // ™
    4154: 353,
    // š
    4156: 339,
    // œ
    4157: 8480,
    // ℠
    4159: 376,
    // Ÿ
    4214: 8539,
    // ⅛
    4215: 8540,
    // ⅜
    4216: 8541,
    // ⅝
    4217: 8542,
    // ⅞
    4218: 9168,
    // ⏐
    4219: 9124,
    // ⎤
    4220: 9123,
    // ⎣
    4221: 9135,
    // ⎯
    4222: 9126,
    // ⎦
    4223: 9121,
    // ⎡
    4256: 12600
    // ㄸ (CC char)
  };
  var get708CharFromCode = function get708CharFromCode2(code) {
    var newCode = CHARACTER_TRANSLATION_708[code] || code;
    if (code & 4096 && code === newCode) {
      return "";
    }
    return String.fromCharCode(newCode);
  };
  var within708TextBlock = function within708TextBlock2(b) {
    return 32 <= b && b <= 127 || 160 <= b && b <= 255;
  };
  var Cea708Window = function Cea708Window2(windowNum) {
    this.windowNum = windowNum;
    this.reset();
  };
  Cea708Window.prototype.reset = function() {
    this.clearText();
    this.pendingNewLine = false;
    this.winAttr = {};
    this.penAttr = {};
    this.penLoc = {};
    this.penColor = {};
    this.visible = 0;
    this.rowLock = 0;
    this.columnLock = 0;
    this.priority = 0;
    this.relativePositioning = 0;
    this.anchorVertical = 0;
    this.anchorHorizontal = 0;
    this.anchorPoint = 0;
    this.rowCount = 1;
    this.virtualRowCount = this.rowCount + 1;
    this.columnCount = 41;
    this.windowStyle = 0;
    this.penStyle = 0;
  };
  Cea708Window.prototype.getText = function() {
    return this.rows.join("\n");
  };
  Cea708Window.prototype.clearText = function() {
    this.rows = [""];
    this.rowIdx = 0;
  };
  Cea708Window.prototype.newLine = function(pts) {
    if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === "function") {
      this.beforeRowOverflow(pts);
    }
    if (this.rows.length > 0) {
      this.rows.push("");
      this.rowIdx++;
    }
    while (this.rows.length > this.virtualRowCount) {
      this.rows.shift();
      this.rowIdx--;
    }
  };
  Cea708Window.prototype.isEmpty = function() {
    if (this.rows.length === 0) {
      return true;
    } else if (this.rows.length === 1) {
      return this.rows[0] === "";
    }
    return false;
  };
  Cea708Window.prototype.addText = function(text) {
    this.rows[this.rowIdx] += text;
  };
  Cea708Window.prototype.backspace = function() {
    if (!this.isEmpty()) {
      var row = this.rows[this.rowIdx];
      this.rows[this.rowIdx] = row.substr(0, row.length - 1);
    }
  };
  var Cea708Service = function Cea708Service2(serviceNum, encoding, stream2) {
    this.serviceNum = serviceNum;
    this.text = "";
    this.currentWindow = new Cea708Window(-1);
    this.windows = [];
    this.stream = stream2;
    if (typeof encoding === "string") {
      this.createTextDecoder(encoding);
    }
  };
  Cea708Service.prototype.init = function(pts, beforeRowOverflow) {
    this.startPts = pts;
    for (var win2 = 0; win2 < 8; win2++) {
      this.windows[win2] = new Cea708Window(win2);
      if (typeof beforeRowOverflow === "function") {
        this.windows[win2].beforeRowOverflow = beforeRowOverflow;
      }
    }
  };
  Cea708Service.prototype.setCurrentWindow = function(windowNum) {
    this.currentWindow = this.windows[windowNum];
  };
  Cea708Service.prototype.createTextDecoder = function(encoding) {
    if (typeof TextDecoder === "undefined") {
      this.stream.trigger("log", {
        level: "warn",
        message: "The `encoding` option is unsupported without TextDecoder support"
      });
    } else {
      try {
        this.textDecoder_ = new TextDecoder(encoding);
      } catch (error) {
        this.stream.trigger("log", {
          level: "warn",
          message: "TextDecoder could not be created with " + encoding + " encoding. " + error
        });
      }
    }
  };
  var Cea708Stream = function Cea708Stream2(options) {
    options = options || {};
    Cea708Stream2.prototype.init.call(this);
    var self2 = this;
    var captionServices = options.captionServices || {};
    var captionServiceEncodings = {};
    var serviceProps;
    Object.keys(captionServices).forEach(function(serviceName) {
      serviceProps = captionServices[serviceName];
      if (/^SERVICE/.test(serviceName)) {
        captionServiceEncodings[serviceName] = serviceProps.encoding;
      }
    });
    this.serviceEncodings = captionServiceEncodings;
    this.current708Packet = null;
    this.services = {};
    this.push = function(packet) {
      if (packet.type === 3) {
        self2.new708Packet();
        self2.add708Bytes(packet);
      } else {
        if (self2.current708Packet === null) {
          self2.new708Packet();
        }
        self2.add708Bytes(packet);
      }
    };
  };
  Cea708Stream.prototype = new stream();
  Cea708Stream.prototype.new708Packet = function() {
    if (this.current708Packet !== null) {
      this.push708Packet();
    }
    this.current708Packet = {
      data: [],
      ptsVals: []
    };
  };
  Cea708Stream.prototype.add708Bytes = function(packet) {
    var data = packet.ccData;
    var byte0 = data >>> 8;
    var byte1 = data & 255;
    this.current708Packet.ptsVals.push(packet.pts);
    this.current708Packet.data.push(byte0);
    this.current708Packet.data.push(byte1);
  };
  Cea708Stream.prototype.push708Packet = function() {
    var packet708 = this.current708Packet;
    var packetData = packet708.data;
    var serviceNum = null;
    var blockSize = null;
    var i = 0;
    var b = packetData[i++];
    packet708.seq = b >> 6;
    packet708.sizeCode = b & 63;
    for (; i < packetData.length; i++) {
      b = packetData[i++];
      serviceNum = b >> 5;
      blockSize = b & 31;
      if (serviceNum === 7 && blockSize > 0) {
        b = packetData[i++];
        serviceNum = b;
      }
      this.pushServiceBlock(serviceNum, i, blockSize);
      if (blockSize > 0) {
        i += blockSize - 1;
      }
    }
  };
  Cea708Stream.prototype.pushServiceBlock = function(serviceNum, start2, size) {
    var b;
    var i = start2;
    var packetData = this.current708Packet.data;
    var service = this.services[serviceNum];
    if (!service) {
      service = this.initService(serviceNum, i);
    }
    for (; i < start2 + size && i < packetData.length; i++) {
      b = packetData[i];
      if (within708TextBlock(b)) {
        i = this.handleText(i, service);
      } else if (b === 24) {
        i = this.multiByteCharacter(i, service);
      } else if (b === 16) {
        i = this.extendedCommands(i, service);
      } else if (128 <= b && b <= 135) {
        i = this.setCurrentWindow(i, service);
      } else if (152 <= b && b <= 159) {
        i = this.defineWindow(i, service);
      } else if (b === 136) {
        i = this.clearWindows(i, service);
      } else if (b === 140) {
        i = this.deleteWindows(i, service);
      } else if (b === 137) {
        i = this.displayWindows(i, service);
      } else if (b === 138) {
        i = this.hideWindows(i, service);
      } else if (b === 139) {
        i = this.toggleWindows(i, service);
      } else if (b === 151) {
        i = this.setWindowAttributes(i, service);
      } else if (b === 144) {
        i = this.setPenAttributes(i, service);
      } else if (b === 145) {
        i = this.setPenColor(i, service);
      } else if (b === 146) {
        i = this.setPenLocation(i, service);
      } else if (b === 143) {
        service = this.reset(i, service);
      } else if (b === 8) {
        service.currentWindow.backspace();
      } else if (b === 12) {
        service.currentWindow.clearText();
      } else if (b === 13) {
        service.currentWindow.pendingNewLine = true;
      } else if (b === 14) {
        service.currentWindow.clearText();
      } else if (b === 141) {
        i++;
      } else ;
    }
  };
  Cea708Stream.prototype.extendedCommands = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[++i];
    if (within708TextBlock(b)) {
      i = this.handleText(i, service, {
        isExtended: true
      });
    }
    return i;
  };
  Cea708Stream.prototype.getPts = function(byteIndex) {
    return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  };
  Cea708Stream.prototype.initService = function(serviceNum, i) {
    var serviceName = "SERVICE" + serviceNum;
    var self2 = this;
    var serviceName;
    var encoding;
    if (serviceName in this.serviceEncodings) {
      encoding = this.serviceEncodings[serviceName];
    }
    this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self2);
    this.services[serviceNum].init(this.getPts(i), function(pts) {
      self2.flushDisplayed(pts, self2.services[serviceNum]);
    });
    return this.services[serviceNum];
  };
  Cea708Stream.prototype.handleText = function(i, service, options) {
    var isExtended = options && options.isExtended;
    var isMultiByte = options && options.isMultiByte;
    var packetData = this.current708Packet.data;
    var extended = isExtended ? 4096 : 0;
    var currentByte = packetData[i];
    var nextByte = packetData[i + 1];
    var win2 = service.currentWindow;
    var _char;
    var charCodeArray;
    if (service.textDecoder_ && !isExtended) {
      if (isMultiByte) {
        charCodeArray = [currentByte, nextByte];
        i++;
      } else {
        charCodeArray = [currentByte];
      }
      _char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
    } else {
      _char = get708CharFromCode(extended | currentByte);
    }
    if (win2.pendingNewLine && !win2.isEmpty()) {
      win2.newLine(this.getPts(i));
    }
    win2.pendingNewLine = false;
    win2.addText(_char);
    return i;
  };
  Cea708Stream.prototype.multiByteCharacter = function(i, service) {
    var packetData = this.current708Packet.data;
    var firstByte = packetData[i + 1];
    var secondByte = packetData[i + 2];
    if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
      i = this.handleText(++i, service, {
        isMultiByte: true
      });
    }
    return i;
  };
  Cea708Stream.prototype.setCurrentWindow = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[i];
    var windowNum = b & 7;
    service.setCurrentWindow(windowNum);
    return i;
  };
  Cea708Stream.prototype.defineWindow = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[i];
    var windowNum = b & 7;
    service.setCurrentWindow(windowNum);
    var win2 = service.currentWindow;
    b = packetData[++i];
    win2.visible = (b & 32) >> 5;
    win2.rowLock = (b & 16) >> 4;
    win2.columnLock = (b & 8) >> 3;
    win2.priority = b & 7;
    b = packetData[++i];
    win2.relativePositioning = (b & 128) >> 7;
    win2.anchorVertical = b & 127;
    b = packetData[++i];
    win2.anchorHorizontal = b;
    b = packetData[++i];
    win2.anchorPoint = (b & 240) >> 4;
    win2.rowCount = b & 15;
    b = packetData[++i];
    win2.columnCount = b & 63;
    b = packetData[++i];
    win2.windowStyle = (b & 56) >> 3;
    win2.penStyle = b & 7;
    win2.virtualRowCount = win2.rowCount + 1;
    return i;
  };
  Cea708Stream.prototype.setWindowAttributes = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[i];
    var winAttr = service.currentWindow.winAttr;
    b = packetData[++i];
    winAttr.fillOpacity = (b & 192) >> 6;
    winAttr.fillRed = (b & 48) >> 4;
    winAttr.fillGreen = (b & 12) >> 2;
    winAttr.fillBlue = b & 3;
    b = packetData[++i];
    winAttr.borderType = (b & 192) >> 6;
    winAttr.borderRed = (b & 48) >> 4;
    winAttr.borderGreen = (b & 12) >> 2;
    winAttr.borderBlue = b & 3;
    b = packetData[++i];
    winAttr.borderType += (b & 128) >> 5;
    winAttr.wordWrap = (b & 64) >> 6;
    winAttr.printDirection = (b & 48) >> 4;
    winAttr.scrollDirection = (b & 12) >> 2;
    winAttr.justify = b & 3;
    b = packetData[++i];
    winAttr.effectSpeed = (b & 240) >> 4;
    winAttr.effectDirection = (b & 12) >> 2;
    winAttr.displayEffect = b & 3;
    return i;
  };
  Cea708Stream.prototype.flushDisplayed = function(pts, service) {
    var displayedText = [];
    for (var winId = 0; winId < 8; winId++) {
      if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
        displayedText.push(service.windows[winId].getText());
      }
    }
    service.endPts = pts;
    service.text = displayedText.join("\n\n");
    this.pushCaption(service);
    service.startPts = pts;
  };
  Cea708Stream.prototype.pushCaption = function(service) {
    if (service.text !== "") {
      this.trigger("data", {
        startPts: service.startPts,
        endPts: service.endPts,
        text: service.text,
        stream: "cc708_" + service.serviceNum
      });
      service.text = "";
      service.startPts = service.endPts;
    }
  };
  Cea708Stream.prototype.displayWindows = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[++i];
    var pts = this.getPts(i);
    this.flushDisplayed(pts, service);
    for (var winId = 0; winId < 8; winId++) {
      if (b & 1 << winId) {
        service.windows[winId].visible = 1;
      }
    }
    return i;
  };
  Cea708Stream.prototype.hideWindows = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[++i];
    var pts = this.getPts(i);
    this.flushDisplayed(pts, service);
    for (var winId = 0; winId < 8; winId++) {
      if (b & 1 << winId) {
        service.windows[winId].visible = 0;
      }
    }
    return i;
  };
  Cea708Stream.prototype.toggleWindows = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[++i];
    var pts = this.getPts(i);
    this.flushDisplayed(pts, service);
    for (var winId = 0; winId < 8; winId++) {
      if (b & 1 << winId) {
        service.windows[winId].visible ^= 1;
      }
    }
    return i;
  };
  Cea708Stream.prototype.clearWindows = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[++i];
    var pts = this.getPts(i);
    this.flushDisplayed(pts, service);
    for (var winId = 0; winId < 8; winId++) {
      if (b & 1 << winId) {
        service.windows[winId].clearText();
      }
    }
    return i;
  };
  Cea708Stream.prototype.deleteWindows = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[++i];
    var pts = this.getPts(i);
    this.flushDisplayed(pts, service);
    for (var winId = 0; winId < 8; winId++) {
      if (b & 1 << winId) {
        service.windows[winId].reset();
      }
    }
    return i;
  };
  Cea708Stream.prototype.setPenAttributes = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[i];
    var penAttr = service.currentWindow.penAttr;
    b = packetData[++i];
    penAttr.textTag = (b & 240) >> 4;
    penAttr.offset = (b & 12) >> 2;
    penAttr.penSize = b & 3;
    b = packetData[++i];
    penAttr.italics = (b & 128) >> 7;
    penAttr.underline = (b & 64) >> 6;
    penAttr.edgeType = (b & 56) >> 3;
    penAttr.fontStyle = b & 7;
    return i;
  };
  Cea708Stream.prototype.setPenColor = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[i];
    var penColor = service.currentWindow.penColor;
    b = packetData[++i];
    penColor.fgOpacity = (b & 192) >> 6;
    penColor.fgRed = (b & 48) >> 4;
    penColor.fgGreen = (b & 12) >> 2;
    penColor.fgBlue = b & 3;
    b = packetData[++i];
    penColor.bgOpacity = (b & 192) >> 6;
    penColor.bgRed = (b & 48) >> 4;
    penColor.bgGreen = (b & 12) >> 2;
    penColor.bgBlue = b & 3;
    b = packetData[++i];
    penColor.edgeRed = (b & 48) >> 4;
    penColor.edgeGreen = (b & 12) >> 2;
    penColor.edgeBlue = b & 3;
    return i;
  };
  Cea708Stream.prototype.setPenLocation = function(i, service) {
    var packetData = this.current708Packet.data;
    var b = packetData[i];
    var penLoc = service.currentWindow.penLoc;
    service.currentWindow.pendingNewLine = true;
    b = packetData[++i];
    penLoc.row = b & 15;
    b = packetData[++i];
    penLoc.column = b & 63;
    return i;
  };
  Cea708Stream.prototype.reset = function(i, service) {
    var pts = this.getPts(i);
    this.flushDisplayed(pts, service);
    return this.initService(service.serviceNum, i);
  };
  var CHARACTER_TRANSLATION = {
    42: 225,
    // á
    92: 233,
    // é
    94: 237,
    // í
    95: 243,
    // ó
    96: 250,
    // ú
    123: 231,
    // ç
    124: 247,
    // ÷
    125: 209,
    // Ñ
    126: 241,
    // ñ
    127: 9608,
    // █
    304: 174,
    // ®
    305: 176,
    // °
    306: 189,
    // ½
    307: 191,
    // ¿
    308: 8482,
    // ™
    309: 162,
    // ¢
    310: 163,
    // £
    311: 9834,
    // ♪
    312: 224,
    // à
    313: 160,
    //
    314: 232,
    // è
    315: 226,
    // â
    316: 234,
    // ê
    317: 238,
    // î
    318: 244,
    // ô
    319: 251,
    // û
    544: 193,
    // Á
    545: 201,
    // É
    546: 211,
    // Ó
    547: 218,
    // Ú
    548: 220,
    // Ü
    549: 252,
    // ü
    550: 8216,
    // ‘
    551: 161,
    // ¡
    552: 42,
    // *
    553: 39,
    // '
    554: 8212,
    // —
    555: 169,
    // ©
    556: 8480,
    // ℠
    557: 8226,
    // •
    558: 8220,
    // “
    559: 8221,
    // ”
    560: 192,
    // À
    561: 194,
    // Â
    562: 199,
    // Ç
    563: 200,
    // È
    564: 202,
    // Ê
    565: 203,
    // Ë
    566: 235,
    // ë
    567: 206,
    // Î
    568: 207,
    // Ï
    569: 239,
    // ï
    570: 212,
    // Ô
    571: 217,
    // Ù
    572: 249,
    // ù
    573: 219,
    // Û
    574: 171,
    // «
    575: 187,
    // »
    800: 195,
    // Ã
    801: 227,
    // ã
    802: 205,
    // Í
    803: 204,
    // Ì
    804: 236,
    // ì
    805: 210,
    // Ò
    806: 242,
    // ò
    807: 213,
    // Õ
    808: 245,
    // õ
    809: 123,
    // {
    810: 125,
    // }
    811: 92,
    // \
    812: 94,
    // ^
    813: 95,
    // _
    814: 124,
    // |
    815: 126,
    // ~
    816: 196,
    // Ä
    817: 228,
    // ä
    818: 214,
    // Ö
    819: 246,
    // ö
    820: 223,
    // ß
    821: 165,
    // ¥
    822: 164,
    // ¤
    823: 9474,
    // │
    824: 197,
    // Å
    825: 229,
    // å
    826: 216,
    // Ø
    827: 248,
    // ø
    828: 9484,
    // ┌
    829: 9488,
    // ┐
    830: 9492,
    // └
    831: 9496
    // ┘
  };
  var getCharFromCode = function getCharFromCode2(code) {
    if (code === null) {
      return "";
    }
    code = CHARACTER_TRANSLATION[code] || code;
    return String.fromCharCode(code);
  };
  var BOTTOM_ROW = 14;
  var ROWS = [4352, 4384, 4608, 4640, 5376, 5408, 5632, 5664, 5888, 5920, 4096, 4864, 4896, 5120, 5152];
  var createDisplayBuffer = function createDisplayBuffer2() {
    var result = [], i = BOTTOM_ROW + 1;
    while (i--) {
      result.push("");
    }
    return result;
  };
  var Cea608Stream = function Cea608Stream2(field, dataChannel) {
    Cea608Stream2.prototype.init.call(this);
    this.field_ = field || 0;
    this.dataChannel_ = dataChannel || 0;
    this.name_ = "CC" + ((this.field_ << 1 | this.dataChannel_) + 1);
    this.setConstants();
    this.reset();
    this.push = function(packet) {
      var data, swap, char0, char1, text;
      data = packet.ccData & 32639;
      if (data === this.lastControlCode_) {
        this.lastControlCode_ = null;
        return;
      }
      if ((data & 61440) === 4096) {
        this.lastControlCode_ = data;
      } else if (data !== this.PADDING_) {
        this.lastControlCode_ = null;
      }
      char0 = data >>> 8;
      char1 = data & 255;
      if (data === this.PADDING_) {
        return;
      } else if (data === this.RESUME_CAPTION_LOADING_) {
        this.mode_ = "popOn";
      } else if (data === this.END_OF_CAPTION_) {
        this.mode_ = "popOn";
        this.clearFormatting(packet.pts);
        this.flushDisplayed(packet.pts);
        swap = this.displayed_;
        this.displayed_ = this.nonDisplayed_;
        this.nonDisplayed_ = swap;
        this.startPts_ = packet.pts;
      } else if (data === this.ROLL_UP_2_ROWS_) {
        this.rollUpRows_ = 2;
        this.setRollUp(packet.pts);
      } else if (data === this.ROLL_UP_3_ROWS_) {
        this.rollUpRows_ = 3;
        this.setRollUp(packet.pts);
      } else if (data === this.ROLL_UP_4_ROWS_) {
        this.rollUpRows_ = 4;
        this.setRollUp(packet.pts);
      } else if (data === this.CARRIAGE_RETURN_) {
        this.clearFormatting(packet.pts);
        this.flushDisplayed(packet.pts);
        this.shiftRowsUp_();
        this.startPts_ = packet.pts;
      } else if (data === this.BACKSPACE_) {
        if (this.mode_ === "popOn") {
          this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
        } else {
          this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
        }
      } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
        this.flushDisplayed(packet.pts);
        this.displayed_ = createDisplayBuffer();
      } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
        this.nonDisplayed_ = createDisplayBuffer();
      } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
        if (this.mode_ !== "paintOn") {
          this.flushDisplayed(packet.pts);
          this.displayed_ = createDisplayBuffer();
        }
        this.mode_ = "paintOn";
        this.startPts_ = packet.pts;
      } else if (this.isSpecialCharacter(char0, char1)) {
        char0 = (char0 & 3) << 8;
        text = getCharFromCode(char0 | char1);
        this[this.mode_](packet.pts, text);
        this.column_++;
      } else if (this.isExtCharacter(char0, char1)) {
        if (this.mode_ === "popOn") {
          this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
        } else {
          this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
        }
        char0 = (char0 & 3) << 8;
        text = getCharFromCode(char0 | char1);
        this[this.mode_](packet.pts, text);
        this.column_++;
      } else if (this.isMidRowCode(char0, char1)) {
        this.clearFormatting(packet.pts);
        this[this.mode_](packet.pts, " ");
        this.column_++;
        if ((char1 & 14) === 14) {
          this.addFormatting(packet.pts, ["i"]);
        }
        if ((char1 & 1) === 1) {
          this.addFormatting(packet.pts, ["u"]);
        }
      } else if (this.isOffsetControlCode(char0, char1)) {
        this.column_ += char1 & 3;
      } else if (this.isPAC(char0, char1)) {
        var row = ROWS.indexOf(data & 7968);
        if (this.mode_ === "rollUp") {
          if (row - this.rollUpRows_ + 1 < 0) {
            row = this.rollUpRows_ - 1;
          }
          this.setRollUp(packet.pts, row);
        }
        if (row !== this.row_) {
          this.clearFormatting(packet.pts);
          this.row_ = row;
        }
        if (char1 & 1 && this.formatting_.indexOf("u") === -1) {
          this.addFormatting(packet.pts, ["u"]);
        }
        if ((data & 16) === 16) {
          this.column_ = ((data & 14) >> 1) * 4;
        }
        if (this.isColorPAC(char1)) {
          if ((char1 & 14) === 14) {
            this.addFormatting(packet.pts, ["i"]);
          }
        }
      } else if (this.isNormalChar(char0)) {
        if (char1 === 0) {
          char1 = null;
        }
        text = getCharFromCode(char0);
        text += getCharFromCode(char1);
        this[this.mode_](packet.pts, text);
        this.column_ += text.length;
      }
    };
  };
  Cea608Stream.prototype = new stream();
  Cea608Stream.prototype.flushDisplayed = function(pts) {
    var content = this.displayed_.map(function(row, index) {
      try {
        return row.trim();
      } catch (e) {
        this.trigger("log", {
          level: "warn",
          message: "Skipping a malformed 608 caption at index " + index + "."
        });
        return "";
      }
    }, this).join("\n").replace(/^\n+|\n+$/g, "");
    if (content.length) {
      this.trigger("data", {
        startPts: this.startPts_,
        endPts: pts,
        text: content,
        stream: this.name_
      });
    }
  };
  Cea608Stream.prototype.reset = function() {
    this.mode_ = "popOn";
    this.topRow_ = 0;
    this.startPts_ = 0;
    this.displayed_ = createDisplayBuffer();
    this.nonDisplayed_ = createDisplayBuffer();
    this.lastControlCode_ = null;
    this.column_ = 0;
    this.row_ = BOTTOM_ROW;
    this.rollUpRows_ = 2;
    this.formatting_ = [];
  };
  Cea608Stream.prototype.setConstants = function() {
    if (this.dataChannel_ === 0) {
      this.BASE_ = 16;
      this.EXT_ = 17;
      this.CONTROL_ = (20 | this.field_) << 8;
      this.OFFSET_ = 23;
    } else if (this.dataChannel_ === 1) {
      this.BASE_ = 24;
      this.EXT_ = 25;
      this.CONTROL_ = (28 | this.field_) << 8;
      this.OFFSET_ = 31;
    }
    this.PADDING_ = 0;
    this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 32;
    this.END_OF_CAPTION_ = this.CONTROL_ | 47;
    this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 37;
    this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 38;
    this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 39;
    this.CARRIAGE_RETURN_ = this.CONTROL_ | 45;
    this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 41;
    this.BACKSPACE_ = this.CONTROL_ | 33;
    this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 44;
    this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 46;
  };
  Cea608Stream.prototype.isSpecialCharacter = function(char0, char1) {
    return char0 === this.EXT_ && char1 >= 48 && char1 <= 63;
  };
  Cea608Stream.prototype.isExtCharacter = function(char0, char1) {
    return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 32 && char1 <= 63;
  };
  Cea608Stream.prototype.isMidRowCode = function(char0, char1) {
    return char0 === this.EXT_ && char1 >= 32 && char1 <= 47;
  };
  Cea608Stream.prototype.isOffsetControlCode = function(char0, char1) {
    return char0 === this.OFFSET_ && char1 >= 33 && char1 <= 35;
  };
  Cea608Stream.prototype.isPAC = function(char0, char1) {
    return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 64 && char1 <= 127;
  };
  Cea608Stream.prototype.isColorPAC = function(char1) {
    return char1 >= 64 && char1 <= 79 || char1 >= 96 && char1 <= 127;
  };
  Cea608Stream.prototype.isNormalChar = function(_char2) {
    return _char2 >= 32 && _char2 <= 127;
  };
  Cea608Stream.prototype.setRollUp = function(pts, newBaseRow) {
    if (this.mode_ !== "rollUp") {
      this.row_ = BOTTOM_ROW;
      this.mode_ = "rollUp";
      this.flushDisplayed(pts);
      this.nonDisplayed_ = createDisplayBuffer();
      this.displayed_ = createDisplayBuffer();
    }
    if (newBaseRow !== void 0 && newBaseRow !== this.row_) {
      for (var i = 0; i < this.rollUpRows_; i++) {
        this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
        this.displayed_[this.row_ - i] = "";
      }
    }
    if (newBaseRow === void 0) {
      newBaseRow = this.row_;
    }
    this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  };
  Cea608Stream.prototype.addFormatting = function(pts, format2) {
    this.formatting_ = this.formatting_.concat(format2);
    var text = format2.reduce(function(text2, format3) {
      return text2 + "<" + format3 + ">";
    }, "");
    this[this.mode_](pts, text);
  };
  Cea608Stream.prototype.clearFormatting = function(pts) {
    if (!this.formatting_.length) {
      return;
    }
    var text = this.formatting_.reverse().reduce(function(text2, format2) {
      return text2 + "</" + format2 + ">";
    }, "");
    this.formatting_ = [];
    this[this.mode_](pts, text);
  };
  Cea608Stream.prototype.popOn = function(pts, text) {
    var baseRow = this.nonDisplayed_[this.row_];
    baseRow += text;
    this.nonDisplayed_[this.row_] = baseRow;
  };
  Cea608Stream.prototype.rollUp = function(pts, text) {
    var baseRow = this.displayed_[this.row_];
    baseRow += text;
    this.displayed_[this.row_] = baseRow;
  };
  Cea608Stream.prototype.shiftRowsUp_ = function() {
    var i;
    for (i = 0; i < this.topRow_; i++) {
      this.displayed_[i] = "";
    }
    for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
      this.displayed_[i] = "";
    }
    for (i = this.topRow_; i < this.row_; i++) {
      this.displayed_[i] = this.displayed_[i + 1];
    }
    this.displayed_[this.row_] = "";
  };
  Cea608Stream.prototype.paintOn = function(pts, text) {
    var baseRow = this.displayed_[this.row_];
    baseRow += text;
    this.displayed_[this.row_] = baseRow;
  };
  var captionStream = {
    CaptionStream: CaptionStream$1,
    Cea608Stream,
    Cea708Stream
  };
  var streamTypes = {
    H264_STREAM_TYPE: 27,
    ADTS_STREAM_TYPE: 15,
    METADATA_STREAM_TYPE: 21
  };
  var MAX_TS = 8589934592;
  var RO_THRESH = 4294967296;
  var TYPE_SHARED = "shared";
  var handleRollover$1 = function handleRollover2(value, reference) {
    var direction = 1;
    if (value > reference) {
      direction = -1;
    }
    while (Math.abs(reference - value) > RO_THRESH) {
      value += direction * MAX_TS;
    }
    return value;
  };
  var TimestampRolloverStream$1 = function TimestampRolloverStream2(type3) {
    var lastDTS, referenceDTS;
    TimestampRolloverStream2.prototype.init.call(this);
    this.type_ = type3 || TYPE_SHARED;
    this.push = function(data) {
      if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
        return;
      }
      if (referenceDTS === void 0) {
        referenceDTS = data.dts;
      }
      data.dts = handleRollover$1(data.dts, referenceDTS);
      data.pts = handleRollover$1(data.pts, referenceDTS);
      lastDTS = data.dts;
      this.trigger("data", data);
    };
    this.flush = function() {
      referenceDTS = lastDTS;
      this.trigger("done");
    };
    this.endTimeline = function() {
      this.flush();
      this.trigger("endedtimeline");
    };
    this.discontinuity = function() {
      referenceDTS = void 0;
      lastDTS = void 0;
    };
    this.reset = function() {
      this.discontinuity();
      this.trigger("reset");
    };
  };
  TimestampRolloverStream$1.prototype = new stream();
  var timestampRolloverStream = {
    TimestampRolloverStream: TimestampRolloverStream$1,
    handleRollover: handleRollover$1
  };
  var percentEncode$1 = function percentEncode2(bytes, start2, end) {
    var i, result = "";
    for (i = start2; i < end; i++) {
      result += "%" + ("00" + bytes[i].toString(16)).slice(-2);
    }
    return result;
  }, parseUtf8 = function parseUtf82(bytes, start2, end) {
    return decodeURIComponent(percentEncode$1(bytes, start2, end));
  }, parseIso88591$1 = function parseIso885912(bytes, start2, end) {
    return unescape(percentEncode$1(bytes, start2, end));
  }, parseSyncSafeInteger$1 = function parseSyncSafeInteger2(data) {
    return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  }, tagParsers = {
    TXXX: function TXXX(tag) {
      var i;
      if (tag.data[0] !== 3) {
        return;
      }
      for (i = 1; i < tag.data.length; i++) {
        if (tag.data[i] === 0) {
          tag.description = parseUtf8(tag.data, 1, i);
          tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, "");
          break;
        }
      }
      tag.data = tag.value;
    },
    WXXX: function WXXX(tag) {
      var i;
      if (tag.data[0] !== 3) {
        return;
      }
      for (i = 1; i < tag.data.length; i++) {
        if (tag.data[i] === 0) {
          tag.description = parseUtf8(tag.data, 1, i);
          tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
          break;
        }
      }
    },
    PRIV: function PRIV(tag) {
      var i;
      for (i = 0; i < tag.data.length; i++) {
        if (tag.data[i] === 0) {
          tag.owner = parseIso88591$1(tag.data, 0, i);
          break;
        }
      }
      tag.privateData = tag.data.subarray(i + 1);
      tag.data = tag.privateData;
    }
  }, _MetadataStream;
  _MetadataStream = function MetadataStream(options) {
    var settings = {
      // the bytes of the program-level descriptor field in MP2T
      // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
      // program element descriptors"
      descriptor: options && options.descriptor
    }, tagSize = 0, buffer = [], bufferSize = 0, i;
    _MetadataStream.prototype.init.call(this);
    this.dispatchType = streamTypes.METADATA_STREAM_TYPE.toString(16);
    if (settings.descriptor) {
      for (i = 0; i < settings.descriptor.length; i++) {
        this.dispatchType += ("00" + settings.descriptor[i].toString(16)).slice(-2);
      }
    }
    this.push = function(chunk) {
      var tag, frameStart, frameSize, frame, i2, frameHeader;
      if (chunk.type !== "timed-metadata") {
        return;
      }
      if (chunk.dataAlignmentIndicator) {
        bufferSize = 0;
        buffer.length = 0;
      }
      if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== "I".charCodeAt(0) || chunk.data[1] !== "D".charCodeAt(0) || chunk.data[2] !== "3".charCodeAt(0))) {
        this.trigger("log", {
          level: "warn",
          message: "Skipping unrecognized metadata packet"
        });
        return;
      }
      buffer.push(chunk);
      bufferSize += chunk.data.byteLength;
      if (buffer.length === 1) {
        tagSize = parseSyncSafeInteger$1(chunk.data.subarray(6, 10));
        tagSize += 10;
      }
      if (bufferSize < tagSize) {
        return;
      }
      tag = {
        data: new Uint8Array(tagSize),
        frames: [],
        pts: buffer[0].pts,
        dts: buffer[0].dts
      };
      for (i2 = 0; i2 < tagSize; ) {
        tag.data.set(buffer[0].data.subarray(0, tagSize - i2), i2);
        i2 += buffer[0].data.byteLength;
        bufferSize -= buffer[0].data.byteLength;
        buffer.shift();
      }
      frameStart = 10;
      if (tag.data[5] & 64) {
        frameStart += 4;
        frameStart += parseSyncSafeInteger$1(tag.data.subarray(10, 14));
        tagSize -= parseSyncSafeInteger$1(tag.data.subarray(16, 20));
      }
      do {
        frameSize = parseSyncSafeInteger$1(tag.data.subarray(frameStart + 4, frameStart + 8));
        if (frameSize < 1) {
          this.trigger("log", {
            level: "warn",
            message: "Malformed ID3 frame encountered. Skipping metadata parsing."
          });
          return;
        }
        frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
        frame = {
          id: frameHeader,
          data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
        };
        frame.key = frame.id;
        if (tagParsers[frame.id]) {
          tagParsers[frame.id](frame);
          if (frame.owner === "com.apple.streaming.transportStreamTimestamp") {
            var d2 = frame.data, size = (d2[3] & 1) << 30 | d2[4] << 22 | d2[5] << 14 | d2[6] << 6 | d2[7] >>> 2;
            size *= 4;
            size += d2[7] & 3;
            frame.timeStamp = size;
            if (tag.pts === void 0 && tag.dts === void 0) {
              tag.pts = frame.timeStamp;
              tag.dts = frame.timeStamp;
            }
            this.trigger("timestamp", frame);
          }
        }
        tag.frames.push(frame);
        frameStart += 10;
        frameStart += frameSize;
      } while (frameStart < tagSize);
      this.trigger("data", tag);
    };
  };
  _MetadataStream.prototype = new stream();
  var metadataStream = _MetadataStream;
  var TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream;
  var _TransportPacketStream, _TransportParseStream, _ElementaryStream;
  var MP2T_PACKET_LENGTH$1 = 188, SYNC_BYTE$1 = 71;
  _TransportPacketStream = function TransportPacketStream() {
    var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1), bytesInBuffer = 0;
    _TransportPacketStream.prototype.init.call(this);
    this.push = function(bytes) {
      var startIndex = 0, endIndex = MP2T_PACKET_LENGTH$1, everything;
      if (bytesInBuffer) {
        everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
        everything.set(buffer.subarray(0, bytesInBuffer));
        everything.set(bytes, bytesInBuffer);
        bytesInBuffer = 0;
      } else {
        everything = bytes;
      }
      while (endIndex < everything.byteLength) {
        if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
          this.trigger("data", everything.subarray(startIndex, endIndex));
          startIndex += MP2T_PACKET_LENGTH$1;
          endIndex += MP2T_PACKET_LENGTH$1;
          continue;
        }
        startIndex++;
        endIndex++;
      }
      if (startIndex < everything.byteLength) {
        buffer.set(everything.subarray(startIndex), 0);
        bytesInBuffer = everything.byteLength - startIndex;
      }
    };
    this.flush = function() {
      if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
        this.trigger("data", buffer);
        bytesInBuffer = 0;
      }
      this.trigger("done");
    };
    this.endTimeline = function() {
      this.flush();
      this.trigger("endedtimeline");
    };
    this.reset = function() {
      bytesInBuffer = 0;
      this.trigger("reset");
    };
  };
  _TransportPacketStream.prototype = new stream();
  _TransportParseStream = function TransportParseStream() {
    var parsePsi, parsePat2, parsePmt2, self2;
    _TransportParseStream.prototype.init.call(this);
    self2 = this;
    this.packetsWaitingForPmt = [];
    this.programMapTable = void 0;
    parsePsi = function parsePsi2(payload, psi) {
      var offset = 0;
      if (psi.payloadUnitStartIndicator) {
        offset += payload[offset] + 1;
      }
      if (psi.type === "pat") {
        parsePat2(payload.subarray(offset), psi);
      } else {
        parsePmt2(payload.subarray(offset), psi);
      }
    };
    parsePat2 = function parsePat3(payload, pat) {
      pat.section_number = payload[7];
      pat.last_section_number = payload[8];
      self2.pmtPid = (payload[10] & 31) << 8 | payload[11];
      pat.pmtPid = self2.pmtPid;
    };
    parsePmt2 = function parsePmt3(payload, pmt) {
      var sectionLength, tableEnd, programInfoLength, offset;
      if (!(payload[5] & 1)) {
        return;
      }
      self2.programMapTable = {
        video: null,
        audio: null,
        "timed-metadata": {}
      };
      sectionLength = (payload[1] & 15) << 8 | payload[2];
      tableEnd = 3 + sectionLength - 4;
      programInfoLength = (payload[10] & 15) << 8 | payload[11];
      offset = 12 + programInfoLength;
      while (offset < tableEnd) {
        var streamType = payload[offset];
        var pid = (payload[offset + 1] & 31) << 8 | payload[offset + 2];
        if (streamType === streamTypes.H264_STREAM_TYPE && self2.programMapTable.video === null) {
          self2.programMapTable.video = pid;
        } else if (streamType === streamTypes.ADTS_STREAM_TYPE && self2.programMapTable.audio === null) {
          self2.programMapTable.audio = pid;
        } else if (streamType === streamTypes.METADATA_STREAM_TYPE) {
          self2.programMapTable["timed-metadata"][pid] = streamType;
        }
        offset += ((payload[offset + 3] & 15) << 8 | payload[offset + 4]) + 5;
      }
      pmt.programMapTable = self2.programMapTable;
    };
    this.push = function(packet) {
      var result = {}, offset = 4;
      result.payloadUnitStartIndicator = !!(packet[1] & 64);
      result.pid = packet[1] & 31;
      result.pid <<= 8;
      result.pid |= packet[2];
      if ((packet[3] & 48) >>> 4 > 1) {
        offset += packet[offset] + 1;
      }
      if (result.pid === 0) {
        result.type = "pat";
        parsePsi(packet.subarray(offset), result);
        this.trigger("data", result);
      } else if (result.pid === this.pmtPid) {
        result.type = "pmt";
        parsePsi(packet.subarray(offset), result);
        this.trigger("data", result);
        while (this.packetsWaitingForPmt.length) {
          this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
        }
      } else if (this.programMapTable === void 0) {
        this.packetsWaitingForPmt.push([packet, offset, result]);
      } else {
        this.processPes_(packet, offset, result);
      }
    };
    this.processPes_ = function(packet, offset, result) {
      if (result.pid === this.programMapTable.video) {
        result.streamType = streamTypes.H264_STREAM_TYPE;
      } else if (result.pid === this.programMapTable.audio) {
        result.streamType = streamTypes.ADTS_STREAM_TYPE;
      } else {
        result.streamType = this.programMapTable["timed-metadata"][result.pid];
      }
      result.type = "pes";
      result.data = packet.subarray(offset);
      this.trigger("data", result);
    };
  };
  _TransportParseStream.prototype = new stream();
  _TransportParseStream.STREAM_TYPES = {
    h264: 27,
    adts: 15
  };
  _ElementaryStream = function ElementaryStream() {
    var self2 = this, segmentHadPmt = false, video = {
      data: [],
      size: 0
    }, audio = {
      data: [],
      size: 0
    }, timedMetadata = {
      data: [],
      size: 0
    }, programMapTable, parsePes = function parsePes2(payload, pes) {
      var ptsDtsFlags;
      var startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2];
      pes.data = new Uint8Array();
      if (startPrefix !== 1) {
        return;
      }
      pes.packetLength = 6 + (payload[4] << 8 | payload[5]);
      pes.dataAlignmentIndicator = (payload[6] & 4) !== 0;
      ptsDtsFlags = payload[7];
      if (ptsDtsFlags & 192) {
        pes.pts = (payload[9] & 14) << 27 | (payload[10] & 255) << 20 | (payload[11] & 254) << 12 | (payload[12] & 255) << 5 | (payload[13] & 254) >>> 3;
        pes.pts *= 4;
        pes.pts += (payload[13] & 6) >>> 1;
        pes.dts = pes.pts;
        if (ptsDtsFlags & 64) {
          pes.dts = (payload[14] & 14) << 27 | (payload[15] & 255) << 20 | (payload[16] & 254) << 12 | (payload[17] & 255) << 5 | (payload[18] & 254) >>> 3;
          pes.dts *= 4;
          pes.dts += (payload[18] & 6) >>> 1;
        }
      }
      pes.data = payload.subarray(9 + payload[8]);
    }, flushStream = function flushStream2(stream2, type3, forceFlush) {
      var packetData = new Uint8Array(stream2.size), event = {
        type: type3
      }, i = 0, offset = 0, packetFlushable = false, fragment;
      if (!stream2.data.length || stream2.size < 9) {
        return;
      }
      event.trackId = stream2.data[0].pid;
      for (i = 0; i < stream2.data.length; i++) {
        fragment = stream2.data[i];
        packetData.set(fragment.data, offset);
        offset += fragment.data.byteLength;
      }
      parsePes(packetData, event);
      packetFlushable = type3 === "video" || event.packetLength <= stream2.size;
      if (forceFlush || packetFlushable) {
        stream2.size = 0;
        stream2.data.length = 0;
      }
      if (packetFlushable) {
        self2.trigger("data", event);
      }
    };
    _ElementaryStream.prototype.init.call(this);
    this.push = function(data) {
      ({
        pat: function pat() {
        },
        pes: function pes() {
          var stream2, streamType;
          switch (data.streamType) {
            case streamTypes.H264_STREAM_TYPE:
              stream2 = video;
              streamType = "video";
              break;
            case streamTypes.ADTS_STREAM_TYPE:
              stream2 = audio;
              streamType = "audio";
              break;
            case streamTypes.METADATA_STREAM_TYPE:
              stream2 = timedMetadata;
              streamType = "timed-metadata";
              break;
            default:
              return;
          }
          if (data.payloadUnitStartIndicator) {
            flushStream(stream2, streamType, true);
          }
          stream2.data.push(data);
          stream2.size += data.data.byteLength;
        },
        pmt: function pmt() {
          var event = {
            type: "metadata",
            tracks: []
          };
          programMapTable = data.programMapTable;
          if (programMapTable.video !== null) {
            event.tracks.push({
              timelineStartInfo: {
                baseMediaDecodeTime: 0
              },
              id: +programMapTable.video,
              codec: "avc",
              type: "video"
            });
          }
          if (programMapTable.audio !== null) {
            event.tracks.push({
              timelineStartInfo: {
                baseMediaDecodeTime: 0
              },
              id: +programMapTable.audio,
              codec: "adts",
              type: "audio"
            });
          }
          segmentHadPmt = true;
          self2.trigger("data", event);
        }
      })[data.type]();
    };
    this.reset = function() {
      video.size = 0;
      video.data.length = 0;
      audio.size = 0;
      audio.data.length = 0;
      this.trigger("reset");
    };
    this.flushStreams_ = function() {
      flushStream(video, "video");
      flushStream(audio, "audio");
      flushStream(timedMetadata, "timed-metadata");
    };
    this.flush = function() {
      if (!segmentHadPmt && programMapTable) {
        var pmt = {
          type: "metadata",
          tracks: []
        };
        if (programMapTable.video !== null) {
          pmt.tracks.push({
            timelineStartInfo: {
              baseMediaDecodeTime: 0
            },
            id: +programMapTable.video,
            codec: "avc",
            type: "video"
          });
        }
        if (programMapTable.audio !== null) {
          pmt.tracks.push({
            timelineStartInfo: {
              baseMediaDecodeTime: 0
            },
            id: +programMapTable.audio,
            codec: "adts",
            type: "audio"
          });
        }
        self2.trigger("data", pmt);
      }
      segmentHadPmt = false;
      this.flushStreams_();
      this.trigger("done");
    };
  };
  _ElementaryStream.prototype = new stream();
  var m2ts = {
    PAT_PID: 0,
    MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
    TransportPacketStream: _TransportPacketStream,
    TransportParseStream: _TransportParseStream,
    ElementaryStream: _ElementaryStream,
    TimestampRolloverStream,
    CaptionStream: captionStream.CaptionStream,
    Cea608Stream: captionStream.Cea608Stream,
    Cea708Stream: captionStream.Cea708Stream,
    MetadataStream: metadataStream
  };
  for (var type2 in streamTypes) {
    if (streamTypes.hasOwnProperty(type2)) {
      m2ts[type2] = streamTypes[type2];
    }
  }
  var m2ts_1 = m2ts;
  var ONE_SECOND_IN_TS$2 = clock.ONE_SECOND_IN_TS;
  var _AdtsStream;
  var ADTS_SAMPLING_FREQUENCIES$1 = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
  _AdtsStream = function AdtsStream(handlePartialSegments) {
    var buffer, frameNum = 0;
    _AdtsStream.prototype.init.call(this);
    this.skipWarn_ = function(start2, end) {
      this.trigger("log", {
        level: "warn",
        message: "adts skiping bytes " + start2 + " to " + end + " in frame " + frameNum + " outside syncword"
      });
    };
    this.push = function(packet) {
      var i = 0, frameLength, protectionSkipBytes, oldBuffer, sampleCount, adtsFrameDuration;
      if (!handlePartialSegments) {
        frameNum = 0;
      }
      if (packet.type !== "audio") {
        return;
      }
      if (buffer && buffer.length) {
        oldBuffer = buffer;
        buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
        buffer.set(oldBuffer);
        buffer.set(packet.data, oldBuffer.byteLength);
      } else {
        buffer = packet.data;
      }
      var skip;
      while (i + 7 < buffer.length) {
        if (buffer[i] !== 255 || (buffer[i + 1] & 246) !== 240) {
          if (typeof skip !== "number") {
            skip = i;
          }
          i++;
          continue;
        }
        if (typeof skip === "number") {
          this.skipWarn_(skip, i);
          skip = null;
        }
        protectionSkipBytes = (~buffer[i + 1] & 1) * 2;
        frameLength = (buffer[i + 3] & 3) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 224) >> 5;
        sampleCount = ((buffer[i + 6] & 3) + 1) * 1024;
        adtsFrameDuration = sampleCount * ONE_SECOND_IN_TS$2 / ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 60) >>> 2];
        if (buffer.byteLength - i < frameLength) {
          break;
        }
        this.trigger("data", {
          pts: packet.pts + frameNum * adtsFrameDuration,
          dts: packet.dts + frameNum * adtsFrameDuration,
          sampleCount,
          audioobjecttype: (buffer[i + 2] >>> 6 & 3) + 1,
          channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 192) >>> 6,
          samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 60) >>> 2],
          samplingfrequencyindex: (buffer[i + 2] & 60) >>> 2,
          // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
          samplesize: 16,
          // data is the frame without it's header
          data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
        });
        frameNum++;
        i += frameLength;
      }
      if (typeof skip === "number") {
        this.skipWarn_(skip, i);
        skip = null;
      }
      buffer = buffer.subarray(i);
    };
    this.flush = function() {
      frameNum = 0;
      this.trigger("done");
    };
    this.reset = function() {
      buffer = void 0;
      this.trigger("reset");
    };
    this.endTimeline = function() {
      buffer = void 0;
      this.trigger("endedtimeline");
    };
  };
  _AdtsStream.prototype = new stream();
  var adts = _AdtsStream;
  var ExpGolomb2;
  ExpGolomb2 = function ExpGolomb3(workingData) {
    var workingBytesAvailable = workingData.byteLength, workingWord = 0, workingBitsAvailable = 0;
    this.length = function() {
      return 8 * workingBytesAvailable;
    };
    this.bitsAvailable = function() {
      return 8 * workingBytesAvailable + workingBitsAvailable;
    };
    this.loadWord = function() {
      var position = workingData.byteLength - workingBytesAvailable, workingBytes = new Uint8Array(4), availableBytes = Math.min(4, workingBytesAvailable);
      if (availableBytes === 0) {
        throw new Error("no bytes available");
      }
      workingBytes.set(workingData.subarray(position, position + availableBytes));
      workingWord = new DataView(workingBytes.buffer).getUint32(0);
      workingBitsAvailable = availableBytes * 8;
      workingBytesAvailable -= availableBytes;
    };
    this.skipBits = function(count) {
      var skipBytes;
      if (workingBitsAvailable > count) {
        workingWord <<= count;
        workingBitsAvailable -= count;
      } else {
        count -= workingBitsAvailable;
        skipBytes = Math.floor(count / 8);
        count -= skipBytes * 8;
        workingBytesAvailable -= skipBytes;
        this.loadWord();
        workingWord <<= count;
        workingBitsAvailable -= count;
      }
    };
    this.readBits = function(size) {
      var bits = Math.min(workingBitsAvailable, size), valu = workingWord >>> 32 - bits;
      workingBitsAvailable -= bits;
      if (workingBitsAvailable > 0) {
        workingWord <<= bits;
      } else if (workingBytesAvailable > 0) {
        this.loadWord();
      }
      bits = size - bits;
      if (bits > 0) {
        return valu << bits | this.readBits(bits);
      }
      return valu;
    };
    this.skipLeadingZeros = function() {
      var leadingZeroCount;
      for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
        if ((workingWord & 2147483648 >>> leadingZeroCount) !== 0) {
          workingWord <<= leadingZeroCount;
          workingBitsAvailable -= leadingZeroCount;
          return leadingZeroCount;
        }
      }
      this.loadWord();
      return leadingZeroCount + this.skipLeadingZeros();
    };
    this.skipUnsignedExpGolomb = function() {
      this.skipBits(1 + this.skipLeadingZeros());
    };
    this.skipExpGolomb = function() {
      this.skipBits(1 + this.skipLeadingZeros());
    };
    this.readUnsignedExpGolomb = function() {
      var clz = this.skipLeadingZeros();
      return this.readBits(clz + 1) - 1;
    };
    this.readExpGolomb = function() {
      var valu = this.readUnsignedExpGolomb();
      if (1 & valu) {
        return 1 + valu >>> 1;
      }
      return -1 * (valu >>> 1);
    };
    this.readBoolean = function() {
      return this.readBits(1) === 1;
    };
    this.readUnsignedByte = function() {
      return this.readBits(8);
    };
    this.loadWord();
  };
  var expGolomb = ExpGolomb2;
  var _H264Stream, _NalByteStream;
  var PROFILES_WITH_OPTIONAL_SPS_DATA;
  _NalByteStream = function NalByteStream() {
    var syncPoint = 0, i, buffer;
    _NalByteStream.prototype.init.call(this);
    this.push = function(data) {
      var swapBuffer;
      if (!buffer) {
        buffer = data.data;
      } else {
        swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
        swapBuffer.set(buffer);
        swapBuffer.set(data.data, buffer.byteLength);
        buffer = swapBuffer;
      }
      var len = buffer.byteLength;
      for (; syncPoint < len - 3; syncPoint++) {
        if (buffer[syncPoint + 2] === 1) {
          i = syncPoint + 5;
          break;
        }
      }
      while (i < len) {
        switch (buffer[i]) {
          case 0:
            if (buffer[i - 1] !== 0) {
              i += 2;
              break;
            } else if (buffer[i - 2] !== 0) {
              i++;
              break;
            }
            if (syncPoint + 3 !== i - 2) {
              this.trigger("data", buffer.subarray(syncPoint + 3, i - 2));
            }
            do {
              i++;
            } while (buffer[i] !== 1 && i < len);
            syncPoint = i - 2;
            i += 3;
            break;
          case 1:
            if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
              i += 3;
              break;
            }
            this.trigger("data", buffer.subarray(syncPoint + 3, i - 2));
            syncPoint = i - 2;
            i += 3;
            break;
          default:
            i += 3;
            break;
        }
      }
      buffer = buffer.subarray(syncPoint);
      i -= syncPoint;
      syncPoint = 0;
    };
    this.reset = function() {
      buffer = null;
      syncPoint = 0;
      this.trigger("reset");
    };
    this.flush = function() {
      if (buffer && buffer.byteLength > 3) {
        this.trigger("data", buffer.subarray(syncPoint + 3));
      }
      buffer = null;
      syncPoint = 0;
      this.trigger("done");
    };
    this.endTimeline = function() {
      this.flush();
      this.trigger("endedtimeline");
    };
  };
  _NalByteStream.prototype = new stream();
  PROFILES_WITH_OPTIONAL_SPS_DATA = {
    100: true,
    110: true,
    122: true,
    244: true,
    44: true,
    83: true,
    86: true,
    118: true,
    128: true,
    // TODO: the three profiles below don't
    // appear to have sps data in the specificiation anymore?
    138: true,
    139: true,
    134: true
  };
  _H264Stream = function H264Stream2() {
    var nalByteStream = new _NalByteStream(), self2, trackId, currentPts, currentDts, discardEmulationPreventionBytes4, readSequenceParameterSet, skipScalingList;
    _H264Stream.prototype.init.call(this);
    self2 = this;
    this.push = function(packet) {
      if (packet.type !== "video") {
        return;
      }
      trackId = packet.trackId;
      currentPts = packet.pts;
      currentDts = packet.dts;
      nalByteStream.push(packet);
    };
    nalByteStream.on("data", function(data) {
      var event = {
        trackId,
        pts: currentPts,
        dts: currentDts,
        data,
        nalUnitTypeCode: data[0] & 31
      };
      switch (event.nalUnitTypeCode) {
        case 5:
          event.nalUnitType = "slice_layer_without_partitioning_rbsp_idr";
          break;
        case 6:
          event.nalUnitType = "sei_rbsp";
          event.escapedRBSP = discardEmulationPreventionBytes4(data.subarray(1));
          break;
        case 7:
          event.nalUnitType = "seq_parameter_set_rbsp";
          event.escapedRBSP = discardEmulationPreventionBytes4(data.subarray(1));
          event.config = readSequenceParameterSet(event.escapedRBSP);
          break;
        case 8:
          event.nalUnitType = "pic_parameter_set_rbsp";
          break;
        case 9:
          event.nalUnitType = "access_unit_delimiter_rbsp";
          break;
      }
      self2.trigger("data", event);
    });
    nalByteStream.on("done", function() {
      self2.trigger("done");
    });
    nalByteStream.on("partialdone", function() {
      self2.trigger("partialdone");
    });
    nalByteStream.on("reset", function() {
      self2.trigger("reset");
    });
    nalByteStream.on("endedtimeline", function() {
      self2.trigger("endedtimeline");
    });
    this.flush = function() {
      nalByteStream.flush();
    };
    this.partialFlush = function() {
      nalByteStream.partialFlush();
    };
    this.reset = function() {
      nalByteStream.reset();
    };
    this.endTimeline = function() {
      nalByteStream.endTimeline();
    };
    skipScalingList = function skipScalingList2(count, expGolombDecoder) {
      var lastScale = 8, nextScale = 8, j, deltaScale;
      for (j = 0; j < count; j++) {
        if (nextScale !== 0) {
          deltaScale = expGolombDecoder.readExpGolomb();
          nextScale = (lastScale + deltaScale + 256) % 256;
        }
        lastScale = nextScale === 0 ? lastScale : nextScale;
      }
    };
    discardEmulationPreventionBytes4 = function discardEmulationPreventionBytes5(data) {
      var length = data.byteLength, emulationPreventionBytesPositions = [], i = 1, newLength, newData;
      while (i < length - 2) {
        if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 3) {
          emulationPreventionBytesPositions.push(i + 2);
          i += 2;
        } else {
          i++;
        }
      }
      if (emulationPreventionBytesPositions.length === 0) {
        return data;
      }
      newLength = length - emulationPreventionBytesPositions.length;
      newData = new Uint8Array(newLength);
      var sourceIndex = 0;
      for (i = 0; i < newLength; sourceIndex++, i++) {
        if (sourceIndex === emulationPreventionBytesPositions[0]) {
          sourceIndex++;
          emulationPreventionBytesPositions.shift();
        }
        newData[i] = data[sourceIndex];
      }
      return newData;
    };
    readSequenceParameterSet = function readSequenceParameterSet2(data) {
      var frameCropLeftOffset = 0, frameCropRightOffset = 0, frameCropTopOffset = 0, frameCropBottomOffset = 0, expGolombDecoder, profileIdc, levelIdc, profileCompatibility, chromaFormatIdc, picOrderCntType, numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1, picHeightInMapUnitsMinus1, frameMbsOnlyFlag, scalingListCount, sarRatio = [1, 1], aspectRatioIdc, i;
      expGolombDecoder = new expGolomb(data);
      profileIdc = expGolombDecoder.readUnsignedByte();
      profileCompatibility = expGolombDecoder.readUnsignedByte();
      levelIdc = expGolombDecoder.readUnsignedByte();
      expGolombDecoder.skipUnsignedExpGolomb();
      if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
        chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
        if (chromaFormatIdc === 3) {
          expGolombDecoder.skipBits(1);
        }
        expGolombDecoder.skipUnsignedExpGolomb();
        expGolombDecoder.skipUnsignedExpGolomb();
        expGolombDecoder.skipBits(1);
        if (expGolombDecoder.readBoolean()) {
          scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
          for (i = 0; i < scalingListCount; i++) {
            if (expGolombDecoder.readBoolean()) {
              if (i < 6) {
                skipScalingList(16, expGolombDecoder);
              } else {
                skipScalingList(64, expGolombDecoder);
              }
            }
          }
        }
      }
      expGolombDecoder.skipUnsignedExpGolomb();
      picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
      if (picOrderCntType === 0) {
        expGolombDecoder.readUnsignedExpGolomb();
      } else if (picOrderCntType === 1) {
        expGolombDecoder.skipBits(1);
        expGolombDecoder.skipExpGolomb();
        expGolombDecoder.skipExpGolomb();
        numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
        for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
          expGolombDecoder.skipExpGolomb();
        }
      }
      expGolombDecoder.skipUnsignedExpGolomb();
      expGolombDecoder.skipBits(1);
      picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
      picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
      frameMbsOnlyFlag = expGolombDecoder.readBits(1);
      if (frameMbsOnlyFlag === 0) {
        expGolombDecoder.skipBits(1);
      }
      expGolombDecoder.skipBits(1);
      if (expGolombDecoder.readBoolean()) {
        frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
        frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
        frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
        frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
      }
      if (expGolombDecoder.readBoolean()) {
        if (expGolombDecoder.readBoolean()) {
          aspectRatioIdc = expGolombDecoder.readUnsignedByte();
          switch (aspectRatioIdc) {
            case 1:
              sarRatio = [1, 1];
              break;
            case 2:
              sarRatio = [12, 11];
              break;
            case 3:
              sarRatio = [10, 11];
              break;
            case 4:
              sarRatio = [16, 11];
              break;
            case 5:
              sarRatio = [40, 33];
              break;
            case 6:
              sarRatio = [24, 11];
              break;
            case 7:
              sarRatio = [20, 11];
              break;
            case 8:
              sarRatio = [32, 11];
              break;
            case 9:
              sarRatio = [80, 33];
              break;
            case 10:
              sarRatio = [18, 11];
              break;
            case 11:
              sarRatio = [15, 11];
              break;
            case 12:
              sarRatio = [64, 33];
              break;
            case 13:
              sarRatio = [160, 99];
              break;
            case 14:
              sarRatio = [4, 3];
              break;
            case 15:
              sarRatio = [3, 2];
              break;
            case 16:
              sarRatio = [2, 1];
              break;
            case 255: {
              sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
              break;
            }
          }
          if (sarRatio) {
            sarRatio[0] / sarRatio[1];
          }
        }
      }
      return {
        profileIdc,
        levelIdc,
        profileCompatibility,
        width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
        height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
        // sar is sample aspect ratio
        sarRatio
      };
    };
  };
  _H264Stream.prototype = new stream();
  var h2642 = {
    H264Stream: _H264Stream,
    NalByteStream: _NalByteStream
  };
  var ADTS_SAMPLING_FREQUENCIES = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
  var parseId3TagSize = function parseId3TagSize2(header, byteIndex) {
    var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9], flags = header[byteIndex + 5], footerPresent = (flags & 16) >> 4;
    returnSize = returnSize >= 0 ? returnSize : 0;
    if (footerPresent) {
      return returnSize + 20;
    }
    return returnSize + 10;
  };
  var getId3Offset3 = function getId3Offset4(data, offset) {
    if (data.length - offset < 10 || data[offset] !== "I".charCodeAt(0) || data[offset + 1] !== "D".charCodeAt(0) || data[offset + 2] !== "3".charCodeAt(0)) {
      return offset;
    }
    offset += parseId3TagSize(data, offset);
    return getId3Offset4(data, offset);
  };
  var isLikelyAacData$1 = function isLikelyAacData2(data) {
    var offset = getId3Offset3(data, 0);
    return data.length >= offset + 2 && (data[offset] & 255) === 255 && (data[offset + 1] & 240) === 240 && // verify that the 2 layer bits are 0, aka this
    // is not mp3 data but aac data.
    (data[offset + 1] & 22) === 16;
  };
  var parseSyncSafeInteger = function parseSyncSafeInteger2(data) {
    return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  };
  var percentEncode = function percentEncode2(bytes, start2, end) {
    var i, result = "";
    for (i = start2; i < end; i++) {
      result += "%" + ("00" + bytes[i].toString(16)).slice(-2);
    }
    return result;
  };
  var parseIso88591 = function parseIso885912(bytes, start2, end) {
    return unescape(percentEncode(bytes, start2, end));
  };
  var parseAdtsSize = function parseAdtsSize2(header, byteIndex) {
    var lowThree = (header[byteIndex + 5] & 224) >> 5, middle = header[byteIndex + 4] << 3, highTwo = header[byteIndex + 3] & 3 << 11;
    return highTwo | middle | lowThree;
  };
  var parseType$2 = function parseType2(header, byteIndex) {
    if (header[byteIndex] === "I".charCodeAt(0) && header[byteIndex + 1] === "D".charCodeAt(0) && header[byteIndex + 2] === "3".charCodeAt(0)) {
      return "timed-metadata";
    } else if (header[byteIndex] & true && (header[byteIndex + 1] & 240) === 240) {
      return "audio";
    }
    return null;
  };
  var parseSampleRate = function parseSampleRate2(packet) {
    var i = 0;
    while (i + 5 < packet.length) {
      if (packet[i] !== 255 || (packet[i + 1] & 246) !== 240) {
        i++;
        continue;
      }
      return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 60) >>> 2];
    }
    return null;
  };
  var parseAacTimestamp = function parseAacTimestamp2(packet) {
    var frameStart, frameSize, frame, frameHeader;
    frameStart = 10;
    if (packet[5] & 64) {
      frameStart += 4;
      frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
    }
    do {
      frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
      if (frameSize < 1) {
        return null;
      }
      frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
      if (frameHeader === "PRIV") {
        frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
        for (var i = 0; i < frame.byteLength; i++) {
          if (frame[i] === 0) {
            var owner = parseIso88591(frame, 0, i);
            if (owner === "com.apple.streaming.transportStreamTimestamp") {
              var d2 = frame.subarray(i + 1);
              var size = (d2[3] & 1) << 30 | d2[4] << 22 | d2[5] << 14 | d2[6] << 6 | d2[7] >>> 2;
              size *= 4;
              size += d2[7] & 3;
              return size;
            }
            break;
          }
        }
      }
      frameStart += 10;
      frameStart += frameSize;
    } while (frameStart < packet.byteLength);
    return null;
  };
  var utils2 = {
    isLikelyAacData: isLikelyAacData$1,
    parseId3TagSize,
    parseAdtsSize,
    parseType: parseType$2,
    parseSampleRate,
    parseAacTimestamp
  };
  var _AacStream;
  _AacStream = function AacStream() {
    var everything = new Uint8Array(), timeStamp = 0;
    _AacStream.prototype.init.call(this);
    this.setTimestamp = function(timestamp) {
      timeStamp = timestamp;
    };
    this.push = function(bytes) {
      var frameSize = 0, byteIndex = 0, bytesLeft, chunk, packet, tempLength;
      if (everything.length) {
        tempLength = everything.length;
        everything = new Uint8Array(bytes.byteLength + tempLength);
        everything.set(everything.subarray(0, tempLength));
        everything.set(bytes, tempLength);
      } else {
        everything = bytes;
      }
      while (everything.length - byteIndex >= 3) {
        if (everything[byteIndex] === "I".charCodeAt(0) && everything[byteIndex + 1] === "D".charCodeAt(0) && everything[byteIndex + 2] === "3".charCodeAt(0)) {
          if (everything.length - byteIndex < 10) {
            break;
          }
          frameSize = utils2.parseId3TagSize(everything, byteIndex);
          if (byteIndex + frameSize > everything.length) {
            break;
          }
          chunk = {
            type: "timed-metadata",
            data: everything.subarray(byteIndex, byteIndex + frameSize)
          };
          this.trigger("data", chunk);
          byteIndex += frameSize;
          continue;
        } else if ((everything[byteIndex] & 255) === 255 && (everything[byteIndex + 1] & 240) === 240) {
          if (everything.length - byteIndex < 7) {
            break;
          }
          frameSize = utils2.parseAdtsSize(everything, byteIndex);
          if (byteIndex + frameSize > everything.length) {
            break;
          }
          packet = {
            type: "audio",
            data: everything.subarray(byteIndex, byteIndex + frameSize),
            pts: timeStamp,
            dts: timeStamp
          };
          this.trigger("data", packet);
          byteIndex += frameSize;
          continue;
        }
        byteIndex++;
      }
      bytesLeft = everything.length - byteIndex;
      if (bytesLeft > 0) {
        everything = everything.subarray(byteIndex);
      } else {
        everything = new Uint8Array();
      }
    };
    this.reset = function() {
      everything = new Uint8Array();
      this.trigger("reset");
    };
    this.endTimeline = function() {
      everything = new Uint8Array();
      this.trigger("endedtimeline");
    };
  };
  _AacStream.prototype = new stream();
  var aac2 = _AacStream;
  var AUDIO_PROPERTIES = ["audioobjecttype", "channelcount", "samplerate", "samplingfrequencyindex", "samplesize"];
  var audioProperties = AUDIO_PROPERTIES;
  var VIDEO_PROPERTIES = ["width", "height", "profileIdc", "levelIdc", "profileCompatibility", "sarRatio"];
  var videoProperties = VIDEO_PROPERTIES;
  var H264Stream = h2642.H264Stream;
  var isLikelyAacData = utils2.isLikelyAacData;
  var ONE_SECOND_IN_TS$1 = clock.ONE_SECOND_IN_TS;
  var _VideoSegmentStream, _AudioSegmentStream, _Transmuxer, _CoalesceStream;
  var retriggerForStream = function retriggerForStream2(key, event) {
    event.stream = key;
    this.trigger("log", event);
  };
  var addPipelineLogRetriggers = function addPipelineLogRetriggers2(transmuxer2, pipeline) {
    var keys3 = Object.keys(pipeline);
    for (var i = 0; i < keys3.length; i++) {
      var key = keys3[i];
      if (key === "headOfPipeline" || !pipeline[key].on) {
        continue;
      }
      pipeline[key].on("log", retriggerForStream.bind(transmuxer2, key));
    }
  };
  var arrayEquals = function arrayEquals2(a, b) {
    var i;
    if (a.length !== b.length) {
      return false;
    }
    for (i = 0; i < a.length; i++) {
      if (a[i] !== b[i]) {
        return false;
      }
    }
    return true;
  };
  var generateSegmentTimingInfo = function generateSegmentTimingInfo2(baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
    var ptsOffsetFromDts = startPts - startDts, decodeDuration = endDts - startDts, presentationDuration = endPts - startPts;
    return {
      start: {
        dts: baseMediaDecodeTime,
        pts: baseMediaDecodeTime + ptsOffsetFromDts
      },
      end: {
        dts: baseMediaDecodeTime + decodeDuration,
        pts: baseMediaDecodeTime + presentationDuration
      },
      prependedContentDuration,
      baseMediaDecodeTime
    };
  };
  _AudioSegmentStream = function AudioSegmentStream(track, options) {
    var adtsFrames = [], sequenceNumber, earliestAllowedDts = 0, audioAppendStartTs = 0, videoBaseMediaDecodeTime = Infinity;
    options = options || {};
    sequenceNumber = options.firstSequenceNumber || 0;
    _AudioSegmentStream.prototype.init.call(this);
    this.push = function(data) {
      trackDecodeInfo.collectDtsInfo(track, data);
      if (track) {
        audioProperties.forEach(function(prop) {
          track[prop] = data[prop];
        });
      }
      adtsFrames.push(data);
    };
    this.setEarliestDts = function(earliestDts) {
      earliestAllowedDts = earliestDts;
    };
    this.setVideoBaseMediaDecodeTime = function(baseMediaDecodeTime) {
      videoBaseMediaDecodeTime = baseMediaDecodeTime;
    };
    this.setAudioAppendStart = function(timestamp) {
      audioAppendStartTs = timestamp;
    };
    this.flush = function() {
      var frames, moof2, mdat2, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed;
      if (adtsFrames.length === 0) {
        this.trigger("done", "AudioSegmentStream");
        return;
      }
      frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
      track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
      videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime);
      track.samples = audioFrameUtils.generateSampleTable(frames);
      mdat2 = mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));
      adtsFrames = [];
      moof2 = mp4Generator.moof(sequenceNumber, [track]);
      boxes = new Uint8Array(moof2.byteLength + mdat2.byteLength);
      sequenceNumber++;
      boxes.set(moof2);
      boxes.set(mdat2, moof2.byteLength);
      trackDecodeInfo.clearDtsInfo(track);
      frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate);
      if (frames.length) {
        segmentDuration = frames.length * frameDuration;
        this.trigger("segmentTimingInfo", generateSegmentTimingInfo(
          // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
          // frame info is in video clock cycles. Convert to match expectation of
          // listeners (that all timestamps will be based on video clock cycles).
          clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate),
          // frame times are already in video clock, as is segment duration
          frames[0].dts,
          frames[0].pts,
          frames[0].dts + segmentDuration,
          frames[0].pts + segmentDuration,
          videoClockCyclesOfSilencePrefixed || 0
        ));
        this.trigger("timingInfo", {
          start: frames[0].pts,
          end: frames[0].pts + segmentDuration
        });
      }
      this.trigger("data", {
        track,
        boxes
      });
      this.trigger("done", "AudioSegmentStream");
    };
    this.reset = function() {
      trackDecodeInfo.clearDtsInfo(track);
      adtsFrames = [];
      this.trigger("reset");
    };
  };
  _AudioSegmentStream.prototype = new stream();
  _VideoSegmentStream = function VideoSegmentStream(track, options) {
    var sequenceNumber, nalUnits = [], gopsToAlignWith = [], config, pps;
    options = options || {};
    sequenceNumber = options.firstSequenceNumber || 0;
    _VideoSegmentStream.prototype.init.call(this);
    delete track.minPTS;
    this.gopCache_ = [];
    this.push = function(nalUnit) {
      trackDecodeInfo.collectDtsInfo(track, nalUnit);
      if (nalUnit.nalUnitType === "seq_parameter_set_rbsp" && !config) {
        config = nalUnit.config;
        track.sps = [nalUnit.data];
        videoProperties.forEach(function(prop) {
          track[prop] = config[prop];
        }, this);
      }
      if (nalUnit.nalUnitType === "pic_parameter_set_rbsp" && !pps) {
        pps = nalUnit.data;
        track.pps = [nalUnit.data];
      }
      nalUnits.push(nalUnit);
    };
    this.flush = function() {
      var frames, gopForFusion, gops, moof2, mdat2, boxes, prependedContentDuration = 0, firstGop, lastGop;
      while (nalUnits.length) {
        if (nalUnits[0].nalUnitType === "access_unit_delimiter_rbsp") {
          break;
        }
        nalUnits.shift();
      }
      if (nalUnits.length === 0) {
        this.resetStream_();
        this.trigger("done", "VideoSegmentStream");
        return;
      }
      frames = frameUtils.groupNalsIntoFrames(nalUnits);
      gops = frameUtils.groupFramesIntoGops(frames);
      if (!gops[0][0].keyFrame) {
        gopForFusion = this.getGopForFusion_(nalUnits[0], track);
        if (gopForFusion) {
          prependedContentDuration = gopForFusion.duration;
          gops.unshift(gopForFusion);
          gops.byteLength += gopForFusion.byteLength;
          gops.nalCount += gopForFusion.nalCount;
          gops.pts = gopForFusion.pts;
          gops.dts = gopForFusion.dts;
          gops.duration += gopForFusion.duration;
        } else {
          gops = frameUtils.extendFirstKeyFrame(gops);
        }
      }
      if (gopsToAlignWith.length) {
        var alignedGops;
        if (options.alignGopsAtEnd) {
          alignedGops = this.alignGopsAtEnd_(gops);
        } else {
          alignedGops = this.alignGopsAtStart_(gops);
        }
        if (!alignedGops) {
          this.gopCache_.unshift({
            gop: gops.pop(),
            pps: track.pps,
            sps: track.sps
          });
          this.gopCache_.length = Math.min(6, this.gopCache_.length);
          nalUnits = [];
          this.resetStream_();
          this.trigger("done", "VideoSegmentStream");
          return;
        }
        trackDecodeInfo.clearDtsInfo(track);
        gops = alignedGops;
      }
      trackDecodeInfo.collectDtsInfo(track, gops);
      track.samples = frameUtils.generateSampleTable(gops);
      mdat2 = mp4Generator.mdat(frameUtils.concatenateNalData(gops));
      track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
      this.trigger("processedGopsInfo", gops.map(function(gop) {
        return {
          pts: gop.pts,
          dts: gop.dts,
          byteLength: gop.byteLength
        };
      }));
      firstGop = gops[0];
      lastGop = gops[gops.length - 1];
      this.trigger("segmentTimingInfo", generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
      this.trigger("timingInfo", {
        start: gops[0].pts,
        end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
      });
      this.gopCache_.unshift({
        gop: gops.pop(),
        pps: track.pps,
        sps: track.sps
      });
      this.gopCache_.length = Math.min(6, this.gopCache_.length);
      nalUnits = [];
      this.trigger("baseMediaDecodeTime", track.baseMediaDecodeTime);
      this.trigger("timelineStartInfo", track.timelineStartInfo);
      moof2 = mp4Generator.moof(sequenceNumber, [track]);
      boxes = new Uint8Array(moof2.byteLength + mdat2.byteLength);
      sequenceNumber++;
      boxes.set(moof2);
      boxes.set(mdat2, moof2.byteLength);
      this.trigger("data", {
        track,
        boxes
      });
      this.resetStream_();
      this.trigger("done", "VideoSegmentStream");
    };
    this.reset = function() {
      this.resetStream_();
      nalUnits = [];
      this.gopCache_.length = 0;
      gopsToAlignWith.length = 0;
      this.trigger("reset");
    };
    this.resetStream_ = function() {
      trackDecodeInfo.clearDtsInfo(track);
      config = void 0;
      pps = void 0;
    };
    this.getGopForFusion_ = function(nalUnit) {
      var halfSecond = 45e3, allowableOverlap = 1e4, nearestDistance = Infinity, dtsDistance, nearestGopObj, currentGop, currentGopObj, i;
      for (i = 0; i < this.gopCache_.length; i++) {
        currentGopObj = this.gopCache_[i];
        currentGop = currentGopObj.gop;
        if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
          continue;
        }
        if (currentGop.dts < track.timelineStartInfo.dts) {
          continue;
        }
        dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration;
        if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
          if (!nearestGopObj || nearestDistance > dtsDistance) {
            nearestGopObj = currentGopObj;
            nearestDistance = dtsDistance;
          }
        }
      }
      if (nearestGopObj) {
        return nearestGopObj.gop;
      }
      return null;
    };
    this.alignGopsAtStart_ = function(gops) {
      var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration5, alignedGops;
      byteLength = gops.byteLength;
      nalCount = gops.nalCount;
      duration5 = gops.duration;
      alignIndex = gopIndex = 0;
      while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
        align = gopsToAlignWith[alignIndex];
        gop = gops[gopIndex];
        if (align.pts === gop.pts) {
          break;
        }
        if (gop.pts > align.pts) {
          alignIndex++;
          continue;
        }
        gopIndex++;
        byteLength -= gop.byteLength;
        nalCount -= gop.nalCount;
        duration5 -= gop.duration;
      }
      if (gopIndex === 0) {
        return gops;
      }
      if (gopIndex === gops.length) {
        return null;
      }
      alignedGops = gops.slice(gopIndex);
      alignedGops.byteLength = byteLength;
      alignedGops.duration = duration5;
      alignedGops.nalCount = nalCount;
      alignedGops.pts = alignedGops[0].pts;
      alignedGops.dts = alignedGops[0].dts;
      return alignedGops;
    };
    this.alignGopsAtEnd_ = function(gops) {
      var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
      alignIndex = gopsToAlignWith.length - 1;
      gopIndex = gops.length - 1;
      alignEndIndex = null;
      matchFound = false;
      while (alignIndex >= 0 && gopIndex >= 0) {
        align = gopsToAlignWith[alignIndex];
        gop = gops[gopIndex];
        if (align.pts === gop.pts) {
          matchFound = true;
          break;
        }
        if (align.pts > gop.pts) {
          alignIndex--;
          continue;
        }
        if (alignIndex === gopsToAlignWith.length - 1) {
          alignEndIndex = gopIndex;
        }
        gopIndex--;
      }
      if (!matchFound && alignEndIndex === null) {
        return null;
      }
      var trimIndex;
      if (matchFound) {
        trimIndex = gopIndex;
      } else {
        trimIndex = alignEndIndex;
      }
      if (trimIndex === 0) {
        return gops;
      }
      var alignedGops = gops.slice(trimIndex);
      var metadata = alignedGops.reduce(function(total, gop2) {
        total.byteLength += gop2.byteLength;
        total.duration += gop2.duration;
        total.nalCount += gop2.nalCount;
        return total;
      }, {
        byteLength: 0,
        duration: 0,
        nalCount: 0
      });
      alignedGops.byteLength = metadata.byteLength;
      alignedGops.duration = metadata.duration;
      alignedGops.nalCount = metadata.nalCount;
      alignedGops.pts = alignedGops[0].pts;
      alignedGops.dts = alignedGops[0].dts;
      return alignedGops;
    };
    this.alignGopsWith = function(newGopsToAlignWith) {
      gopsToAlignWith = newGopsToAlignWith;
    };
  };
  _VideoSegmentStream.prototype = new stream();
  _CoalesceStream = function CoalesceStream(options, metadataStream2) {
    this.numberOfTracks = 0;
    this.metadataStream = metadataStream2;
    options = options || {};
    if (typeof options.remux !== "undefined") {
      this.remuxTracks = !!options.remux;
    } else {
      this.remuxTracks = true;
    }
    if (typeof options.keepOriginalTimestamps === "boolean") {
      this.keepOriginalTimestamps = options.keepOriginalTimestamps;
    } else {
      this.keepOriginalTimestamps = false;
    }
    this.pendingTracks = [];
    this.videoTrack = null;
    this.pendingBoxes = [];
    this.pendingCaptions = [];
    this.pendingMetadata = [];
    this.pendingBytes = 0;
    this.emittedTracks = 0;
    _CoalesceStream.prototype.init.call(this);
    this.push = function(output) {
      if (output.text) {
        return this.pendingCaptions.push(output);
      }
      if (output.frames) {
        return this.pendingMetadata.push(output);
      }
      this.pendingTracks.push(output.track);
      this.pendingBytes += output.boxes.byteLength;
      if (output.track.type === "video") {
        this.videoTrack = output.track;
        this.pendingBoxes.push(output.boxes);
      }
      if (output.track.type === "audio") {
        this.audioTrack = output.track;
        this.pendingBoxes.unshift(output.boxes);
      }
    };
  };
  _CoalesceStream.prototype = new stream();
  _CoalesceStream.prototype.flush = function(flushSource) {
    var offset = 0, event = {
      captions: [],
      captionStreams: {},
      metadata: [],
      info: {}
    }, caption, id3, initSegment, timelineStartPts = 0, i;
    if (this.pendingTracks.length < this.numberOfTracks) {
      if (flushSource !== "VideoSegmentStream" && flushSource !== "AudioSegmentStream") {
        return;
      } else if (this.remuxTracks) {
        return;
      } else if (this.pendingTracks.length === 0) {
        this.emittedTracks++;
        if (this.emittedTracks >= this.numberOfTracks) {
          this.trigger("done");
          this.emittedTracks = 0;
        }
        return;
      }
    }
    if (this.videoTrack) {
      timelineStartPts = this.videoTrack.timelineStartInfo.pts;
      videoProperties.forEach(function(prop) {
        event.info[prop] = this.videoTrack[prop];
      }, this);
    } else if (this.audioTrack) {
      timelineStartPts = this.audioTrack.timelineStartInfo.pts;
      audioProperties.forEach(function(prop) {
        event.info[prop] = this.audioTrack[prop];
      }, this);
    }
    if (this.videoTrack || this.audioTrack) {
      if (this.pendingTracks.length === 1) {
        event.type = this.pendingTracks[0].type;
      } else {
        event.type = "combined";
      }
      this.emittedTracks += this.pendingTracks.length;
      initSegment = mp4Generator.initSegment(this.pendingTracks);
      event.initSegment = new Uint8Array(initSegment.byteLength);
      event.initSegment.set(initSegment);
      event.data = new Uint8Array(this.pendingBytes);
      for (i = 0; i < this.pendingBoxes.length; i++) {
        event.data.set(this.pendingBoxes[i], offset);
        offset += this.pendingBoxes[i].byteLength;
      }
      for (i = 0; i < this.pendingCaptions.length; i++) {
        caption = this.pendingCaptions[i];
        caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
        caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
        event.captionStreams[caption.stream] = true;
        event.captions.push(caption);
      }
      for (i = 0; i < this.pendingMetadata.length; i++) {
        id3 = this.pendingMetadata[i];
        id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
        event.metadata.push(id3);
      }
      event.metadata.dispatchType = this.metadataStream.dispatchType;
      this.pendingTracks.length = 0;
      this.videoTrack = null;
      this.pendingBoxes.length = 0;
      this.pendingCaptions.length = 0;
      this.pendingBytes = 0;
      this.pendingMetadata.length = 0;
      this.trigger("data", event);
      for (i = 0; i < event.captions.length; i++) {
        caption = event.captions[i];
        this.trigger("caption", caption);
      }
      for (i = 0; i < event.metadata.length; i++) {
        id3 = event.metadata[i];
        this.trigger("id3Frame", id3);
      }
    }
    if (this.emittedTracks >= this.numberOfTracks) {
      this.trigger("done");
      this.emittedTracks = 0;
    }
  };
  _CoalesceStream.prototype.setRemux = function(val) {
    this.remuxTracks = val;
  };
  _Transmuxer = function Transmuxer2(options) {
    var self2 = this, hasFlushed = true, videoTrack, audioTrack;
    _Transmuxer.prototype.init.call(this);
    options = options || {};
    this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
    this.transmuxPipeline_ = {};
    this.setupAacPipeline = function() {
      var pipeline = {};
      this.transmuxPipeline_ = pipeline;
      pipeline.type = "aac";
      pipeline.metadataStream = new m2ts_1.MetadataStream();
      pipeline.aacStream = new aac2();
      pipeline.audioTimestampRolloverStream = new m2ts_1.TimestampRolloverStream("audio");
      pipeline.timedMetadataTimestampRolloverStream = new m2ts_1.TimestampRolloverStream("timed-metadata");
      pipeline.adtsStream = new adts();
      pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
      pipeline.headOfPipeline = pipeline.aacStream;
      pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
      pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
      pipeline.metadataStream.on("timestamp", function(frame) {
        pipeline.aacStream.setTimestamp(frame.timeStamp);
      });
      pipeline.aacStream.on("data", function(data) {
        if (data.type !== "timed-metadata" && data.type !== "audio" || pipeline.audioSegmentStream) {
          return;
        }
        audioTrack = audioTrack || {
          timelineStartInfo: {
            baseMediaDecodeTime: self2.baseMediaDecodeTime
          },
          codec: "adts",
          type: "audio"
        };
        pipeline.coalesceStream.numberOfTracks++;
        pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
        pipeline.audioSegmentStream.on("log", self2.getLogTrigger_("audioSegmentStream"));
        pipeline.audioSegmentStream.on("timingInfo", self2.trigger.bind(self2, "audioTimingInfo"));
        pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
        self2.trigger("trackinfo", {
          hasAudio: !!audioTrack,
          hasVideo: !!videoTrack
        });
      });
      pipeline.coalesceStream.on("data", this.trigger.bind(this, "data"));
      pipeline.coalesceStream.on("done", this.trigger.bind(this, "done"));
      addPipelineLogRetriggers(this, pipeline);
    };
    this.setupTsPipeline = function() {
      var pipeline = {};
      this.transmuxPipeline_ = pipeline;
      pipeline.type = "ts";
      pipeline.metadataStream = new m2ts_1.MetadataStream();
      pipeline.packetStream = new m2ts_1.TransportPacketStream();
      pipeline.parseStream = new m2ts_1.TransportParseStream();
      pipeline.elementaryStream = new m2ts_1.ElementaryStream();
      pipeline.timestampRolloverStream = new m2ts_1.TimestampRolloverStream();
      pipeline.adtsStream = new adts();
      pipeline.h264Stream = new H264Stream();
      pipeline.captionStream = new m2ts_1.CaptionStream(options);
      pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
      pipeline.headOfPipeline = pipeline.packetStream;
      pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream);
      pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
      pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
      pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
      pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
      pipeline.elementaryStream.on("data", function(data) {
        var i;
        if (data.type === "metadata") {
          i = data.tracks.length;
          while (i--) {
            if (!videoTrack && data.tracks[i].type === "video") {
              videoTrack = data.tracks[i];
              videoTrack.timelineStartInfo.baseMediaDecodeTime = self2.baseMediaDecodeTime;
            } else if (!audioTrack && data.tracks[i].type === "audio") {
              audioTrack = data.tracks[i];
              audioTrack.timelineStartInfo.baseMediaDecodeTime = self2.baseMediaDecodeTime;
            }
          }
          if (videoTrack && !pipeline.videoSegmentStream) {
            pipeline.coalesceStream.numberOfTracks++;
            pipeline.videoSegmentStream = new _VideoSegmentStream(videoTrack, options);
            pipeline.videoSegmentStream.on("log", self2.getLogTrigger_("videoSegmentStream"));
            pipeline.videoSegmentStream.on("timelineStartInfo", function(timelineStartInfo) {
              if (audioTrack && !options.keepOriginalTimestamps) {
                audioTrack.timelineStartInfo = timelineStartInfo;
                pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self2.baseMediaDecodeTime);
              }
            });
            pipeline.videoSegmentStream.on("processedGopsInfo", self2.trigger.bind(self2, "gopInfo"));
            pipeline.videoSegmentStream.on("segmentTimingInfo", self2.trigger.bind(self2, "videoSegmentTimingInfo"));
            pipeline.videoSegmentStream.on("baseMediaDecodeTime", function(baseMediaDecodeTime) {
              if (audioTrack) {
                pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
              }
            });
            pipeline.videoSegmentStream.on("timingInfo", self2.trigger.bind(self2, "videoTimingInfo"));
            pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
          }
          if (audioTrack && !pipeline.audioSegmentStream) {
            pipeline.coalesceStream.numberOfTracks++;
            pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
            pipeline.audioSegmentStream.on("log", self2.getLogTrigger_("audioSegmentStream"));
            pipeline.audioSegmentStream.on("timingInfo", self2.trigger.bind(self2, "audioTimingInfo"));
            pipeline.audioSegmentStream.on("segmentTimingInfo", self2.trigger.bind(self2, "audioSegmentTimingInfo"));
            pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
          }
          self2.trigger("trackinfo", {
            hasAudio: !!audioTrack,
            hasVideo: !!videoTrack
          });
        }
      });
      pipeline.coalesceStream.on("data", this.trigger.bind(this, "data"));
      pipeline.coalesceStream.on("id3Frame", function(id3Frame) {
        id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
        self2.trigger("id3Frame", id3Frame);
      });
      pipeline.coalesceStream.on("caption", this.trigger.bind(this, "caption"));
      pipeline.coalesceStream.on("done", this.trigger.bind(this, "done"));
      addPipelineLogRetriggers(this, pipeline);
    };
    this.setBaseMediaDecodeTime = function(baseMediaDecodeTime) {
      var pipeline = this.transmuxPipeline_;
      if (!options.keepOriginalTimestamps) {
        this.baseMediaDecodeTime = baseMediaDecodeTime;
      }
      if (audioTrack) {
        audioTrack.timelineStartInfo.dts = void 0;
        audioTrack.timelineStartInfo.pts = void 0;
        trackDecodeInfo.clearDtsInfo(audioTrack);
        if (pipeline.audioTimestampRolloverStream) {
          pipeline.audioTimestampRolloverStream.discontinuity();
        }
      }
      if (videoTrack) {
        if (pipeline.videoSegmentStream) {
          pipeline.videoSegmentStream.gopCache_ = [];
        }
        videoTrack.timelineStartInfo.dts = void 0;
        videoTrack.timelineStartInfo.pts = void 0;
        trackDecodeInfo.clearDtsInfo(videoTrack);
        pipeline.captionStream.reset();
      }
      if (pipeline.timestampRolloverStream) {
        pipeline.timestampRolloverStream.discontinuity();
      }
    };
    this.setAudioAppendStart = function(timestamp) {
      if (audioTrack) {
        this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
      }
    };
    this.setRemux = function(val) {
      var pipeline = this.transmuxPipeline_;
      options.remux = val;
      if (pipeline && pipeline.coalesceStream) {
        pipeline.coalesceStream.setRemux(val);
      }
    };
    this.alignGopsWith = function(gopsToAlignWith) {
      if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
        this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
      }
    };
    this.getLogTrigger_ = function(key) {
      var self3 = this;
      return function(event) {
        event.stream = key;
        self3.trigger("log", event);
      };
    };
    this.push = function(data) {
      if (hasFlushed) {
        var isAac = isLikelyAacData(data);
        if (isAac && this.transmuxPipeline_.type !== "aac") {
          this.setupAacPipeline();
        } else if (!isAac && this.transmuxPipeline_.type !== "ts") {
          this.setupTsPipeline();
        }
        hasFlushed = false;
      }
      this.transmuxPipeline_.headOfPipeline.push(data);
    };
    this.flush = function() {
      hasFlushed = true;
      this.transmuxPipeline_.headOfPipeline.flush();
    };
    this.endTimeline = function() {
      this.transmuxPipeline_.headOfPipeline.endTimeline();
    };
    this.reset = function() {
      if (this.transmuxPipeline_.headOfPipeline) {
        this.transmuxPipeline_.headOfPipeline.reset();
      }
    };
    this.resetCaptions = function() {
      if (this.transmuxPipeline_.captionStream) {
        this.transmuxPipeline_.captionStream.reset();
      }
    };
  };
  _Transmuxer.prototype = new stream();
  var transmuxer = {
    Transmuxer: _Transmuxer,
    VideoSegmentStream: _VideoSegmentStream,
    AudioSegmentStream: _AudioSegmentStream,
    AUDIO_PROPERTIES: audioProperties,
    VIDEO_PROPERTIES: videoProperties,
    // exported for testing
    generateSegmentTimingInfo
  };
  var toUnsigned$3 = function toUnsigned2(value) {
    return value >>> 0;
  };
  var toHexString$1 = function toHexString3(value) {
    return ("00" + value.toString(16)).slice(-2);
  };
  var bin = {
    toUnsigned: toUnsigned$3,
    toHexString: toHexString$1
  };
  var parseType$1 = function parseType2(buffer) {
    var result = "";
    result += String.fromCharCode(buffer[0]);
    result += String.fromCharCode(buffer[1]);
    result += String.fromCharCode(buffer[2]);
    result += String.fromCharCode(buffer[3]);
    return result;
  };
  var parseType_1 = parseType$1;
  var toUnsigned$2 = bin.toUnsigned;
  var findBox4 = function findBox5(data, path) {
    var results = [], i, size, type3, end, subresults;
    if (!path.length) {
      return null;
    }
    for (i = 0; i < data.byteLength; ) {
      size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
      type3 = parseType_1(data.subarray(i + 4, i + 8));
      end = size > 1 ? i + size : data.byteLength;
      if (type3 === path[0]) {
        if (path.length === 1) {
          results.push(data.subarray(i + 8, end));
        } else {
          subresults = findBox5(data.subarray(i + 8, end), path.slice(1));
          if (subresults.length) {
            results = results.concat(subresults);
          }
        }
      }
      i = end;
    }
    return results;
  };
  var findBox_1 = findBox4;
  var toUnsigned$1 = bin.toUnsigned;
  var getUint64$1 = numbers.getUint64;
  var tfdt = function tfdt2(data) {
    var result = {
      version: data[0],
      flags: new Uint8Array(data.subarray(1, 4))
    };
    if (result.version === 1) {
      result.baseMediaDecodeTime = getUint64$1(data.subarray(4));
    } else {
      result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
    }
    return result;
  };
  var parseTfdt = tfdt;
  var parseSampleFlags = function parseSampleFlags2(flags) {
    return {
      isLeading: (flags[0] & 12) >>> 2,
      dependsOn: flags[0] & 3,
      isDependedOn: (flags[1] & 192) >>> 6,
      hasRedundancy: (flags[1] & 48) >>> 4,
      paddingValue: (flags[1] & 14) >>> 1,
      isNonSyncSample: flags[1] & 1,
      degradationPriority: flags[2] << 8 | flags[3]
    };
  };
  var parseSampleFlags_1 = parseSampleFlags;
  var trun = function trun2(data) {
    var result = {
      version: data[0],
      flags: new Uint8Array(data.subarray(1, 4)),
      samples: []
    }, view2 = new DataView(data.buffer, data.byteOffset, data.byteLength), dataOffsetPresent = result.flags[2] & 1, firstSampleFlagsPresent = result.flags[2] & 4, sampleDurationPresent = result.flags[1] & 1, sampleSizePresent = result.flags[1] & 2, sampleFlagsPresent = result.flags[1] & 4, sampleCompositionTimeOffsetPresent = result.flags[1] & 8, sampleCount = view2.getUint32(4), offset = 8, sample;
    if (dataOffsetPresent) {
      result.dataOffset = view2.getInt32(offset);
      offset += 4;
    }
    if (firstSampleFlagsPresent && sampleCount) {
      sample = {
        flags: parseSampleFlags_1(data.subarray(offset, offset + 4))
      };
      offset += 4;
      if (sampleDurationPresent) {
        sample.duration = view2.getUint32(offset);
        offset += 4;
      }
      if (sampleSizePresent) {
        sample.size = view2.getUint32(offset);
        offset += 4;
      }
      if (sampleCompositionTimeOffsetPresent) {
        if (result.version === 1) {
          sample.compositionTimeOffset = view2.getInt32(offset);
        } else {
          sample.compositionTimeOffset = view2.getUint32(offset);
        }
        offset += 4;
      }
      result.samples.push(sample);
      sampleCount--;
    }
    while (sampleCount--) {
      sample = {};
      if (sampleDurationPresent) {
        sample.duration = view2.getUint32(offset);
        offset += 4;
      }
      if (sampleSizePresent) {
        sample.size = view2.getUint32(offset);
        offset += 4;
      }
      if (sampleFlagsPresent) {
        sample.flags = parseSampleFlags_1(data.subarray(offset, offset + 4));
        offset += 4;
      }
      if (sampleCompositionTimeOffsetPresent) {
        if (result.version === 1) {
          sample.compositionTimeOffset = view2.getInt32(offset);
        } else {
          sample.compositionTimeOffset = view2.getUint32(offset);
        }
        offset += 4;
      }
      result.samples.push(sample);
    }
    return result;
  };
  var parseTrun = trun;
  var tfhd = function tfhd2(data) {
    var view2 = new DataView(data.buffer, data.byteOffset, data.byteLength), result = {
      version: data[0],
      flags: new Uint8Array(data.subarray(1, 4)),
      trackId: view2.getUint32(4)
    }, baseDataOffsetPresent = result.flags[2] & 1, sampleDescriptionIndexPresent = result.flags[2] & 2, defaultSampleDurationPresent = result.flags[2] & 8, defaultSampleSizePresent = result.flags[2] & 16, defaultSampleFlagsPresent = result.flags[2] & 32, durationIsEmpty = result.flags[0] & 65536, defaultBaseIsMoof = result.flags[0] & 131072, i;
    i = 8;
    if (baseDataOffsetPresent) {
      i += 4;
      result.baseDataOffset = view2.getUint32(12);
      i += 4;
    }
    if (sampleDescriptionIndexPresent) {
      result.sampleDescriptionIndex = view2.getUint32(i);
      i += 4;
    }
    if (defaultSampleDurationPresent) {
      result.defaultSampleDuration = view2.getUint32(i);
      i += 4;
    }
    if (defaultSampleSizePresent) {
      result.defaultSampleSize = view2.getUint32(i);
      i += 4;
    }
    if (defaultSampleFlagsPresent) {
      result.defaultSampleFlags = view2.getUint32(i);
    }
    if (durationIsEmpty) {
      result.durationIsEmpty = true;
    }
    if (!baseDataOffsetPresent && defaultBaseIsMoof) {
      result.baseDataOffsetIsMoof = true;
    }
    return result;
  };
  var parseTfhd = tfhd;
  var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
  var win;
  if (typeof window !== "undefined") {
    win = window;
  } else if (typeof commonjsGlobal !== "undefined") {
    win = commonjsGlobal;
  } else if (typeof self !== "undefined") {
    win = self;
  } else {
    win = {};
  }
  var window_1 = win;
  var discardEmulationPreventionBytes3 = captionPacketParser.discardEmulationPreventionBytes;
  var CaptionStream = captionStream.CaptionStream;
  var mapToSample = function mapToSample2(offset, samples) {
    var approximateOffset = offset;
    for (var i = 0; i < samples.length; i++) {
      var sample = samples[i];
      if (approximateOffset < sample.size) {
        return sample;
      }
      approximateOffset -= sample.size;
    }
    return null;
  };
  var findSeiNals = function findSeiNals2(avcStream, samples, trackId) {
    var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength), result = {
      logs: [],
      seiNals: []
    }, seiNal, i, length, lastMatchedSample;
    for (i = 0; i + 4 < avcStream.length; i += length) {
      length = avcView.getUint32(i);
      i += 4;
      if (length <= 0) {
        continue;
      }
      switch (avcStream[i] & 31) {
        case 6:
          var data = avcStream.subarray(i + 1, i + 1 + length);
          var matchingSample = mapToSample(i, samples);
          seiNal = {
            nalUnitType: "sei_rbsp",
            size: length,
            data,
            escapedRBSP: discardEmulationPreventionBytes3(data),
            trackId
          };
          if (matchingSample) {
            seiNal.pts = matchingSample.pts;
            seiNal.dts = matchingSample.dts;
            lastMatchedSample = matchingSample;
          } else if (lastMatchedSample) {
            seiNal.pts = lastMatchedSample.pts;
            seiNal.dts = lastMatchedSample.dts;
          } else {
            result.logs.push({
              level: "warn",
              message: "We've encountered a nal unit without data at " + i + " for trackId " + trackId + ". See mux.js#223."
            });
            break;
          }
          result.seiNals.push(seiNal);
          break;
      }
    }
    return result;
  };
  var parseSamples2 = function parseSamples3(truns, baseMediaDecodeTime, tfhd2) {
    var currentDts = baseMediaDecodeTime;
    var defaultSampleDuration = tfhd2.defaultSampleDuration || 0;
    var defaultSampleSize = tfhd2.defaultSampleSize || 0;
    var trackId = tfhd2.trackId;
    var allSamples = [];
    truns.forEach(function(trun2) {
      var trackRun = parseTrun(trun2);
      var samples = trackRun.samples;
      samples.forEach(function(sample) {
        if (sample.duration === void 0) {
          sample.duration = defaultSampleDuration;
        }
        if (sample.size === void 0) {
          sample.size = defaultSampleSize;
        }
        sample.trackId = trackId;
        sample.dts = currentDts;
        if (sample.compositionTimeOffset === void 0) {
          sample.compositionTimeOffset = 0;
        }
        if (typeof currentDts === "bigint") {
          sample.pts = currentDts + window_1.BigInt(sample.compositionTimeOffset);
          currentDts += window_1.BigInt(sample.duration);
        } else {
          sample.pts = currentDts + sample.compositionTimeOffset;
          currentDts += sample.duration;
        }
      });
      allSamples = allSamples.concat(samples);
    });
    return allSamples;
  };
  var parseCaptionNals = function parseCaptionNals2(segment, videoTrackId) {
    var trafs = findBox_1(segment, ["moof", "traf"]);
    var mdats = findBox_1(segment, ["mdat"]);
    var captionNals = {};
    var mdatTrafPairs = [];
    mdats.forEach(function(mdat2, index) {
      var matchingTraf = trafs[index];
      mdatTrafPairs.push({
        mdat: mdat2,
        traf: matchingTraf
      });
    });
    mdatTrafPairs.forEach(function(pair) {
      var mdat2 = pair.mdat;
      var traf2 = pair.traf;
      var tfhd2 = findBox_1(traf2, ["tfhd"]);
      var headerInfo = parseTfhd(tfhd2[0]);
      var trackId = headerInfo.trackId;
      var tfdt2 = findBox_1(traf2, ["tfdt"]);
      var baseMediaDecodeTime = tfdt2.length > 0 ? parseTfdt(tfdt2[0]).baseMediaDecodeTime : 0;
      var truns = findBox_1(traf2, ["trun"]);
      var samples;
      var result;
      if (videoTrackId === trackId && truns.length > 0) {
        samples = parseSamples2(truns, baseMediaDecodeTime, headerInfo);
        result = findSeiNals(mdat2, samples, trackId);
        if (!captionNals[trackId]) {
          captionNals[trackId] = {
            seiNals: [],
            logs: []
          };
        }
        captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
        captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
      }
    });
    return captionNals;
  };
  var parseEmbeddedCaptions = function parseEmbeddedCaptions2(segment, trackId, timescale3) {
    var captionNals;
    if (trackId === null) {
      return null;
    }
    captionNals = parseCaptionNals(segment, trackId);
    var trackNals = captionNals[trackId] || {};
    return {
      seiNals: trackNals.seiNals,
      logs: trackNals.logs,
      timescale: timescale3
    };
  };
  var CaptionParser = function CaptionParser2() {
    var isInitialized = false;
    var captionStream2;
    var segmentCache;
    var trackId;
    var timescale3;
    var parsedCaptions;
    var parsingPartial;
    this.isInitialized = function() {
      return isInitialized;
    };
    this.init = function(options) {
      captionStream2 = new CaptionStream();
      isInitialized = true;
      parsingPartial = options ? options.isPartial : false;
      captionStream2.on("data", function(event) {
        event.startTime = event.startPts / timescale3;
        event.endTime = event.endPts / timescale3;
        parsedCaptions.captions.push(event);
        parsedCaptions.captionStreams[event.stream] = true;
      });
      captionStream2.on("log", function(log2) {
        parsedCaptions.logs.push(log2);
      });
    };
    this.isNewInit = function(videoTrackIds, timescales) {
      if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === "object" && Object.keys(timescales).length === 0) {
        return false;
      }
      return trackId !== videoTrackIds[0] || timescale3 !== timescales[trackId];
    };
    this.parse = function(segment, videoTrackIds, timescales) {
      var parsedData;
      if (!this.isInitialized()) {
        return null;
      } else if (!videoTrackIds || !timescales) {
        return null;
      } else if (this.isNewInit(videoTrackIds, timescales)) {
        trackId = videoTrackIds[0];
        timescale3 = timescales[trackId];
      } else if (trackId === null || !timescale3) {
        segmentCache.push(segment);
        return null;
      }
      while (segmentCache.length > 0) {
        var cachedSegment = segmentCache.shift();
        this.parse(cachedSegment, videoTrackIds, timescales);
      }
      parsedData = parseEmbeddedCaptions(segment, trackId, timescale3);
      if (parsedData && parsedData.logs) {
        parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
      }
      if (parsedData === null || !parsedData.seiNals) {
        if (parsedCaptions.logs.length) {
          return {
            logs: parsedCaptions.logs,
            captions: [],
            captionStreams: []
          };
        }
        return null;
      }
      this.pushNals(parsedData.seiNals);
      this.flushStream();
      return parsedCaptions;
    };
    this.pushNals = function(nals) {
      if (!this.isInitialized() || !nals || nals.length === 0) {
        return null;
      }
      nals.forEach(function(nal) {
        captionStream2.push(nal);
      });
    };
    this.flushStream = function() {
      if (!this.isInitialized()) {
        return null;
      }
      if (!parsingPartial) {
        captionStream2.flush();
      } else {
        captionStream2.partialFlush();
      }
    };
    this.clearParsedCaptions = function() {
      parsedCaptions.captions = [];
      parsedCaptions.captionStreams = {};
      parsedCaptions.logs = [];
    };
    this.resetCaptionStream = function() {
      if (!this.isInitialized()) {
        return null;
      }
      captionStream2.reset();
    };
    this.clearAllCaptions = function() {
      this.clearParsedCaptions();
      this.resetCaptionStream();
    };
    this.reset = function() {
      segmentCache = [];
      trackId = null;
      timescale3 = null;
      if (!parsedCaptions) {
        parsedCaptions = {
          captions: [],
          // CC1, CC2, CC3, CC4
          captionStreams: {},
          logs: []
        };
      } else {
        this.clearParsedCaptions();
      }
      this.resetCaptionStream();
    };
    this.reset();
  };
  var captionParser = CaptionParser;
  var toUnsigned = bin.toUnsigned;
  var toHexString2 = bin.toHexString;
  var getUint64 = numbers.getUint64;
  var timescale2, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader;
  timescale2 = function timescale3(init) {
    var result = {}, traks = findBox_1(init, ["moov", "trak"]);
    return traks.reduce(function(result2, trak2) {
      var tkhd2, version6, index, id, mdhd2;
      tkhd2 = findBox_1(trak2, ["tkhd"])[0];
      if (!tkhd2) {
        return null;
      }
      version6 = tkhd2[0];
      index = version6 === 0 ? 12 : 20;
      id = toUnsigned(tkhd2[index] << 24 | tkhd2[index + 1] << 16 | tkhd2[index + 2] << 8 | tkhd2[index + 3]);
      mdhd2 = findBox_1(trak2, ["mdia", "mdhd"])[0];
      if (!mdhd2) {
        return null;
      }
      version6 = mdhd2[0];
      index = version6 === 0 ? 12 : 20;
      result2[id] = toUnsigned(mdhd2[index] << 24 | mdhd2[index + 1] << 16 | mdhd2[index + 2] << 8 | mdhd2[index + 3]);
      return result2;
    }, result);
  };
  startTime = function startTime2(timescale3, fragment) {
    var trafs;
    trafs = findBox_1(fragment, ["moof", "traf"]);
    var lowestTime = trafs.reduce(function(acc, traf2) {
      var tfhd2 = findBox_1(traf2, ["tfhd"])[0];
      var id = toUnsigned(tfhd2[4] << 24 | tfhd2[5] << 16 | tfhd2[6] << 8 | tfhd2[7]);
      var scale = timescale3[id] || 9e4;
      var tfdt2 = findBox_1(traf2, ["tfdt"])[0];
      var dv = new DataView(tfdt2.buffer, tfdt2.byteOffset, tfdt2.byteLength);
      var baseTime;
      if (tfdt2[0] === 1) {
        baseTime = getUint64(tfdt2.subarray(4, 12));
      } else {
        baseTime = dv.getUint32(4);
      }
      var seconds;
      if (typeof baseTime === "bigint") {
        seconds = baseTime / window_1.BigInt(scale);
      } else if (typeof baseTime === "number" && !isNaN(baseTime)) {
        seconds = baseTime / scale;
      }
      if (seconds < Number.MAX_SAFE_INTEGER) {
        seconds = Number(seconds);
      }
      if (seconds < acc) {
        acc = seconds;
      }
      return acc;
    }, Infinity);
    return typeof lowestTime === "bigint" || isFinite(lowestTime) ? lowestTime : 0;
  };
  compositionStartTime = function compositionStartTime2(timescales, fragment) {
    var trafBoxes = findBox_1(fragment, ["moof", "traf"]);
    var baseMediaDecodeTime = 0;
    var compositionTimeOffset = 0;
    var trackId;
    if (trafBoxes && trafBoxes.length) {
      var tfhd2 = findBox_1(trafBoxes[0], ["tfhd"])[0];
      var trun2 = findBox_1(trafBoxes[0], ["trun"])[0];
      var tfdt2 = findBox_1(trafBoxes[0], ["tfdt"])[0];
      if (tfhd2) {
        var parsedTfhd = parseTfhd(tfhd2);
        trackId = parsedTfhd.trackId;
      }
      if (tfdt2) {
        var parsedTfdt = parseTfdt(tfdt2);
        baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
      }
      if (trun2) {
        var parsedTrun = parseTrun(trun2);
        if (parsedTrun.samples && parsedTrun.samples.length) {
          compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
        }
      }
    }
    var timescale3 = timescales[trackId] || 9e4;
    if (typeof baseMediaDecodeTime === "bigint") {
      compositionTimeOffset = window_1.BigInt(compositionTimeOffset);
      timescale3 = window_1.BigInt(timescale3);
    }
    var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale3;
    if (typeof result === "bigint" && result < Number.MAX_SAFE_INTEGER) {
      result = Number(result);
    }
    return result;
  };
  getVideoTrackIds = function getVideoTrackIds2(init) {
    var traks = findBox_1(init, ["moov", "trak"]);
    var videoTrackIds = [];
    traks.forEach(function(trak2) {
      var hdlrs = findBox_1(trak2, ["mdia", "hdlr"]);
      var tkhds = findBox_1(trak2, ["tkhd"]);
      hdlrs.forEach(function(hdlr2, index) {
        var handlerType = parseType_1(hdlr2.subarray(8, 12));
        var tkhd2 = tkhds[index];
        var view2;
        var version6;
        var trackId;
        if (handlerType === "vide") {
          view2 = new DataView(tkhd2.buffer, tkhd2.byteOffset, tkhd2.byteLength);
          version6 = view2.getUint8(0);
          trackId = version6 === 0 ? view2.getUint32(12) : view2.getUint32(20);
          videoTrackIds.push(trackId);
        }
      });
    });
    return videoTrackIds;
  };
  getTimescaleFromMediaHeader = function getTimescaleFromMediaHeader2(mdhd2) {
    var version6 = mdhd2[0];
    var index = version6 === 0 ? 12 : 20;
    return toUnsigned(mdhd2[index] << 24 | mdhd2[index + 1] << 16 | mdhd2[index + 2] << 8 | mdhd2[index + 3]);
  };
  getTracks = function getTracks2(init) {
    var traks = findBox_1(init, ["moov", "trak"]);
    var tracks = [];
    traks.forEach(function(trak2) {
      var track = {};
      var tkhd2 = findBox_1(trak2, ["tkhd"])[0];
      var view2, tkhdVersion;
      if (tkhd2) {
        view2 = new DataView(tkhd2.buffer, tkhd2.byteOffset, tkhd2.byteLength);
        tkhdVersion = view2.getUint8(0);
        track.id = tkhdVersion === 0 ? view2.getUint32(12) : view2.getUint32(20);
      }
      var hdlr2 = findBox_1(trak2, ["mdia", "hdlr"])[0];
      if (hdlr2) {
        var type3 = parseType_1(hdlr2.subarray(8, 12));
        if (type3 === "vide") {
          track.type = "video";
        } else if (type3 === "soun") {
          track.type = "audio";
        } else {
          track.type = type3;
        }
      }
      var stsd2 = findBox_1(trak2, ["mdia", "minf", "stbl", "stsd"])[0];
      if (stsd2) {
        var sampleDescriptions = stsd2.subarray(8);
        track.codec = parseType_1(sampleDescriptions.subarray(4, 8));
        var codecBox = findBox_1(sampleDescriptions, [track.codec])[0];
        var codecConfig, codecConfigType;
        if (codecBox) {
          if (/^[asm]vc[1-9]$/i.test(track.codec)) {
            codecConfig = codecBox.subarray(78);
            codecConfigType = parseType_1(codecConfig.subarray(4, 8));
            if (codecConfigType === "avcC" && codecConfig.length > 11) {
              track.codec += ".";
              track.codec += toHexString2(codecConfig[9]);
              track.codec += toHexString2(codecConfig[10]);
              track.codec += toHexString2(codecConfig[11]);
            } else {
              track.codec = "avc1.4d400d";
            }
          } else if (/^mp4[a,v]$/i.test(track.codec)) {
            codecConfig = codecBox.subarray(28);
            codecConfigType = parseType_1(codecConfig.subarray(4, 8));
            if (codecConfigType === "esds" && codecConfig.length > 20 && codecConfig[19] !== 0) {
              track.codec += "." + toHexString2(codecConfig[19]);
              track.codec += "." + toHexString2(codecConfig[20] >>> 2 & 63).replace(/^0/, "");
            } else {
              track.codec = "mp4a.40.2";
            }
          } else {
            track.codec = track.codec.toLowerCase();
          }
        }
      }
      var mdhd2 = findBox_1(trak2, ["mdia", "mdhd"])[0];
      if (mdhd2) {
        track.timescale = getTimescaleFromMediaHeader(mdhd2);
      }
      tracks.push(track);
    });
    return tracks;
  };
  var probe$2 = {
    // export mp4 inspector's findBox and parseType for backwards compatibility
    findBox: findBox_1,
    parseType: parseType_1,
    timescale: timescale2,
    startTime,
    compositionStartTime,
    videoTrackIds: getVideoTrackIds,
    tracks: getTracks,
    getTimescaleFromMediaHeader
  };
  var parsePid = function parsePid2(packet) {
    var pid = packet[1] & 31;
    pid <<= 8;
    pid |= packet[2];
    return pid;
  };
  var parsePayloadUnitStartIndicator = function parsePayloadUnitStartIndicator2(packet) {
    return !!(packet[1] & 64);
  };
  var parseAdaptionField = function parseAdaptionField2(packet) {
    var offset = 0;
    if ((packet[3] & 48) >>> 4 > 1) {
      offset += packet[4] + 1;
    }
    return offset;
  };
  var parseType = function parseType2(packet, pmtPid) {
    var pid = parsePid(packet);
    if (pid === 0) {
      return "pat";
    } else if (pid === pmtPid) {
      return "pmt";
    } else if (pmtPid) {
      return "pes";
    }
    return null;
  };
  var parsePat = function parsePat2(packet) {
    var pusi = parsePayloadUnitStartIndicator(packet);
    var offset = 4 + parseAdaptionField(packet);
    if (pusi) {
      offset += packet[offset] + 1;
    }
    return (packet[offset + 10] & 31) << 8 | packet[offset + 11];
  };
  var parsePmt = function parsePmt2(packet) {
    var programMapTable = {};
    var pusi = parsePayloadUnitStartIndicator(packet);
    var payloadOffset = 4 + parseAdaptionField(packet);
    if (pusi) {
      payloadOffset += packet[payloadOffset] + 1;
    }
    if (!(packet[payloadOffset + 5] & 1)) {
      return;
    }
    var sectionLength, tableEnd, programInfoLength;
    sectionLength = (packet[payloadOffset + 1] & 15) << 8 | packet[payloadOffset + 2];
    tableEnd = 3 + sectionLength - 4;
    programInfoLength = (packet[payloadOffset + 10] & 15) << 8 | packet[payloadOffset + 11];
    var offset = 12 + programInfoLength;
    while (offset < tableEnd) {
      var i = payloadOffset + offset;
      programMapTable[(packet[i + 1] & 31) << 8 | packet[i + 2]] = packet[i];
      offset += ((packet[i + 3] & 15) << 8 | packet[i + 4]) + 5;
    }
    return programMapTable;
  };
  var parsePesType = function parsePesType2(packet, programMapTable) {
    var pid = parsePid(packet);
    var type3 = programMapTable[pid];
    switch (type3) {
      case streamTypes.H264_STREAM_TYPE:
        return "video";
      case streamTypes.ADTS_STREAM_TYPE:
        return "audio";
      case streamTypes.METADATA_STREAM_TYPE:
        return "timed-metadata";
      default:
        return null;
    }
  };
  var parsePesTime = function parsePesTime2(packet) {
    var pusi = parsePayloadUnitStartIndicator(packet);
    if (!pusi) {
      return null;
    }
    var offset = 4 + parseAdaptionField(packet);
    if (offset >= packet.byteLength) {
      return null;
    }
    var pes = null;
    var ptsDtsFlags;
    ptsDtsFlags = packet[offset + 7];
    if (ptsDtsFlags & 192) {
      pes = {};
      pes.pts = (packet[offset + 9] & 14) << 27 | (packet[offset + 10] & 255) << 20 | (packet[offset + 11] & 254) << 12 | (packet[offset + 12] & 255) << 5 | (packet[offset + 13] & 254) >>> 3;
      pes.pts *= 4;
      pes.pts += (packet[offset + 13] & 6) >>> 1;
      pes.dts = pes.pts;
      if (ptsDtsFlags & 64) {
        pes.dts = (packet[offset + 14] & 14) << 27 | (packet[offset + 15] & 255) << 20 | (packet[offset + 16] & 254) << 12 | (packet[offset + 17] & 255) << 5 | (packet[offset + 18] & 254) >>> 3;
        pes.dts *= 4;
        pes.dts += (packet[offset + 18] & 6) >>> 1;
      }
    }
    return pes;
  };
  var parseNalUnitType = function parseNalUnitType2(type3) {
    switch (type3) {
      case 5:
        return "slice_layer_without_partitioning_rbsp_idr";
      case 6:
        return "sei_rbsp";
      case 7:
        return "seq_parameter_set_rbsp";
      case 8:
        return "pic_parameter_set_rbsp";
      case 9:
        return "access_unit_delimiter_rbsp";
      default:
        return null;
    }
  };
  var videoPacketContainsKeyFrame = function videoPacketContainsKeyFrame2(packet) {
    var offset = 4 + parseAdaptionField(packet);
    var frameBuffer = packet.subarray(offset);
    var frameI = 0;
    var frameSyncPoint = 0;
    var foundKeyFrame = false;
    var nalType;
    for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
      if (frameBuffer[frameSyncPoint + 2] === 1) {
        frameI = frameSyncPoint + 5;
        break;
      }
    }
    while (frameI < frameBuffer.byteLength) {
      switch (frameBuffer[frameI]) {
        case 0:
          if (frameBuffer[frameI - 1] !== 0) {
            frameI += 2;
            break;
          } else if (frameBuffer[frameI - 2] !== 0) {
            frameI++;
            break;
          }
          if (frameSyncPoint + 3 !== frameI - 2) {
            nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 31);
            if (nalType === "slice_layer_without_partitioning_rbsp_idr") {
              foundKeyFrame = true;
            }
          }
          do {
            frameI++;
          } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
          frameSyncPoint = frameI - 2;
          frameI += 3;
          break;
        case 1:
          if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
            frameI += 3;
            break;
          }
          nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 31);
          if (nalType === "slice_layer_without_partitioning_rbsp_idr") {
            foundKeyFrame = true;
          }
          frameSyncPoint = frameI - 2;
          frameI += 3;
          break;
        default:
          frameI += 3;
          break;
      }
    }
    frameBuffer = frameBuffer.subarray(frameSyncPoint);
    frameI -= frameSyncPoint;
    frameSyncPoint = 0;
    if (frameBuffer && frameBuffer.byteLength > 3) {
      nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 31);
      if (nalType === "slice_layer_without_partitioning_rbsp_idr") {
        foundKeyFrame = true;
      }
    }
    return foundKeyFrame;
  };
  var probe$12 = {
    parseType,
    parsePat,
    parsePmt,
    parsePayloadUnitStartIndicator,
    parsePesType,
    parsePesTime,
    videoPacketContainsKeyFrame
  };
  var handleRollover = timestampRolloverStream.handleRollover;
  var probe2 = {};
  probe2.ts = probe$12;
  probe2.aac = utils2;
  var ONE_SECOND_IN_TS2 = clock.ONE_SECOND_IN_TS;
  var MP2T_PACKET_LENGTH = 188, SYNC_BYTE = 71;
  var parsePsi_ = function parsePsi_2(bytes, pmt) {
    var startIndex = 0, endIndex = MP2T_PACKET_LENGTH, packet, type3;
    while (endIndex < bytes.byteLength) {
      if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
        packet = bytes.subarray(startIndex, endIndex);
        type3 = probe2.ts.parseType(packet, pmt.pid);
        switch (type3) {
          case "pat":
            pmt.pid = probe2.ts.parsePat(packet);
            break;
          case "pmt":
            var table = probe2.ts.parsePmt(packet);
            pmt.table = pmt.table || {};
            Object.keys(table).forEach(function(key) {
              pmt.table[key] = table[key];
            });
            break;
        }
        startIndex += MP2T_PACKET_LENGTH;
        endIndex += MP2T_PACKET_LENGTH;
        continue;
      }
      startIndex++;
      endIndex++;
    }
  };
  var parseAudioPes_ = function parseAudioPes_2(bytes, pmt, result) {
    var startIndex = 0, endIndex = MP2T_PACKET_LENGTH, packet, type3, pesType, pusi, parsed;
    var endLoop = false;
    while (endIndex <= bytes.byteLength) {
      if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
        packet = bytes.subarray(startIndex, endIndex);
        type3 = probe2.ts.parseType(packet, pmt.pid);
        switch (type3) {
          case "pes":
            pesType = probe2.ts.parsePesType(packet, pmt.table);
            pusi = probe2.ts.parsePayloadUnitStartIndicator(packet);
            if (pesType === "audio" && pusi) {
              parsed = probe2.ts.parsePesTime(packet);
              if (parsed) {
                parsed.type = "audio";
                result.audio.push(parsed);
                endLoop = true;
              }
            }
            break;
        }
        if (endLoop) {
          break;
        }
        startIndex += MP2T_PACKET_LENGTH;
        endIndex += MP2T_PACKET_LENGTH;
        continue;
      }
      startIndex++;
      endIndex++;
    }
    endIndex = bytes.byteLength;
    startIndex = endIndex - MP2T_PACKET_LENGTH;
    endLoop = false;
    while (startIndex >= 0) {
      if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
        packet = bytes.subarray(startIndex, endIndex);
        type3 = probe2.ts.parseType(packet, pmt.pid);
        switch (type3) {
          case "pes":
            pesType = probe2.ts.parsePesType(packet, pmt.table);
            pusi = probe2.ts.parsePayloadUnitStartIndicator(packet);
            if (pesType === "audio" && pusi) {
              parsed = probe2.ts.parsePesTime(packet);
              if (parsed) {
                parsed.type = "audio";
                result.audio.push(parsed);
                endLoop = true;
              }
            }
            break;
        }
        if (endLoop) {
          break;
        }
        startIndex -= MP2T_PACKET_LENGTH;
        endIndex -= MP2T_PACKET_LENGTH;
        continue;
      }
      startIndex--;
      endIndex--;
    }
  };
  var parseVideoPes_ = function parseVideoPes_2(bytes, pmt, result) {
    var startIndex = 0, endIndex = MP2T_PACKET_LENGTH, packet, type3, pesType, pusi, parsed, frame, i, pes;
    var endLoop = false;
    var currentFrame = {
      data: [],
      size: 0
    };
    while (endIndex < bytes.byteLength) {
      if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
        packet = bytes.subarray(startIndex, endIndex);
        type3 = probe2.ts.parseType(packet, pmt.pid);
        switch (type3) {
          case "pes":
            pesType = probe2.ts.parsePesType(packet, pmt.table);
            pusi = probe2.ts.parsePayloadUnitStartIndicator(packet);
            if (pesType === "video") {
              if (pusi && !endLoop) {
                parsed = probe2.ts.parsePesTime(packet);
                if (parsed) {
                  parsed.type = "video";
                  result.video.push(parsed);
                  endLoop = true;
                }
              }
              if (!result.firstKeyFrame) {
                if (pusi) {
                  if (currentFrame.size !== 0) {
                    frame = new Uint8Array(currentFrame.size);
                    i = 0;
                    while (currentFrame.data.length) {
                      pes = currentFrame.data.shift();
                      frame.set(pes, i);
                      i += pes.byteLength;
                    }
                    if (probe2.ts.videoPacketContainsKeyFrame(frame)) {
                      var firstKeyFrame = probe2.ts.parsePesTime(frame);
                      if (firstKeyFrame) {
                        result.firstKeyFrame = firstKeyFrame;
                        result.firstKeyFrame.type = "video";
                      } else {
                        console.warn("Failed to extract PTS/DTS from PES at first keyframe. This could be an unusual TS segment, or else mux.js did not parse your TS segment correctly. If you know your TS segments do contain PTS/DTS on keyframes please file a bug report! You can try ffprobe to double check for yourself.");
                      }
                    }
                    currentFrame.size = 0;
                  }
                }
                currentFrame.data.push(packet);
                currentFrame.size += packet.byteLength;
              }
            }
            break;
        }
        if (endLoop && result.firstKeyFrame) {
          break;
        }
        startIndex += MP2T_PACKET_LENGTH;
        endIndex += MP2T_PACKET_LENGTH;
        continue;
      }
      startIndex++;
      endIndex++;
    }
    endIndex = bytes.byteLength;
    startIndex = endIndex - MP2T_PACKET_LENGTH;
    endLoop = false;
    while (startIndex >= 0) {
      if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
        packet = bytes.subarray(startIndex, endIndex);
        type3 = probe2.ts.parseType(packet, pmt.pid);
        switch (type3) {
          case "pes":
            pesType = probe2.ts.parsePesType(packet, pmt.table);
            pusi = probe2.ts.parsePayloadUnitStartIndicator(packet);
            if (pesType === "video" && pusi) {
              parsed = probe2.ts.parsePesTime(packet);
              if (parsed) {
                parsed.type = "video";
                result.video.push(parsed);
                endLoop = true;
              }
            }
            break;
        }
        if (endLoop) {
          break;
        }
        startIndex -= MP2T_PACKET_LENGTH;
        endIndex -= MP2T_PACKET_LENGTH;
        continue;
      }
      startIndex--;
      endIndex--;
    }
  };
  var adjustTimestamp_ = function adjustTimestamp_2(segmentInfo, baseTimestamp) {
    if (segmentInfo.audio && segmentInfo.audio.length) {
      var audioBaseTimestamp = baseTimestamp;
      if (typeof audioBaseTimestamp === "undefined" || isNaN(audioBaseTimestamp)) {
        audioBaseTimestamp = segmentInfo.audio[0].dts;
      }
      segmentInfo.audio.forEach(function(info) {
        info.dts = handleRollover(info.dts, audioBaseTimestamp);
        info.pts = handleRollover(info.pts, audioBaseTimestamp);
        info.dtsTime = info.dts / ONE_SECOND_IN_TS2;
        info.ptsTime = info.pts / ONE_SECOND_IN_TS2;
      });
    }
    if (segmentInfo.video && segmentInfo.video.length) {
      var videoBaseTimestamp = baseTimestamp;
      if (typeof videoBaseTimestamp === "undefined" || isNaN(videoBaseTimestamp)) {
        videoBaseTimestamp = segmentInfo.video[0].dts;
      }
      segmentInfo.video.forEach(function(info) {
        info.dts = handleRollover(info.dts, videoBaseTimestamp);
        info.pts = handleRollover(info.pts, videoBaseTimestamp);
        info.dtsTime = info.dts / ONE_SECOND_IN_TS2;
        info.ptsTime = info.pts / ONE_SECOND_IN_TS2;
      });
      if (segmentInfo.firstKeyFrame) {
        var frame = segmentInfo.firstKeyFrame;
        frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
        frame.pts = handleRollover(frame.pts, videoBaseTimestamp);
        frame.dtsTime = frame.dts / ONE_SECOND_IN_TS2;
        frame.ptsTime = frame.pts / ONE_SECOND_IN_TS2;
      }
    }
  };
  var inspectAac_ = function inspectAac_2(bytes) {
    var endLoop = false, audioCount = 0, sampleRate = null, timestamp = null, frameSize = 0, byteIndex = 0, packet;
    while (bytes.length - byteIndex >= 3) {
      var type3 = probe2.aac.parseType(bytes, byteIndex);
      switch (type3) {
        case "timed-metadata":
          if (bytes.length - byteIndex < 10) {
            endLoop = true;
            break;
          }
          frameSize = probe2.aac.parseId3TagSize(bytes, byteIndex);
          if (frameSize > bytes.length) {
            endLoop = true;
            break;
          }
          if (timestamp === null) {
            packet = bytes.subarray(byteIndex, byteIndex + frameSize);
            timestamp = probe2.aac.parseAacTimestamp(packet);
          }
          byteIndex += frameSize;
          break;
        case "audio":
          if (bytes.length - byteIndex < 7) {
            endLoop = true;
            break;
          }
          frameSize = probe2.aac.parseAdtsSize(bytes, byteIndex);
          if (frameSize > bytes.length) {
            endLoop = true;
            break;
          }
          if (sampleRate === null) {
            packet = bytes.subarray(byteIndex, byteIndex + frameSize);
            sampleRate = probe2.aac.parseSampleRate(packet);
          }
          audioCount++;
          byteIndex += frameSize;
          break;
        default:
          byteIndex++;
          break;
      }
      if (endLoop) {
        return null;
      }
    }
    if (sampleRate === null || timestamp === null) {
      return null;
    }
    var audioTimescale = ONE_SECOND_IN_TS2 / sampleRate;
    var result = {
      audio: [{
        type: "audio",
        dts: timestamp,
        pts: timestamp
      }, {
        type: "audio",
        dts: timestamp + audioCount * 1024 * audioTimescale,
        pts: timestamp + audioCount * 1024 * audioTimescale
      }]
    };
    return result;
  };
  var inspectTs_ = function inspectTs_2(bytes) {
    var pmt = {
      pid: null,
      table: null
    };
    var result = {};
    parsePsi_(bytes, pmt);
    for (var pid in pmt.table) {
      if (pmt.table.hasOwnProperty(pid)) {
        var type3 = pmt.table[pid];
        switch (type3) {
          case streamTypes.H264_STREAM_TYPE:
            result.video = [];
            parseVideoPes_(bytes, pmt, result);
            if (result.video.length === 0) {
              delete result.video;
            }
            break;
          case streamTypes.ADTS_STREAM_TYPE:
            result.audio = [];
            parseAudioPes_(bytes, pmt, result);
            if (result.audio.length === 0) {
              delete result.audio;
            }
            break;
        }
      }
    }
    return result;
  };
  var inspect = function inspect2(bytes, baseTimestamp) {
    var isAacData = probe2.aac.isLikelyAacData(bytes);
    var result;
    if (isAacData) {
      result = inspectAac_(bytes);
    } else {
      result = inspectTs_(bytes);
    }
    if (!result || !result.audio && !result.video) {
      return null;
    }
    adjustTimestamp_(result, baseTimestamp);
    return result;
  };
  var tsInspector = {
    inspect,
    parseAudioPes_
  };
  var wireTransmuxerEvents = function wireTransmuxerEvents2(self2, transmuxer2) {
    transmuxer2.on("data", function(segment) {
      var initArray = segment.initSegment;
      segment.initSegment = {
        data: initArray.buffer,
        byteOffset: initArray.byteOffset,
        byteLength: initArray.byteLength
      };
      var typedArray = segment.data;
      segment.data = typedArray.buffer;
      self2.postMessage({
        action: "data",
        segment,
        byteOffset: typedArray.byteOffset,
        byteLength: typedArray.byteLength
      }, [segment.data]);
    });
    transmuxer2.on("done", function(data) {
      self2.postMessage({
        action: "done"
      });
    });
    transmuxer2.on("gopInfo", function(gopInfo) {
      self2.postMessage({
        action: "gopInfo",
        gopInfo
      });
    });
    transmuxer2.on("videoSegmentTimingInfo", function(timingInfo) {
      var videoSegmentTimingInfo = {
        start: {
          decode: clock.videoTsToSeconds(timingInfo.start.dts),
          presentation: clock.videoTsToSeconds(timingInfo.start.pts)
        },
        end: {
          decode: clock.videoTsToSeconds(timingInfo.end.dts),
          presentation: clock.videoTsToSeconds(timingInfo.end.pts)
        },
        baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
      };
      if (timingInfo.prependedContentDuration) {
        videoSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
      }
      self2.postMessage({
        action: "videoSegmentTimingInfo",
        videoSegmentTimingInfo
      });
    });
    transmuxer2.on("audioSegmentTimingInfo", function(timingInfo) {
      var audioSegmentTimingInfo = {
        start: {
          decode: clock.videoTsToSeconds(timingInfo.start.dts),
          presentation: clock.videoTsToSeconds(timingInfo.start.pts)
        },
        end: {
          decode: clock.videoTsToSeconds(timingInfo.end.dts),
          presentation: clock.videoTsToSeconds(timingInfo.end.pts)
        },
        baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
      };
      if (timingInfo.prependedContentDuration) {
        audioSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
      }
      self2.postMessage({
        action: "audioSegmentTimingInfo",
        audioSegmentTimingInfo
      });
    });
    transmuxer2.on("id3Frame", function(id3Frame) {
      self2.postMessage({
        action: "id3Frame",
        id3Frame
      });
    });
    transmuxer2.on("caption", function(caption) {
      self2.postMessage({
        action: "caption",
        caption
      });
    });
    transmuxer2.on("trackinfo", function(trackInfo) {
      self2.postMessage({
        action: "trackinfo",
        trackInfo
      });
    });
    transmuxer2.on("audioTimingInfo", function(audioTimingInfo) {
      self2.postMessage({
        action: "audioTimingInfo",
        audioTimingInfo: {
          start: clock.videoTsToSeconds(audioTimingInfo.start),
          end: clock.videoTsToSeconds(audioTimingInfo.end)
        }
      });
    });
    transmuxer2.on("videoTimingInfo", function(videoTimingInfo) {
      self2.postMessage({
        action: "videoTimingInfo",
        videoTimingInfo: {
          start: clock.videoTsToSeconds(videoTimingInfo.start),
          end: clock.videoTsToSeconds(videoTimingInfo.end)
        }
      });
    });
    transmuxer2.on("log", function(log2) {
      self2.postMessage({
        action: "log",
        log: log2
      });
    });
  };
  var MessageHandlers = /* @__PURE__ */ function() {
    function MessageHandlers2(self2, options) {
      this.options = options || {};
      this.self = self2;
      this.init();
    }
    var _proto = MessageHandlers2.prototype;
    _proto.init = function init() {
      if (this.transmuxer) {
        this.transmuxer.dispose();
      }
      this.transmuxer = new transmuxer.Transmuxer(this.options);
      wireTransmuxerEvents(this.self, this.transmuxer);
    };
    _proto.pushMp4Captions = function pushMp4Captions(data) {
      if (!this.captionParser) {
        this.captionParser = new captionParser();
        this.captionParser.init();
      }
      var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
      var parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
      this.self.postMessage({
        action: "mp4Captions",
        captions: parsed && parsed.captions || [],
        logs: parsed && parsed.logs || [],
        data: segment.buffer
      }, [segment.buffer]);
    };
    _proto.probeMp4StartTime = function probeMp4StartTime(_ref) {
      var timescales = _ref.timescales, data = _ref.data;
      var startTime2 = probe$2.startTime(timescales, data);
      this.self.postMessage({
        action: "probeMp4StartTime",
        startTime: startTime2,
        data
      }, [data.buffer]);
    };
    _proto.probeMp4Tracks = function probeMp4Tracks(_ref2) {
      var data = _ref2.data;
      var tracks = probe$2.tracks(data);
      this.self.postMessage({
        action: "probeMp4Tracks",
        tracks,
        data
      }, [data.buffer]);
    };
    _proto.probeTs = function probeTs(_ref3) {
      var data = _ref3.data, baseStartTime = _ref3.baseStartTime;
      var tsStartTime = typeof baseStartTime === "number" && !isNaN(baseStartTime) ? baseStartTime * clock.ONE_SECOND_IN_TS : void 0;
      var timeInfo = tsInspector.inspect(data, tsStartTime);
      var result = null;
      if (timeInfo) {
        result = {
          // each type's time info comes back as an array of 2 times, start and end
          hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
          hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
        };
        if (result.hasVideo) {
          result.videoStart = timeInfo.video[0].ptsTime;
        }
        if (result.hasAudio) {
          result.audioStart = timeInfo.audio[0].ptsTime;
        }
      }
      this.self.postMessage({
        action: "probeTs",
        result,
        data
      }, [data.buffer]);
    };
    _proto.clearAllMp4Captions = function clearAllMp4Captions() {
      if (this.captionParser) {
        this.captionParser.clearAllCaptions();
      }
    };
    _proto.clearParsedMp4Captions = function clearParsedMp4Captions() {
      if (this.captionParser) {
        this.captionParser.clearParsedCaptions();
      }
    };
    _proto.push = function push2(data) {
      var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
      this.transmuxer.push(segment);
    };
    _proto.reset = function reset3() {
      this.transmuxer.reset();
    };
    _proto.setTimestampOffset = function setTimestampOffset(data) {
      var timestampOffset2 = data.timestampOffset || 0;
      this.transmuxer.setBaseMediaDecodeTime(Math.round(clock.secondsToVideoTs(timestampOffset2)));
    };
    _proto.setAudioAppendStart = function setAudioAppendStart(data) {
      this.transmuxer.setAudioAppendStart(Math.ceil(clock.secondsToVideoTs(data.appendStart)));
    };
    _proto.setRemux = function setRemux(data) {
      this.transmuxer.setRemux(data.remux);
    };
    _proto.flush = function flush(data) {
      this.transmuxer.flush();
      self.postMessage({
        action: "done",
        type: "transmuxed"
      });
    };
    _proto.endTimeline = function endTimeline3() {
      this.transmuxer.endTimeline();
      self.postMessage({
        action: "endedtimeline",
        type: "transmuxed"
      });
    };
    _proto.alignGopsWith = function alignGopsWith(data) {
      this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
    };
    return MessageHandlers2;
  }();
  self.onmessage = function(event) {
    if (event.data.action === "init" && event.data.options) {
      this.messageHandlers = new MessageHandlers(self, event.data.options);
      return;
    }
    if (!this.messageHandlers) {
      this.messageHandlers = new MessageHandlers(self);
    }
    if (event.data && event.data.action && event.data.action !== "init") {
      if (this.messageHandlers[event.data.action]) {
        this.messageHandlers[event.data.action](event.data);
      }
    }
  };
}));
var TransmuxWorker = factory(workerCode$1);
var handleData_ = function handleData_2(event, transmuxedData, callback2) {
  var _event$data$segment = event.data.segment, type2 = _event$data$segment.type, initSegment = _event$data$segment.initSegment, captions = _event$data$segment.captions, captionStreams = _event$data$segment.captionStreams, metadata = _event$data$segment.metadata, videoFrameDtsTime = _event$data$segment.videoFrameDtsTime, videoFramePtsTime = _event$data$segment.videoFramePtsTime;
  transmuxedData.buffer.push({
    captions,
    captionStreams,
    metadata
  });
  var boxes = event.data.segment.boxes || {
    data: event.data.segment.data
  };
  var result = {
    type: type2,
    // cast ArrayBuffer to TypedArray
    data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
    initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  };
  if (typeof videoFrameDtsTime !== "undefined") {
    result.videoFrameDtsTime = videoFrameDtsTime;
  }
  if (typeof videoFramePtsTime !== "undefined") {
    result.videoFramePtsTime = videoFramePtsTime;
  }
  callback2(result);
};
var handleDone_ = function handleDone_2(_ref) {
  var transmuxedData = _ref.transmuxedData, callback2 = _ref.callback;
  transmuxedData.buffer = [];
  callback2(transmuxedData);
};
var handleGopInfo_ = function handleGopInfo_2(event, transmuxedData) {
  transmuxedData.gopInfo = event.data.gopInfo;
};
var processTransmux = function processTransmux2(options) {
  var transmuxer = options.transmuxer, bytes = options.bytes, audioAppendStart = options.audioAppendStart, gopsToAlignWith = options.gopsToAlignWith, remux = options.remux, onData = options.onData, onTrackInfo = options.onTrackInfo, onAudioTimingInfo = options.onAudioTimingInfo, onVideoTimingInfo = options.onVideoTimingInfo, onVideoSegmentTimingInfo = options.onVideoSegmentTimingInfo, onAudioSegmentTimingInfo = options.onAudioSegmentTimingInfo, onId3 = options.onId3, onCaptions = options.onCaptions, onDone = options.onDone, onEndedTimeline = options.onEndedTimeline, onTransmuxerLog = options.onTransmuxerLog, isEndOfTimeline = options.isEndOfTimeline;
  var transmuxedData = {
    buffer: []
  };
  var waitForEndedTimelineEvent = isEndOfTimeline;
  var handleMessage = function handleMessage2(event) {
    if (transmuxer.currentTransmux !== options) {
      return;
    }
    if (event.data.action === "data") {
      handleData_(event, transmuxedData, onData);
    }
    if (event.data.action === "trackinfo") {
      onTrackInfo(event.data.trackInfo);
    }
    if (event.data.action === "gopInfo") {
      handleGopInfo_(event, transmuxedData);
    }
    if (event.data.action === "audioTimingInfo") {
      onAudioTimingInfo(event.data.audioTimingInfo);
    }
    if (event.data.action === "videoTimingInfo") {
      onVideoTimingInfo(event.data.videoTimingInfo);
    }
    if (event.data.action === "videoSegmentTimingInfo") {
      onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
    }
    if (event.data.action === "audioSegmentTimingInfo") {
      onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
    }
    if (event.data.action === "id3Frame") {
      onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
    }
    if (event.data.action === "caption") {
      onCaptions(event.data.caption);
    }
    if (event.data.action === "endedtimeline") {
      waitForEndedTimelineEvent = false;
      onEndedTimeline();
    }
    if (event.data.action === "log") {
      onTransmuxerLog(event.data.log);
    }
    if (event.data.type !== "transmuxed") {
      return;
    }
    if (waitForEndedTimelineEvent) {
      return;
    }
    transmuxer.onmessage = null;
    handleDone_({
      transmuxedData,
      callback: onDone
    });
    dequeue(transmuxer);
  };
  transmuxer.onmessage = handleMessage;
  if (audioAppendStart) {
    transmuxer.postMessage({
      action: "setAudioAppendStart",
      appendStart: audioAppendStart
    });
  }
  if (Array.isArray(gopsToAlignWith)) {
    transmuxer.postMessage({
      action: "alignGopsWith",
      gopsToAlignWith
    });
  }
  if (typeof remux !== "undefined") {
    transmuxer.postMessage({
      action: "setRemux",
      remux
    });
  }
  if (bytes.byteLength) {
    var buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
    var byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
    transmuxer.postMessage({
      action: "push",
      // Send the typed-array of data as an ArrayBuffer so that
      // it can be sent as a "Transferable" and avoid the costly
      // memory copy
      data: buffer,
      // To recreate the original typed-array, we need information
      // about what portion of the ArrayBuffer it was a view into
      byteOffset,
      byteLength: bytes.byteLength
    }, [buffer]);
  }
  if (isEndOfTimeline) {
    transmuxer.postMessage({
      action: "endTimeline"
    });
  }
  transmuxer.postMessage({
    action: "flush"
  });
};
var dequeue = function dequeue2(transmuxer) {
  transmuxer.currentTransmux = null;
  if (transmuxer.transmuxQueue.length) {
    transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
    if (typeof transmuxer.currentTransmux === "function") {
      transmuxer.currentTransmux();
    } else {
      processTransmux(transmuxer.currentTransmux);
    }
  }
};
var processAction = function processAction2(transmuxer, action) {
  transmuxer.postMessage({
    action
  });
  dequeue(transmuxer);
};
var enqueueAction = function enqueueAction2(action, transmuxer) {
  if (!transmuxer.currentTransmux) {
    transmuxer.currentTransmux = action;
    processAction(transmuxer, action);
    return;
  }
  transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
};
var reset = function reset2(transmuxer) {
  enqueueAction("reset", transmuxer);
};
var endTimeline = function endTimeline2(transmuxer) {
  enqueueAction("endTimeline", transmuxer);
};
var transmux = function transmux2(options) {
  if (!options.transmuxer.currentTransmux) {
    options.transmuxer.currentTransmux = options;
    processTransmux(options);
    return;
  }
  options.transmuxer.transmuxQueue.push(options);
};
var createTransmuxer = function createTransmuxer2(options) {
  var transmuxer = new TransmuxWorker();
  transmuxer.currentTransmux = null;
  transmuxer.transmuxQueue = [];
  var term = transmuxer.terminate;
  transmuxer.terminate = function() {
    transmuxer.currentTransmux = null;
    transmuxer.transmuxQueue.length = 0;
    return term.call(transmuxer);
  };
  transmuxer.postMessage({
    action: "init",
    options
  });
  return transmuxer;
};
var segmentTransmuxer = {
  reset,
  endTimeline,
  transmux,
  createTransmuxer
};
var workerCallback = function workerCallback2(options) {
  var transmuxer = options.transmuxer;
  var endAction = options.endAction || options.action;
  var callback2 = options.callback;
  var message = _extends2({}, options, {
    endAction: null,
    transmuxer: null,
    callback: null
  });
  var listenForEndEvent = function listenForEndEvent2(event) {
    if (event.data.action !== endAction) {
      return;
    }
    transmuxer.removeEventListener("message", listenForEndEvent2);
    if (event.data.data) {
      event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
      if (options.data) {
        options.data = event.data.data;
      }
    }
    callback2(event.data);
  };
  transmuxer.addEventListener("message", listenForEndEvent);
  if (options.data) {
    var isArrayBuffer = options.data instanceof ArrayBuffer;
    message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
    message.byteLength = options.data.byteLength;
    var transfers = [isArrayBuffer ? options.data : options.data.buffer];
    transmuxer.postMessage(message, transfers);
  } else {
    transmuxer.postMessage(message);
  }
};
var REQUEST_ERRORS = {
  FAILURE: 2,
  TIMEOUT: -101,
  ABORTED: -102
};
var abortAll = function abortAll2(activeXhrs) {
  activeXhrs.forEach(function(xhr) {
    xhr.abort();
  });
};
var getRequestStats = function getRequestStats2(request) {
  return {
    bandwidth: request.bandwidth,
    bytesReceived: request.bytesReceived || 0,
    roundTripTime: request.roundTripTime || 0
  };
};
var getProgressStats = function getProgressStats2(progressEvent) {
  var request = progressEvent.target;
  var roundTripTime = Date.now() - request.requestTime;
  var stats = {
    bandwidth: Infinity,
    bytesReceived: 0,
    roundTripTime: roundTripTime || 0
  };
  stats.bytesReceived = progressEvent.loaded;
  stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1e3);
  return stats;
};
var handleErrors = function handleErrors2(error, request) {
  if (request.timedout) {
    return {
      status: request.status,
      message: "HLS request timed-out at URL: " + request.uri,
      code: REQUEST_ERRORS.TIMEOUT,
      xhr: request
    };
  }
  if (request.aborted) {
    return {
      status: request.status,
      message: "HLS request aborted at URL: " + request.uri,
      code: REQUEST_ERRORS.ABORTED,
      xhr: request
    };
  }
  if (error) {
    return {
      status: request.status,
      message: "HLS request errored at URL: " + request.uri,
      code: REQUEST_ERRORS.FAILURE,
      xhr: request
    };
  }
  if (request.responseType === "arraybuffer" && request.response.byteLength === 0) {
    return {
      status: request.status,
      message: "Empty HLS response at URL: " + request.uri,
      code: REQUEST_ERRORS.FAILURE,
      xhr: request
    };
  }
  return null;
};
var handleKeyResponse = function handleKeyResponse2(segment, objects, finishProcessingFn) {
  return function(error, request) {
    var response = request.response;
    var errorObj = handleErrors(error, request);
    if (errorObj) {
      return finishProcessingFn(errorObj, segment);
    }
    if (response.byteLength !== 16) {
      return finishProcessingFn({
        status: request.status,
        message: "Invalid HLS key at URL: " + request.uri,
        code: REQUEST_ERRORS.FAILURE,
        xhr: request
      }, segment);
    }
    var view2 = new DataView(response);
    var bytes = new Uint32Array([view2.getUint32(0), view2.getUint32(4), view2.getUint32(8), view2.getUint32(12)]);
    for (var i = 0; i < objects.length; i++) {
      objects[i].bytes = bytes;
    }
    return finishProcessingFn(null, segment);
  };
};
var parseInitSegment2 = function parseInitSegment3(segment, _callback) {
  var type2 = detectContainerForBytes(segment.map.bytes);
  if (type2 !== "mp4") {
    var uri = segment.map.resolvedUri || segment.map.uri;
    return _callback({
      internal: true,
      message: "Found unsupported " + (type2 || "unknown") + " container for initialization segment at URL: " + uri,
      code: REQUEST_ERRORS.FAILURE
    });
  }
  workerCallback({
    action: "probeMp4Tracks",
    data: segment.map.bytes,
    transmuxer: segment.transmuxer,
    callback: function callback2(_ref) {
      var tracks = _ref.tracks, data = _ref.data;
      segment.map.bytes = data;
      tracks.forEach(function(track) {
        segment.map.tracks = segment.map.tracks || {};
        if (segment.map.tracks[track.type]) {
          return;
        }
        segment.map.tracks[track.type] = track;
        if (typeof track.id === "number" && track.timescale) {
          segment.map.timescales = segment.map.timescales || {};
          segment.map.timescales[track.id] = track.timescale;
        }
      });
      return _callback(null);
    }
  });
};
var handleInitSegmentResponse = function handleInitSegmentResponse2(_ref2) {
  var segment = _ref2.segment, finishProcessingFn = _ref2.finishProcessingFn;
  return function(error, request) {
    var errorObj = handleErrors(error, request);
    if (errorObj) {
      return finishProcessingFn(errorObj, segment);
    }
    var bytes = new Uint8Array(request.response);
    if (segment.map.key) {
      segment.map.encryptedBytes = bytes;
      return finishProcessingFn(null, segment);
    }
    segment.map.bytes = bytes;
    parseInitSegment2(segment, function(parseError) {
      if (parseError) {
        parseError.xhr = request;
        parseError.status = request.status;
        return finishProcessingFn(parseError, segment);
      }
      finishProcessingFn(null, segment);
    });
  };
};
var handleSegmentResponse = function handleSegmentResponse2(_ref3) {
  var segment = _ref3.segment, finishProcessingFn = _ref3.finishProcessingFn, responseType = _ref3.responseType;
  return function(error, request) {
    var errorObj = handleErrors(error, request);
    if (errorObj) {
      return finishProcessingFn(errorObj, segment);
    }
    var newBytes = (
      // although responseText "should" exist, this guard serves to prevent an error being
      // thrown for two primary cases:
      // 1. the mime type override stops working, or is not implemented for a specific
      //    browser
      // 2. when using mock XHR libraries like sinon that do not allow the override behavior
      responseType === "arraybuffer" || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0))
    );
    segment.stats = getRequestStats(request);
    if (segment.key) {
      segment.encryptedBytes = new Uint8Array(newBytes);
    } else {
      segment.bytes = new Uint8Array(newBytes);
    }
    return finishProcessingFn(null, segment);
  };
};
var transmuxAndNotify = function transmuxAndNotify2(_ref4) {
  var segment = _ref4.segment, bytes = _ref4.bytes, trackInfoFn = _ref4.trackInfoFn, timingInfoFn = _ref4.timingInfoFn, videoSegmentTimingInfoFn = _ref4.videoSegmentTimingInfoFn, audioSegmentTimingInfoFn = _ref4.audioSegmentTimingInfoFn, id3Fn = _ref4.id3Fn, captionsFn = _ref4.captionsFn, isEndOfTimeline = _ref4.isEndOfTimeline, endedTimelineFn = _ref4.endedTimelineFn, dataFn = _ref4.dataFn, doneFn = _ref4.doneFn, onTransmuxerLog = _ref4.onTransmuxerLog;
  var fmp4Tracks = segment.map && segment.map.tracks || {};
  var isMuxed3 = Boolean(fmp4Tracks.audio && fmp4Tracks.video);
  var audioStartFn = timingInfoFn.bind(null, segment, "audio", "start");
  var audioEndFn = timingInfoFn.bind(null, segment, "audio", "end");
  var videoStartFn = timingInfoFn.bind(null, segment, "video", "start");
  var videoEndFn = timingInfoFn.bind(null, segment, "video", "end");
  var finish = function finish2() {
    return transmux({
      bytes,
      transmuxer: segment.transmuxer,
      audioAppendStart: segment.audioAppendStart,
      gopsToAlignWith: segment.gopsToAlignWith,
      remux: isMuxed3,
      onData: function onData(result) {
        result.type = result.type === "combined" ? "video" : result.type;
        dataFn(segment, result);
      },
      onTrackInfo: function onTrackInfo(trackInfo) {
        if (trackInfoFn) {
          if (isMuxed3) {
            trackInfo.isMuxed = true;
          }
          trackInfoFn(segment, trackInfo);
        }
      },
      onAudioTimingInfo: function onAudioTimingInfo(audioTimingInfo) {
        if (audioStartFn && typeof audioTimingInfo.start !== "undefined") {
          audioStartFn(audioTimingInfo.start);
          audioStartFn = null;
        }
        if (audioEndFn && typeof audioTimingInfo.end !== "undefined") {
          audioEndFn(audioTimingInfo.end);
        }
      },
      onVideoTimingInfo: function onVideoTimingInfo(videoTimingInfo) {
        if (videoStartFn && typeof videoTimingInfo.start !== "undefined") {
          videoStartFn(videoTimingInfo.start);
          videoStartFn = null;
        }
        if (videoEndFn && typeof videoTimingInfo.end !== "undefined") {
          videoEndFn(videoTimingInfo.end);
        }
      },
      onVideoSegmentTimingInfo: function onVideoSegmentTimingInfo(videoSegmentTimingInfo) {
        videoSegmentTimingInfoFn(videoSegmentTimingInfo);
      },
      onAudioSegmentTimingInfo: function onAudioSegmentTimingInfo(audioSegmentTimingInfo) {
        audioSegmentTimingInfoFn(audioSegmentTimingInfo);
      },
      onId3: function onId3(id3Frames, dispatchType) {
        id3Fn(segment, id3Frames, dispatchType);
      },
      onCaptions: function onCaptions(captions) {
        captionsFn(segment, [captions]);
      },
      isEndOfTimeline,
      onEndedTimeline: function onEndedTimeline() {
        endedTimelineFn();
      },
      onTransmuxerLog,
      onDone: function onDone(result) {
        if (!doneFn) {
          return;
        }
        result.type = result.type === "combined" ? "video" : result.type;
        doneFn(null, segment, result);
      }
    });
  };
  workerCallback({
    action: "probeTs",
    transmuxer: segment.transmuxer,
    data: bytes,
    baseStartTime: segment.baseStartTime,
    callback: function callback2(data) {
      segment.bytes = bytes = data.data;
      var probeResult = data.result;
      if (probeResult) {
        trackInfoFn(segment, {
          hasAudio: probeResult.hasAudio,
          hasVideo: probeResult.hasVideo,
          isMuxed: isMuxed3
        });
        trackInfoFn = null;
        if (probeResult.hasAudio && !isMuxed3) {
          audioStartFn(probeResult.audioStart);
        }
        if (probeResult.hasVideo) {
          videoStartFn(probeResult.videoStart);
        }
        audioStartFn = null;
        videoStartFn = null;
      }
      finish();
    }
  });
};
var handleSegmentBytes = function handleSegmentBytes2(_ref5) {
  var segment = _ref5.segment, bytes = _ref5.bytes, trackInfoFn = _ref5.trackInfoFn, timingInfoFn = _ref5.timingInfoFn, videoSegmentTimingInfoFn = _ref5.videoSegmentTimingInfoFn, audioSegmentTimingInfoFn = _ref5.audioSegmentTimingInfoFn, id3Fn = _ref5.id3Fn, captionsFn = _ref5.captionsFn, isEndOfTimeline = _ref5.isEndOfTimeline, endedTimelineFn = _ref5.endedTimelineFn, dataFn = _ref5.dataFn, doneFn = _ref5.doneFn, onTransmuxerLog = _ref5.onTransmuxerLog;
  var bytesAsUint8Array = new Uint8Array(bytes);
  if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
    segment.isFmp4 = true;
    var tracks = segment.map.tracks;
    var trackInfo = {
      isFmp4: true,
      hasVideo: !!tracks.video,
      hasAudio: !!tracks.audio
    };
    if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== "enca") {
      trackInfo.audioCodec = tracks.audio.codec;
    }
    if (tracks.video && tracks.video.codec && tracks.video.codec !== "encv") {
      trackInfo.videoCodec = tracks.video.codec;
    }
    if (tracks.video && tracks.audio) {
      trackInfo.isMuxed = true;
    }
    trackInfoFn(segment, trackInfo);
    var finishLoading = function finishLoading2(captions) {
      dataFn(segment, {
        data: bytesAsUint8Array,
        type: trackInfo.hasAudio && !trackInfo.isMuxed ? "audio" : "video"
      });
      if (captions && captions.length) {
        captionsFn(segment, captions);
      }
      doneFn(null, segment, {});
    };
    workerCallback({
      action: "probeMp4StartTime",
      timescales: segment.map.timescales,
      data: bytesAsUint8Array,
      transmuxer: segment.transmuxer,
      callback: function callback2(_ref6) {
        var data = _ref6.data, startTime = _ref6.startTime;
        bytes = data.buffer;
        segment.bytes = bytesAsUint8Array = data;
        if (trackInfo.hasAudio && !trackInfo.isMuxed) {
          timingInfoFn(segment, "audio", "start", startTime);
        }
        if (trackInfo.hasVideo) {
          timingInfoFn(segment, "video", "start", startTime);
        }
        if (!tracks.video || !data.byteLength || !segment.transmuxer) {
          finishLoading();
          return;
        }
        workerCallback({
          action: "pushMp4Captions",
          endAction: "mp4Captions",
          transmuxer: segment.transmuxer,
          data: bytesAsUint8Array,
          timescales: segment.map.timescales,
          trackIds: [tracks.video.id],
          callback: function callback3(message) {
            bytes = message.data.buffer;
            segment.bytes = bytesAsUint8Array = message.data;
            message.logs.forEach(function(log2) {
              onTransmuxerLog(videojs.mergeOptions(log2, {
                stream: "mp4CaptionParser"
              }));
            });
            finishLoading(message.captions);
          }
        });
      }
    });
    return;
  }
  if (!segment.transmuxer) {
    doneFn(null, segment, {});
    return;
  }
  if (typeof segment.container === "undefined") {
    segment.container = detectContainerForBytes(bytesAsUint8Array);
  }
  if (segment.container !== "ts" && segment.container !== "aac") {
    trackInfoFn(segment, {
      hasAudio: false,
      hasVideo: false
    });
    doneFn(null, segment, {});
    return;
  }
  transmuxAndNotify({
    segment,
    bytes,
    trackInfoFn,
    timingInfoFn,
    videoSegmentTimingInfoFn,
    audioSegmentTimingInfoFn,
    id3Fn,
    captionsFn,
    isEndOfTimeline,
    endedTimelineFn,
    dataFn,
    doneFn,
    onTransmuxerLog
  });
};
var decrypt = function decrypt2(_ref7, callback2) {
  var id = _ref7.id, key = _ref7.key, encryptedBytes = _ref7.encryptedBytes, decryptionWorker = _ref7.decryptionWorker;
  var decryptionHandler = function decryptionHandler2(event) {
    if (event.data.source === id) {
      decryptionWorker.removeEventListener("message", decryptionHandler2);
      var decrypted = event.data.decrypted;
      callback2(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
    }
  };
  decryptionWorker.addEventListener("message", decryptionHandler);
  var keyBytes;
  if (key.bytes.slice) {
    keyBytes = key.bytes.slice();
  } else {
    keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  }
  decryptionWorker.postMessage(createTransferableMessage({
    source: id,
    encrypted: encryptedBytes,
    key: keyBytes,
    iv: key.iv
  }), [encryptedBytes.buffer, keyBytes.buffer]);
};
var decryptSegment = function decryptSegment2(_ref8) {
  var decryptionWorker = _ref8.decryptionWorker, segment = _ref8.segment, trackInfoFn = _ref8.trackInfoFn, timingInfoFn = _ref8.timingInfoFn, videoSegmentTimingInfoFn = _ref8.videoSegmentTimingInfoFn, audioSegmentTimingInfoFn = _ref8.audioSegmentTimingInfoFn, id3Fn = _ref8.id3Fn, captionsFn = _ref8.captionsFn, isEndOfTimeline = _ref8.isEndOfTimeline, endedTimelineFn = _ref8.endedTimelineFn, dataFn = _ref8.dataFn, doneFn = _ref8.doneFn, onTransmuxerLog = _ref8.onTransmuxerLog;
  decrypt({
    id: segment.requestId,
    key: segment.key,
    encryptedBytes: segment.encryptedBytes,
    decryptionWorker
  }, function(decryptedBytes) {
    segment.bytes = decryptedBytes;
    handleSegmentBytes({
      segment,
      bytes: segment.bytes,
      trackInfoFn,
      timingInfoFn,
      videoSegmentTimingInfoFn,
      audioSegmentTimingInfoFn,
      id3Fn,
      captionsFn,
      isEndOfTimeline,
      endedTimelineFn,
      dataFn,
      doneFn,
      onTransmuxerLog
    });
  });
};
var waitForCompletion = function waitForCompletion2(_ref9) {
  var activeXhrs = _ref9.activeXhrs, decryptionWorker = _ref9.decryptionWorker, trackInfoFn = _ref9.trackInfoFn, timingInfoFn = _ref9.timingInfoFn, videoSegmentTimingInfoFn = _ref9.videoSegmentTimingInfoFn, audioSegmentTimingInfoFn = _ref9.audioSegmentTimingInfoFn, id3Fn = _ref9.id3Fn, captionsFn = _ref9.captionsFn, isEndOfTimeline = _ref9.isEndOfTimeline, endedTimelineFn = _ref9.endedTimelineFn, dataFn = _ref9.dataFn, doneFn = _ref9.doneFn, onTransmuxerLog = _ref9.onTransmuxerLog;
  var count = 0;
  var didError = false;
  return function(error, segment) {
    if (didError) {
      return;
    }
    if (error) {
      didError = true;
      abortAll(activeXhrs);
      return doneFn(error, segment);
    }
    count += 1;
    if (count === activeXhrs.length) {
      var segmentFinish = function segmentFinish2() {
        if (segment.encryptedBytes) {
          return decryptSegment({
            decryptionWorker,
            segment,
            trackInfoFn,
            timingInfoFn,
            videoSegmentTimingInfoFn,
            audioSegmentTimingInfoFn,
            id3Fn,
            captionsFn,
            isEndOfTimeline,
            endedTimelineFn,
            dataFn,
            doneFn,
            onTransmuxerLog
          });
        }
        handleSegmentBytes({
          segment,
          bytes: segment.bytes,
          trackInfoFn,
          timingInfoFn,
          videoSegmentTimingInfoFn,
          audioSegmentTimingInfoFn,
          id3Fn,
          captionsFn,
          isEndOfTimeline,
          endedTimelineFn,
          dataFn,
          doneFn,
          onTransmuxerLog
        });
      };
      segment.endOfAllRequests = Date.now();
      if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
        return decrypt({
          decryptionWorker,
          // add -init to the "id" to differentiate between segment
          // and init segment decryption, just in case they happen
          // at the same time at some point in the future.
          id: segment.requestId + "-init",
          encryptedBytes: segment.map.encryptedBytes,
          key: segment.map.key
        }, function(decryptedBytes) {
          segment.map.bytes = decryptedBytes;
          parseInitSegment2(segment, function(parseError) {
            if (parseError) {
              abortAll(activeXhrs);
              return doneFn(parseError, segment);
            }
            segmentFinish();
          });
        });
      }
      segmentFinish();
    }
  };
};
var handleLoadEnd = function handleLoadEnd2(_ref10) {
  var loadendState = _ref10.loadendState, abortFn = _ref10.abortFn;
  return function(event) {
    var request = event.target;
    if (request.aborted && abortFn && !loadendState.calledAbortFn) {
      abortFn();
      loadendState.calledAbortFn = true;
    }
  };
};
var handleProgress = function handleProgress2(_ref11) {
  var segment = _ref11.segment, progressFn = _ref11.progressFn;
  _ref11.trackInfoFn;
  _ref11.timingInfoFn;
  _ref11.videoSegmentTimingInfoFn;
  _ref11.audioSegmentTimingInfoFn;
  _ref11.id3Fn;
  _ref11.captionsFn;
  _ref11.isEndOfTimeline;
  _ref11.endedTimelineFn;
  _ref11.dataFn;
  return function(event) {
    var request = event.target;
    if (request.aborted) {
      return;
    }
    segment.stats = videojs.mergeOptions(segment.stats, getProgressStats(event));
    if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
      segment.stats.firstBytesReceivedAt = Date.now();
    }
    return progressFn(event, segment);
  };
};
var mediaSegmentRequest = function mediaSegmentRequest2(_ref12) {
  var xhr = _ref12.xhr, xhrOptions = _ref12.xhrOptions, decryptionWorker = _ref12.decryptionWorker, segment = _ref12.segment, abortFn = _ref12.abortFn, progressFn = _ref12.progressFn, trackInfoFn = _ref12.trackInfoFn, timingInfoFn = _ref12.timingInfoFn, videoSegmentTimingInfoFn = _ref12.videoSegmentTimingInfoFn, audioSegmentTimingInfoFn = _ref12.audioSegmentTimingInfoFn, id3Fn = _ref12.id3Fn, captionsFn = _ref12.captionsFn, isEndOfTimeline = _ref12.isEndOfTimeline, endedTimelineFn = _ref12.endedTimelineFn, dataFn = _ref12.dataFn, doneFn = _ref12.doneFn, onTransmuxerLog = _ref12.onTransmuxerLog;
  var activeXhrs = [];
  var finishProcessingFn = waitForCompletion({
    activeXhrs,
    decryptionWorker,
    trackInfoFn,
    timingInfoFn,
    videoSegmentTimingInfoFn,
    audioSegmentTimingInfoFn,
    id3Fn,
    captionsFn,
    isEndOfTimeline,
    endedTimelineFn,
    dataFn,
    doneFn,
    onTransmuxerLog
  });
  if (segment.key && !segment.key.bytes) {
    var objects = [segment.key];
    if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
      objects.push(segment.map.key);
    }
    var keyRequestOptions = videojs.mergeOptions(xhrOptions, {
      uri: segment.key.resolvedUri,
      responseType: "arraybuffer"
    });
    var keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
    var keyXhr = xhr(keyRequestOptions, keyRequestCallback);
    activeXhrs.push(keyXhr);
  }
  if (segment.map && !segment.map.bytes) {
    var differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
    if (differentMapKey) {
      var mapKeyRequestOptions = videojs.mergeOptions(xhrOptions, {
        uri: segment.map.key.resolvedUri,
        responseType: "arraybuffer"
      });
      var mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
      var mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
      activeXhrs.push(mapKeyXhr);
    }
    var initSegmentOptions = videojs.mergeOptions(xhrOptions, {
      uri: segment.map.resolvedUri,
      responseType: "arraybuffer",
      headers: segmentXhrHeaders(segment.map)
    });
    var initSegmentRequestCallback = handleInitSegmentResponse({
      segment,
      finishProcessingFn
    });
    var initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
    activeXhrs.push(initSegmentXhr);
  }
  var segmentRequestOptions = videojs.mergeOptions(xhrOptions, {
    uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
    responseType: "arraybuffer",
    headers: segmentXhrHeaders(segment)
  });
  var segmentRequestCallback = handleSegmentResponse({
    segment,
    finishProcessingFn,
    responseType: segmentRequestOptions.responseType
  });
  var segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  segmentXhr.addEventListener("progress", handleProgress({
    segment,
    progressFn,
    trackInfoFn,
    timingInfoFn,
    videoSegmentTimingInfoFn,
    audioSegmentTimingInfoFn,
    id3Fn,
    captionsFn,
    isEndOfTimeline,
    endedTimelineFn,
    dataFn
  }));
  activeXhrs.push(segmentXhr);
  var loadendState = {};
  activeXhrs.forEach(function(activeXhr) {
    activeXhr.addEventListener("loadend", handleLoadEnd({
      loadendState,
      abortFn
    }));
  });
  return function() {
    return abortAll(activeXhrs);
  };
};
var logFn$1 = logger2("CodecUtils");
var getCodecs = function getCodecs2(media) {
  var mediaAttributes = media.attributes || {};
  if (mediaAttributes.CODECS) {
    return parseCodecs(mediaAttributes.CODECS);
  }
};
var isMaat = function isMaat2(master, media) {
  var mediaAttributes = media.attributes || {};
  return master && master.mediaGroups && master.mediaGroups.AUDIO && mediaAttributes.AUDIO && master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
};
var isMuxed = function isMuxed2(master, media) {
  if (!isMaat(master, media)) {
    return true;
  }
  var mediaAttributes = media.attributes || {};
  var audioGroup = master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  for (var groupId in audioGroup) {
    if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
      return true;
    }
  }
  return false;
};
var unwrapCodecList = function unwrapCodecList2(codecList) {
  var codecs = {};
  codecList.forEach(function(_ref) {
    var mediaType = _ref.mediaType, type2 = _ref.type, details = _ref.details;
    codecs[mediaType] = codecs[mediaType] || [];
    codecs[mediaType].push(translateLegacyCodec("" + type2 + details));
  });
  Object.keys(codecs).forEach(function(mediaType) {
    if (codecs[mediaType].length > 1) {
      logFn$1("multiple " + mediaType + " codecs found as attributes: " + codecs[mediaType].join(", ") + ". Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.");
      codecs[mediaType] = null;
      return;
    }
    codecs[mediaType] = codecs[mediaType][0];
  });
  return codecs;
};
var codecCount = function codecCount2(codecObj) {
  var count = 0;
  if (codecObj.audio) {
    count++;
  }
  if (codecObj.video) {
    count++;
  }
  return count;
};
var codecsForPlaylist = function codecsForPlaylist2(master, media) {
  var mediaAttributes = media.attributes || {};
  var codecInfo = unwrapCodecList(getCodecs(media) || []);
  if (isMaat(master, media) && !codecInfo.audio) {
    if (!isMuxed(master, media)) {
      var defaultCodecs = unwrapCodecList(codecsFromDefault(master, mediaAttributes.AUDIO) || []);
      if (defaultCodecs.audio) {
        codecInfo.audio = defaultCodecs.audio;
      }
    }
  }
  return codecInfo;
};
var logFn = logger2("PlaylistSelector");
var representationToString = function representationToString2(representation) {
  if (!representation || !representation.playlist) {
    return;
  }
  var playlist = representation.playlist;
  return JSON.stringify({
    id: playlist.id,
    bandwidth: representation.bandwidth,
    width: representation.width,
    height: representation.height,
    codecs: playlist.attributes && playlist.attributes.CODECS || ""
  });
};
var safeGetComputedStyle = function safeGetComputedStyle2(el, property) {
  if (!el) {
    return "";
  }
  var result = import_window6.default.getComputedStyle(el);
  if (!result) {
    return "";
  }
  return result[property];
};
var stableSort = function stableSort2(array, sortFn) {
  var newArray = array.slice();
  array.sort(function(left, right) {
    var cmp = sortFn(left, right);
    if (cmp === 0) {
      return newArray.indexOf(left) - newArray.indexOf(right);
    }
    return cmp;
  });
};
var comparePlaylistBandwidth = function comparePlaylistBandwidth2(left, right) {
  var leftBandwidth;
  var rightBandwidth;
  if (left.attributes.BANDWIDTH) {
    leftBandwidth = left.attributes.BANDWIDTH;
  }
  leftBandwidth = leftBandwidth || import_window6.default.Number.MAX_VALUE;
  if (right.attributes.BANDWIDTH) {
    rightBandwidth = right.attributes.BANDWIDTH;
  }
  rightBandwidth = rightBandwidth || import_window6.default.Number.MAX_VALUE;
  return leftBandwidth - rightBandwidth;
};
var comparePlaylistResolution = function comparePlaylistResolution2(left, right) {
  var leftWidth;
  var rightWidth;
  if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
    leftWidth = left.attributes.RESOLUTION.width;
  }
  leftWidth = leftWidth || import_window6.default.Number.MAX_VALUE;
  if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
    rightWidth = right.attributes.RESOLUTION.width;
  }
  rightWidth = rightWidth || import_window6.default.Number.MAX_VALUE;
  if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
    return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  }
  return leftWidth - rightWidth;
};
var simpleSelector = function simpleSelector2(master, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, masterPlaylistController) {
  if (!master) {
    return;
  }
  var options = {
    bandwidth: playerBandwidth,
    width: playerWidth,
    height: playerHeight,
    limitRenditionByPlayerDimensions
  };
  var playlists = master.playlists;
  if (Playlist.isAudioOnly(master)) {
    playlists = masterPlaylistController.getAudioTrackPlaylists_();
    options.audioOnly = true;
  }
  var sortedPlaylistReps = playlists.map(function(playlist) {
    var bandwidth2;
    var width2 = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
    var height2 = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
    bandwidth2 = playlist.attributes && playlist.attributes.BANDWIDTH;
    bandwidth2 = bandwidth2 || import_window6.default.Number.MAX_VALUE;
    return {
      bandwidth: bandwidth2,
      width: width2,
      height: height2,
      playlist
    };
  });
  stableSort(sortedPlaylistReps, function(left, right) {
    return left.bandwidth - right.bandwidth;
  });
  sortedPlaylistReps = sortedPlaylistReps.filter(function(rep) {
    return !Playlist.isIncompatible(rep.playlist);
  });
  var enabledPlaylistReps = sortedPlaylistReps.filter(function(rep) {
    return Playlist.isEnabled(rep.playlist);
  });
  if (!enabledPlaylistReps.length) {
    enabledPlaylistReps = sortedPlaylistReps.filter(function(rep) {
      return !Playlist.isDisabled(rep.playlist);
    });
  }
  var bandwidthPlaylistReps = enabledPlaylistReps.filter(function(rep) {
    return rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth;
  });
  var highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1];
  var bandwidthBestRep = bandwidthPlaylistReps.filter(function(rep) {
    return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
  })[0];
  if (limitRenditionByPlayerDimensions === false) {
    var _chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
    if (_chosenRep && _chosenRep.playlist) {
      var type2 = "sortedPlaylistReps";
      if (bandwidthBestRep) {
        type2 = "bandwidthBestRep";
      }
      if (enabledPlaylistReps[0]) {
        type2 = "enabledPlaylistReps";
      }
      logFn("choosing " + representationToString(_chosenRep) + " using " + type2 + " with options", options);
      return _chosenRep.playlist;
    }
    logFn("could not choose a playlist with options", options);
    return null;
  }
  var haveResolution = bandwidthPlaylistReps.filter(function(rep) {
    return rep.width && rep.height;
  });
  stableSort(haveResolution, function(left, right) {
    return left.width - right.width;
  });
  var resolutionBestRepList = haveResolution.filter(function(rep) {
    return rep.width === playerWidth && rep.height === playerHeight;
  });
  highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1];
  var resolutionBestRep = resolutionBestRepList.filter(function(rep) {
    return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
  })[0];
  var resolutionPlusOneList;
  var resolutionPlusOneSmallest;
  var resolutionPlusOneRep;
  if (!resolutionBestRep) {
    resolutionPlusOneList = haveResolution.filter(function(rep) {
      return rep.width > playerWidth || rep.height > playerHeight;
    });
    resolutionPlusOneSmallest = resolutionPlusOneList.filter(function(rep) {
      return rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height;
    });
    highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
    resolutionPlusOneRep = resolutionPlusOneSmallest.filter(function(rep) {
      return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
    })[0];
  }
  var leastPixelDiffRep;
  if (masterPlaylistController.experimentalLeastPixelDiffSelector) {
    var leastPixelDiffList = haveResolution.map(function(rep) {
      rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
      return rep;
    });
    stableSort(leastPixelDiffList, function(left, right) {
      if (left.pixelDiff === right.pixelDiff) {
        return right.bandwidth - left.bandwidth;
      }
      return left.pixelDiff - right.pixelDiff;
    });
    leastPixelDiffRep = leastPixelDiffList[0];
  }
  var chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  if (chosenRep && chosenRep.playlist) {
    var _type = "sortedPlaylistReps";
    if (leastPixelDiffRep) {
      _type = "leastPixelDiffRep";
    } else if (resolutionPlusOneRep) {
      _type = "resolutionPlusOneRep";
    } else if (resolutionBestRep) {
      _type = "resolutionBestRep";
    } else if (bandwidthBestRep) {
      _type = "bandwidthBestRep";
    } else if (enabledPlaylistReps[0]) {
      _type = "enabledPlaylistReps";
    }
    logFn("choosing " + representationToString(chosenRep) + " using " + _type + " with options", options);
    return chosenRep.playlist;
  }
  logFn("could not choose a playlist with options", options);
  return null;
};
var lastBandwidthSelector = function lastBandwidthSelector2() {
  var pixelRatio = this.useDevicePixelRatio ? import_window6.default.devicePixelRatio || 1 : 1;
  return simpleSelector(this.playlists.master, this.systemBandwidth, parseInt(safeGetComputedStyle(this.tech_.el(), "width"), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), "height"), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
};
var movingAverageBandwidthSelector = function movingAverageBandwidthSelector2(decay) {
  var average = -1;
  var lastSystemBandwidth = -1;
  if (decay < 0 || decay > 1) {
    throw new Error("Moving average bandwidth decay must be between 0 and 1.");
  }
  return function() {
    var pixelRatio = this.useDevicePixelRatio ? import_window6.default.devicePixelRatio || 1 : 1;
    if (average < 0) {
      average = this.systemBandwidth;
      lastSystemBandwidth = this.systemBandwidth;
    }
    if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
      average = decay * this.systemBandwidth + (1 - decay) * average;
      lastSystemBandwidth = this.systemBandwidth;
    }
    return simpleSelector(this.playlists.master, average, parseInt(safeGetComputedStyle(this.tech_.el(), "width"), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), "height"), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
  };
};
var minRebufferMaxBandwidthSelector = function minRebufferMaxBandwidthSelector2(settings) {
  var master = settings.master, currentTime = settings.currentTime, bandwidth2 = settings.bandwidth, duration5 = settings.duration, segmentDuration = settings.segmentDuration, timeUntilRebuffer3 = settings.timeUntilRebuffer, currentTimeline = settings.currentTimeline, syncController = settings.syncController;
  var compatiblePlaylists = master.playlists.filter(function(playlist) {
    return !Playlist.isIncompatible(playlist);
  });
  var enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  if (!enabledPlaylists.length) {
    enabledPlaylists = compatiblePlaylists.filter(function(playlist) {
      return !Playlist.isDisabled(playlist);
    });
  }
  var bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, "BANDWIDTH"));
  var rebufferingEstimates = bandwidthPlaylists.map(function(playlist) {
    var syncPoint = syncController.getSyncPoint(playlist, duration5, currentTimeline, currentTime);
    var numRequests = syncPoint ? 1 : 2;
    var requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth2, playlist);
    var rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer3;
    return {
      playlist,
      rebufferingImpact
    };
  });
  var noRebufferingPlaylists = rebufferingEstimates.filter(function(estimate) {
    return estimate.rebufferingImpact <= 0;
  });
  stableSort(noRebufferingPlaylists, function(a, b) {
    return comparePlaylistBandwidth(b.playlist, a.playlist);
  });
  if (noRebufferingPlaylists.length) {
    return noRebufferingPlaylists[0];
  }
  stableSort(rebufferingEstimates, function(a, b) {
    return a.rebufferingImpact - b.rebufferingImpact;
  });
  return rebufferingEstimates[0] || null;
};
var lowestBitrateCompatibleVariantSelector = function lowestBitrateCompatibleVariantSelector2() {
  var _this = this;
  var playlists = this.playlists.master.playlists.filter(Playlist.isEnabled);
  stableSort(playlists, function(a, b) {
    return comparePlaylistBandwidth(a, b);
  });
  var playlistsWithVideo = playlists.filter(function(playlist) {
    return !!codecsForPlaylist(_this.playlists.master, playlist).video;
  });
  return playlistsWithVideo[0] || null;
};
var concatSegments = function concatSegments2(segmentObj) {
  var offset = 0;
  var tempBuffer;
  if (segmentObj.bytes) {
    tempBuffer = new Uint8Array(segmentObj.bytes);
    segmentObj.segments.forEach(function(segment) {
      tempBuffer.set(segment, offset);
      offset += segment.byteLength;
    });
  }
  return tempBuffer;
};
var createCaptionsTrackIfNotExists = function createCaptionsTrackIfNotExists2(inbandTextTracks, tech, captionStream) {
  if (!inbandTextTracks[captionStream]) {
    tech.trigger({
      type: "usage",
      name: "vhs-608"
    });
    tech.trigger({
      type: "usage",
      name: "hls-608"
    });
    var instreamId = captionStream;
    if (/^cc708_/.test(captionStream)) {
      instreamId = "SERVICE" + captionStream.split("_")[1];
    }
    var track = tech.textTracks().getTrackById(instreamId);
    if (track) {
      inbandTextTracks[captionStream] = track;
    } else {
      var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
      var label = captionStream;
      var language = captionStream;
      var def = false;
      var captionService = captionServices[instreamId];
      if (captionService) {
        label = captionService.label;
        language = captionService.language;
        def = captionService["default"];
      }
      inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
        kind: "captions",
        id: instreamId,
        // TODO: investigate why this doesn't seem to turn the caption on by default
        "default": def,
        label,
        language
      }, false).track;
    }
  }
};
var addCaptionData = function addCaptionData2(_ref) {
  var inbandTextTracks = _ref.inbandTextTracks, captionArray = _ref.captionArray, timestampOffset2 = _ref.timestampOffset;
  if (!captionArray) {
    return;
  }
  var Cue = import_window6.default.WebKitDataCue || import_window6.default.VTTCue;
  captionArray.forEach(function(caption) {
    var track = caption.stream;
    inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset2, caption.endTime + timestampOffset2, caption.text));
  });
};
var deprecateOldCue = function deprecateOldCue2(cue) {
  Object.defineProperties(cue.frame, {
    id: {
      get: function get7() {
        videojs.log.warn("cue.frame.id is deprecated. Use cue.value.key instead.");
        return cue.value.key;
      }
    },
    value: {
      get: function get7() {
        videojs.log.warn("cue.frame.value is deprecated. Use cue.value.data instead.");
        return cue.value.data;
      }
    },
    privateData: {
      get: function get7() {
        videojs.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead.");
        return cue.value.data;
      }
    }
  });
};
var addMetadata = function addMetadata2(_ref2) {
  var inbandTextTracks = _ref2.inbandTextTracks, metadataArray = _ref2.metadataArray, timestampOffset2 = _ref2.timestampOffset, videoDuration = _ref2.videoDuration;
  if (!metadataArray) {
    return;
  }
  var Cue = import_window6.default.WebKitDataCue || import_window6.default.VTTCue;
  var metadataTrack = inbandTextTracks.metadataTrack_;
  if (!metadataTrack) {
    return;
  }
  metadataArray.forEach(function(metadata) {
    var time = metadata.cueTime + timestampOffset2;
    if (typeof time !== "number" || import_window6.default.isNaN(time) || time < 0 || !(time < Infinity)) {
      return;
    }
    metadata.frames.forEach(function(frame) {
      var cue = new Cue(time, time, frame.value || frame.url || frame.data || "");
      cue.frame = frame;
      cue.value = frame;
      deprecateOldCue(cue);
      metadataTrack.addCue(cue);
    });
  });
  if (!metadataTrack.cues || !metadataTrack.cues.length) {
    return;
  }
  var cues = metadataTrack.cues;
  var cuesArray = [];
  for (var i = 0; i < cues.length; i++) {
    if (cues[i]) {
      cuesArray.push(cues[i]);
    }
  }
  var cuesGroupedByStartTime = cuesArray.reduce(function(obj, cue) {
    var timeSlot = obj[cue.startTime] || [];
    timeSlot.push(cue);
    obj[cue.startTime] = timeSlot;
    return obj;
  }, {});
  var sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort(function(a, b) {
    return Number(a) - Number(b);
  });
  sortedStartTimes.forEach(function(startTime, idx) {
    var cueGroup = cuesGroupedByStartTime[startTime];
    var nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration;
    cueGroup.forEach(function(cue) {
      cue.endTime = nextTime;
    });
  });
};
var createMetadataTrackIfNotExists = function createMetadataTrackIfNotExists2(inbandTextTracks, dispatchType, tech) {
  if (inbandTextTracks.metadataTrack_) {
    return;
  }
  inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
    kind: "metadata",
    label: "Timed Metadata"
  }, false).track;
  inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
};
var removeCuesFromTrack = function removeCuesFromTrack2(start2, end, track) {
  var i;
  var cue;
  if (!track) {
    return;
  }
  if (!track.cues) {
    return;
  }
  i = track.cues.length;
  while (i--) {
    cue = track.cues[i];
    if (cue.startTime >= start2 && cue.endTime <= end) {
      track.removeCue(cue);
    }
  }
};
var removeDuplicateCuesFromTrack = function removeDuplicateCuesFromTrack2(track) {
  var cues = track.cues;
  if (!cues) {
    return;
  }
  for (var i = 0; i < cues.length; i++) {
    var duplicates = [];
    var occurrences = 0;
    for (var j = 0; j < cues.length; j++) {
      if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
        occurrences++;
        if (occurrences > 1) {
          duplicates.push(cues[j]);
        }
      }
    }
    if (duplicates.length) {
      duplicates.forEach(function(dupe) {
        return track.removeCue(dupe);
      });
    }
  }
};
var gopsSafeToAlignWith = function gopsSafeToAlignWith2(buffer, currentTime, mapping) {
  if (typeof currentTime === "undefined" || currentTime === null || !buffer.length) {
    return [];
  }
  var currentTimePts = Math.ceil((currentTime - mapping + 3) * import_clock.ONE_SECOND_IN_TS);
  var i;
  for (i = 0; i < buffer.length; i++) {
    if (buffer[i].pts > currentTimePts) {
      break;
    }
  }
  return buffer.slice(i);
};
var updateGopBuffer = function updateGopBuffer2(buffer, gops, replace) {
  if (!gops.length) {
    return buffer;
  }
  if (replace) {
    return gops.slice();
  }
  var start2 = gops[0].pts;
  var i = 0;
  for (i; i < buffer.length; i++) {
    if (buffer[i].pts >= start2) {
      break;
    }
  }
  return buffer.slice(0, i).concat(gops);
};
var removeGopBuffer = function removeGopBuffer2(buffer, start2, end, mapping) {
  var startPts = Math.ceil((start2 - mapping) * import_clock.ONE_SECOND_IN_TS);
  var endPts = Math.ceil((end - mapping) * import_clock.ONE_SECOND_IN_TS);
  var updatedBuffer = buffer.slice();
  var i = buffer.length;
  while (i--) {
    if (buffer[i].pts <= endPts) {
      break;
    }
  }
  if (i === -1) {
    return updatedBuffer;
  }
  var j = i + 1;
  while (j--) {
    if (buffer[j].pts <= startPts) {
      break;
    }
  }
  j = Math.max(j, 0);
  updatedBuffer.splice(j, i - j + 1);
  return updatedBuffer;
};
var shallowEqual = function shallowEqual2(a, b) {
  if (!a && !b || !a && b || a && !b) {
    return false;
  }
  if (a === b) {
    return true;
  }
  var akeys = Object.keys(a).sort();
  var bkeys = Object.keys(b).sort();
  if (akeys.length !== bkeys.length) {
    return false;
  }
  for (var i = 0; i < akeys.length; i++) {
    var key = akeys[i];
    if (key !== bkeys[i]) {
      return false;
    }
    if (a[key] !== b[key]) {
      return false;
    }
  }
  return true;
};
var QUOTA_EXCEEDED_ERR = 22;
var getSyncSegmentCandidate = function getSyncSegmentCandidate2(currentTimeline, segments, targetTime) {
  segments = segments || [];
  var timelineSegments = [];
  var time = 0;
  for (var i = 0; i < segments.length; i++) {
    var segment = segments[i];
    if (currentTimeline === segment.timeline) {
      timelineSegments.push(i);
      time += segment.duration;
      if (time > targetTime) {
        return i;
      }
    }
  }
  if (timelineSegments.length === 0) {
    return 0;
  }
  return timelineSegments[timelineSegments.length - 1];
};
var MIN_BACK_BUFFER = 1;
var CHECK_BUFFER_DELAY = 500;
var finite = function finite2(num) {
  return typeof num === "number" && isFinite(num);
};
var MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
var illegalMediaSwitch = function illegalMediaSwitch2(loaderType, startingMedia, trackInfo) {
  if (loaderType !== "main" || !startingMedia || !trackInfo) {
    return null;
  }
  if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
    return "Neither audio nor video found in segment.";
  }
  if (startingMedia.hasVideo && !trackInfo.hasVideo) {
    return "Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.";
  }
  if (!startingMedia.hasVideo && trackInfo.hasVideo) {
    return "Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.";
  }
  return null;
};
var safeBackBufferTrimTime = function safeBackBufferTrimTime2(seekable3, currentTime, targetDuration) {
  var trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  if (seekable3.length) {
    trimTime = Math.max(trimTime, seekable3.start(0));
  }
  var maxTrimTime = currentTime - targetDuration;
  return Math.min(maxTrimTime, trimTime);
};
var segmentInfoString = function segmentInfoString2(segmentInfo) {
  var startOfSegment = segmentInfo.startOfSegment, duration5 = segmentInfo.duration, segment = segmentInfo.segment, part = segmentInfo.part, _segmentInfo$playlist = segmentInfo.playlist, seq = _segmentInfo$playlist.mediaSequence, id = _segmentInfo$playlist.id, _segmentInfo$playlist2 = _segmentInfo$playlist.segments, segments = _segmentInfo$playlist2 === void 0 ? [] : _segmentInfo$playlist2, index = segmentInfo.mediaIndex, partIndex = segmentInfo.partIndex, timeline = segmentInfo.timeline;
  var segmentLen = segments.length - 1;
  var selection = "mediaIndex/partIndex increment";
  if (segmentInfo.getMediaInfoForTime) {
    selection = "getMediaInfoForTime (" + segmentInfo.getMediaInfoForTime + ")";
  } else if (segmentInfo.isSyncRequest) {
    selection = "getSyncSegmentCandidate (isSyncRequest)";
  }
  if (segmentInfo.independent) {
    selection += " with independent " + segmentInfo.independent;
  }
  var hasPartIndex = typeof partIndex === "number";
  var name = segmentInfo.segment.uri ? "segment" : "pre-segment";
  var zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
    preloadSegment: segment
  }) - 1 : 0;
  return name + " [" + (seq + index) + "/" + (seq + segmentLen) + "]" + (hasPartIndex ? " part [" + partIndex + "/" + zeroBasedPartCount + "]" : "") + (" segment start/end [" + segment.start + " => " + segment.end + "]") + (hasPartIndex ? " part start/end [" + part.start + " => " + part.end + "]" : "") + (" startOfSegment [" + startOfSegment + "]") + (" duration [" + duration5 + "]") + (" timeline [" + timeline + "]") + (" selected by [" + selection + "]") + (" playlist [" + id + "]");
};
var timingInfoPropertyForMedia = function timingInfoPropertyForMedia2(mediaType) {
  return mediaType + "TimingInfo";
};
var timestampOffsetForSegment = function timestampOffsetForSegment2(_ref) {
  var segmentTimeline = _ref.segmentTimeline, currentTimeline = _ref.currentTimeline, startOfSegment = _ref.startOfSegment, buffered = _ref.buffered, overrideCheck = _ref.overrideCheck;
  if (!overrideCheck && segmentTimeline === currentTimeline) {
    return null;
  }
  if (segmentTimeline < currentTimeline) {
    return startOfSegment;
  }
  return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
};
var shouldWaitForTimelineChange = function shouldWaitForTimelineChange2(_ref2) {
  var timelineChangeController = _ref2.timelineChangeController, currentTimeline = _ref2.currentTimeline, segmentTimeline = _ref2.segmentTimeline, loaderType = _ref2.loaderType, audioDisabled = _ref2.audioDisabled;
  if (currentTimeline === segmentTimeline) {
    return false;
  }
  if (loaderType === "audio") {
    var lastMainTimelineChange = timelineChangeController.lastTimelineChange({
      type: "main"
    });
    return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  }
  if (loaderType === "main" && audioDisabled) {
    var pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
      type: "audio"
    });
    if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
      return false;
    }
    return true;
  }
  return false;
};
var mediaDuration = function mediaDuration2(timingInfos) {
  var maxDuration = 0;
  ["video", "audio"].forEach(function(type2) {
    var typeTimingInfo = timingInfos[type2 + "TimingInfo"];
    if (!typeTimingInfo) {
      return;
    }
    var start2 = typeTimingInfo.start, end = typeTimingInfo.end;
    var duration5;
    if (typeof start2 === "bigint" || typeof end === "bigint") {
      duration5 = import_window6.default.BigInt(end) - import_window6.default.BigInt(start2);
    } else if (typeof start2 === "number" && typeof end === "number") {
      duration5 = end - start2;
    }
    if (typeof duration5 !== "undefined" && duration5 > maxDuration) {
      maxDuration = duration5;
    }
  });
  if (typeof maxDuration === "bigint" && maxDuration < Number.MAX_SAFE_INTEGER) {
    maxDuration = Number(maxDuration);
  }
  return maxDuration;
};
var segmentTooLong = function segmentTooLong2(_ref3) {
  var segmentDuration = _ref3.segmentDuration, maxDuration = _ref3.maxDuration;
  if (!segmentDuration) {
    return false;
  }
  return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
};
var getTroublesomeSegmentDurationMessage = function getTroublesomeSegmentDurationMessage2(segmentInfo, sourceType) {
  if (sourceType !== "hls") {
    return null;
  }
  var segmentDuration = mediaDuration({
    audioTimingInfo: segmentInfo.audioTimingInfo,
    videoTimingInfo: segmentInfo.videoTimingInfo
  });
  if (!segmentDuration) {
    return null;
  }
  var targetDuration = segmentInfo.playlist.targetDuration;
  var isSegmentWayTooLong = segmentTooLong({
    segmentDuration,
    maxDuration: targetDuration * 2
  });
  var isSegmentSlightlyTooLong = segmentTooLong({
    segmentDuration,
    maxDuration: targetDuration
  });
  var segmentTooLongMessage = "Segment with index " + segmentInfo.mediaIndex + " " + ("from playlist " + segmentInfo.playlist.id + " ") + ("has a duration of " + segmentDuration + " ") + ("when the reported duration is " + segmentInfo.duration + " ") + ("and the target duration is " + targetDuration + ". ") + "For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1";
  if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
    return {
      severity: isSegmentWayTooLong ? "warn" : "info",
      message: segmentTooLongMessage
    };
  }
  return null;
};
var SegmentLoader = /* @__PURE__ */ function(_videojs$EventTarget) {
  _inheritsLoose(SegmentLoader2, _videojs$EventTarget);
  function SegmentLoader2(settings, options) {
    var _this;
    _this = _videojs$EventTarget.call(this) || this;
    if (!settings) {
      throw new TypeError("Initialization settings are required");
    }
    if (typeof settings.currentTime !== "function") {
      throw new TypeError("No currentTime getter specified");
    }
    if (!settings.mediaSource) {
      throw new TypeError("No MediaSource specified");
    }
    _this.bandwidth = settings.bandwidth;
    _this.throughput = {
      rate: 0,
      count: 0
    };
    _this.roundTrip = NaN;
    _this.resetStats_();
    _this.mediaIndex = null;
    _this.partIndex = null;
    _this.hasPlayed_ = settings.hasPlayed;
    _this.currentTime_ = settings.currentTime;
    _this.seekable_ = settings.seekable;
    _this.seeking_ = settings.seeking;
    _this.duration_ = settings.duration;
    _this.mediaSource_ = settings.mediaSource;
    _this.vhs_ = settings.vhs;
    _this.loaderType_ = settings.loaderType;
    _this.currentMediaInfo_ = void 0;
    _this.startingMediaInfo_ = void 0;
    _this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
    _this.goalBufferLength_ = settings.goalBufferLength;
    _this.sourceType_ = settings.sourceType;
    _this.sourceUpdater_ = settings.sourceUpdater;
    _this.inbandTextTracks_ = settings.inbandTextTracks;
    _this.state_ = "INIT";
    _this.timelineChangeController_ = settings.timelineChangeController;
    _this.shouldSaveSegmentTimingInfo_ = true;
    _this.parse708captions_ = settings.parse708captions;
    _this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
    _this.captionServices_ = settings.captionServices;
    _this.experimentalExactManifestTimings = settings.experimentalExactManifestTimings;
    _this.checkBufferTimeout_ = null;
    _this.error_ = void 0;
    _this.currentTimeline_ = -1;
    _this.pendingSegment_ = null;
    _this.xhrOptions_ = null;
    _this.pendingSegments_ = [];
    _this.audioDisabled_ = false;
    _this.isPendingTimestampOffset_ = false;
    _this.gopBuffer_ = [];
    _this.timeMapping_ = 0;
    _this.safeAppend_ = videojs.browser.IE_VERSION >= 11;
    _this.appendInitSegment_ = {
      audio: true,
      video: true
    };
    _this.playlistOfLastInitSegment_ = {
      audio: null,
      video: null
    };
    _this.callQueue_ = [];
    _this.loadQueue_ = [];
    _this.metadataQueue_ = {
      id3: [],
      caption: []
    };
    _this.waitingOnRemove_ = false;
    _this.quotaExceededErrorRetryTimeout_ = null;
    _this.activeInitSegmentId_ = null;
    _this.initSegments_ = {};
    _this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
    _this.keyCache_ = {};
    _this.decrypter_ = settings.decrypter;
    _this.syncController_ = settings.syncController;
    _this.syncPoint_ = {
      segmentIndex: 0,
      time: 0
    };
    _this.transmuxer_ = _this.createTransmuxer_();
    _this.triggerSyncInfoUpdate_ = function() {
      return _this.trigger("syncinfoupdate");
    };
    _this.syncController_.on("syncinfoupdate", _this.triggerSyncInfoUpdate_);
    _this.mediaSource_.addEventListener("sourceopen", function() {
      if (!_this.isEndOfStream_()) {
        _this.ended_ = false;
      }
    });
    _this.fetchAtBuffer_ = false;
    _this.logger_ = logger2("SegmentLoader[" + _this.loaderType_ + "]");
    Object.defineProperty(_assertThisInitialized(_this), "state", {
      get: function get7() {
        return this.state_;
      },
      set: function set4(newState) {
        if (newState !== this.state_) {
          this.logger_(this.state_ + " -> " + newState);
          this.state_ = newState;
          this.trigger("statechange");
        }
      }
    });
    _this.sourceUpdater_.on("ready", function() {
      if (_this.hasEnoughInfoToAppend_()) {
        _this.processCallQueue_();
      }
    });
    if (_this.loaderType_ === "main") {
      _this.timelineChangeController_.on("pendingtimelinechange", function() {
        if (_this.hasEnoughInfoToAppend_()) {
          _this.processCallQueue_();
        }
      });
    }
    if (_this.loaderType_ === "audio") {
      _this.timelineChangeController_.on("timelinechange", function() {
        if (_this.hasEnoughInfoToLoad_()) {
          _this.processLoadQueue_();
        }
        if (_this.hasEnoughInfoToAppend_()) {
          _this.processCallQueue_();
        }
      });
    }
    return _this;
  }
  var _proto = SegmentLoader2.prototype;
  _proto.createTransmuxer_ = function createTransmuxer_() {
    return segmentTransmuxer.createTransmuxer({
      remux: false,
      alignGopsAtEnd: this.safeAppend_,
      keepOriginalTimestamps: true,
      parse708captions: this.parse708captions_,
      captionServices: this.captionServices_
    });
  };
  _proto.resetStats_ = function resetStats_() {
    this.mediaBytesTransferred = 0;
    this.mediaRequests = 0;
    this.mediaRequestsAborted = 0;
    this.mediaRequestsTimedout = 0;
    this.mediaRequestsErrored = 0;
    this.mediaTransferDuration = 0;
    this.mediaSecondsLoaded = 0;
    this.mediaAppends = 0;
  };
  _proto.dispose = function dispose() {
    this.trigger("dispose");
    this.state = "DISPOSED";
    this.pause();
    this.abort_();
    if (this.transmuxer_) {
      this.transmuxer_.terminate();
    }
    this.resetStats_();
    if (this.checkBufferTimeout_) {
      import_window6.default.clearTimeout(this.checkBufferTimeout_);
    }
    if (this.syncController_ && this.triggerSyncInfoUpdate_) {
      this.syncController_.off("syncinfoupdate", this.triggerSyncInfoUpdate_);
    }
    this.off();
  };
  _proto.setAudio = function setAudio(enable) {
    this.audioDisabled_ = !enable;
    if (enable) {
      this.appendInitSegment_.audio = true;
    } else {
      this.sourceUpdater_.removeAudio(0, this.duration_());
    }
  };
  _proto.abort = function abort2() {
    if (this.state !== "WAITING") {
      if (this.pendingSegment_) {
        this.pendingSegment_ = null;
      }
      return;
    }
    this.abort_();
    this.state = "READY";
    if (!this.paused()) {
      this.monitorBuffer_();
    }
  };
  _proto.abort_ = function abort_() {
    if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
      this.pendingSegment_.abortRequests();
    }
    this.pendingSegment_ = null;
    this.callQueue_ = [];
    this.loadQueue_ = [];
    this.metadataQueue_.id3 = [];
    this.metadataQueue_.caption = [];
    this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
    this.waitingOnRemove_ = false;
    import_window6.default.clearTimeout(this.quotaExceededErrorRetryTimeout_);
    this.quotaExceededErrorRetryTimeout_ = null;
  };
  _proto.checkForAbort_ = function checkForAbort_(requestId) {
    if (this.state === "APPENDING" && !this.pendingSegment_) {
      this.state = "READY";
      return true;
    }
    if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
      return true;
    }
    return false;
  };
  _proto.error = function error(_error) {
    if (typeof _error !== "undefined") {
      this.logger_("error occurred:", _error);
      this.error_ = _error;
    }
    this.pendingSegment_ = null;
    return this.error_;
  };
  _proto.endOfStream = function endOfStream2() {
    this.ended_ = true;
    if (this.transmuxer_) {
      segmentTransmuxer.reset(this.transmuxer_);
    }
    this.gopBuffer_.length = 0;
    this.pause();
    this.trigger("ended");
  };
  _proto.buffered_ = function buffered_() {
    var trackInfo = this.getMediaInfo_();
    if (!this.sourceUpdater_ || !trackInfo) {
      return videojs.createTimeRanges();
    }
    if (this.loaderType_ === "main") {
      var hasAudio = trackInfo.hasAudio, hasVideo = trackInfo.hasVideo, isMuxed3 = trackInfo.isMuxed;
      if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed3) {
        return this.sourceUpdater_.buffered();
      }
      if (hasVideo) {
        return this.sourceUpdater_.videoBuffered();
      }
    }
    return this.sourceUpdater_.audioBuffered();
  };
  _proto.initSegmentForMap = function initSegmentForMap(map, set4) {
    if (set4 === void 0) {
      set4 = false;
    }
    if (!map) {
      return null;
    }
    var id = initSegmentId(map);
    var storedMap = this.initSegments_[id];
    if (set4 && !storedMap && map.bytes) {
      this.initSegments_[id] = storedMap = {
        resolvedUri: map.resolvedUri,
        byterange: map.byterange,
        bytes: map.bytes,
        tracks: map.tracks,
        timescales: map.timescales
      };
    }
    return storedMap || map;
  };
  _proto.segmentKey = function segmentKey(key, set4) {
    if (set4 === void 0) {
      set4 = false;
    }
    if (!key) {
      return null;
    }
    var id = segmentKeyId(key);
    var storedKey = this.keyCache_[id];
    if (this.cacheEncryptionKeys_ && set4 && !storedKey && key.bytes) {
      this.keyCache_[id] = storedKey = {
        resolvedUri: key.resolvedUri,
        bytes: key.bytes
      };
    }
    var result = {
      resolvedUri: (storedKey || key).resolvedUri
    };
    if (storedKey) {
      result.bytes = storedKey.bytes;
    }
    return result;
  };
  _proto.couldBeginLoading_ = function couldBeginLoading_() {
    return this.playlist_ && !this.paused();
  };
  _proto.load = function load() {
    this.monitorBuffer_();
    if (!this.playlist_) {
      return;
    }
    if (this.state === "INIT" && this.couldBeginLoading_()) {
      return this.init_();
    }
    if (!this.couldBeginLoading_() || this.state !== "READY" && this.state !== "INIT") {
      return;
    }
    this.state = "READY";
  };
  _proto.init_ = function init_() {
    this.state = "READY";
    this.resetEverything();
    return this.monitorBuffer_();
  };
  _proto.playlist = function playlist(newPlaylist, options) {
    if (options === void 0) {
      options = {};
    }
    if (!newPlaylist) {
      return;
    }
    var oldPlaylist = this.playlist_;
    var segmentInfo = this.pendingSegment_;
    this.playlist_ = newPlaylist;
    this.xhrOptions_ = options;
    if (this.state === "INIT") {
      newPlaylist.syncInfo = {
        mediaSequence: newPlaylist.mediaSequence,
        time: 0
      };
      if (this.loaderType_ === "main") {
        this.syncController_.setDateTimeMappingForStart(newPlaylist);
      }
    }
    var oldId = null;
    if (oldPlaylist) {
      if (oldPlaylist.id) {
        oldId = oldPlaylist.id;
      } else if (oldPlaylist.uri) {
        oldId = oldPlaylist.uri;
      }
    }
    this.logger_("playlist update [" + oldId + " => " + (newPlaylist.id || newPlaylist.uri) + "]");
    this.trigger("syncinfoupdate");
    if (this.state === "INIT" && this.couldBeginLoading_()) {
      return this.init_();
    }
    if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
      if (this.mediaIndex !== null) {
        if (!newPlaylist.endList) {
          this.resetLoader();
        } else {
          this.resyncLoader();
        }
      }
      this.currentMediaInfo_ = void 0;
      this.trigger("playlistupdate");
      return;
    }
    var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
    this.logger_("live window shift [" + mediaSequenceDiff + "]");
    if (this.mediaIndex !== null) {
      this.mediaIndex -= mediaSequenceDiff;
      if (this.mediaIndex < 0) {
        this.mediaIndex = null;
        this.partIndex = null;
      } else {
        var segment = this.playlist_.segments[this.mediaIndex];
        if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
          var mediaIndex = this.mediaIndex;
          this.logger_("currently processing part (index " + this.partIndex + ") no longer exists.");
          this.resetLoader();
          this.mediaIndex = mediaIndex;
        }
      }
    }
    if (segmentInfo) {
      segmentInfo.mediaIndex -= mediaSequenceDiff;
      if (segmentInfo.mediaIndex < 0) {
        segmentInfo.mediaIndex = null;
        segmentInfo.partIndex = null;
      } else {
        if (segmentInfo.mediaIndex >= 0) {
          segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
        }
        if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
          segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
        }
      }
    }
    this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  };
  _proto.pause = function pause() {
    if (this.checkBufferTimeout_) {
      import_window6.default.clearTimeout(this.checkBufferTimeout_);
      this.checkBufferTimeout_ = null;
    }
  };
  _proto.paused = function paused() {
    return this.checkBufferTimeout_ === null;
  };
  _proto.resetEverything = function resetEverything(done) {
    this.ended_ = false;
    this.appendInitSegment_ = {
      audio: true,
      video: true
    };
    this.resetLoader();
    this.remove(0, Infinity, done);
    if (this.transmuxer_) {
      this.transmuxer_.postMessage({
        action: "clearAllMp4Captions"
      });
      this.transmuxer_.postMessage({
        action: "reset"
      });
    }
  };
  _proto.resetLoader = function resetLoader() {
    this.fetchAtBuffer_ = false;
    this.resyncLoader();
  };
  _proto.resyncLoader = function resyncLoader() {
    if (this.transmuxer_) {
      segmentTransmuxer.reset(this.transmuxer_);
    }
    this.mediaIndex = null;
    this.partIndex = null;
    this.syncPoint_ = null;
    this.isPendingTimestampOffset_ = false;
    this.callQueue_ = [];
    this.loadQueue_ = [];
    this.metadataQueue_.id3 = [];
    this.metadataQueue_.caption = [];
    this.abort();
    if (this.transmuxer_) {
      this.transmuxer_.postMessage({
        action: "clearParsedMp4Captions"
      });
    }
  };
  _proto.remove = function remove2(start2, end, done, force) {
    if (done === void 0) {
      done = function done2() {
      };
    }
    if (force === void 0) {
      force = false;
    }
    if (end === Infinity) {
      end = this.duration_();
    }
    if (end <= start2) {
      this.logger_("skipping remove because end ${end} is <= start ${start}");
      return;
    }
    if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
      this.logger_("skipping remove because no source updater or starting media info");
      return;
    }
    var removesRemaining = 1;
    var removeFinished = function removeFinished2() {
      removesRemaining--;
      if (removesRemaining === 0) {
        done();
      }
    };
    if (force || !this.audioDisabled_) {
      removesRemaining++;
      this.sourceUpdater_.removeAudio(start2, end, removeFinished);
    }
    if (force || this.loaderType_ === "main") {
      this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start2, end, this.timeMapping_);
      removesRemaining++;
      this.sourceUpdater_.removeVideo(start2, end, removeFinished);
    }
    for (var track in this.inbandTextTracks_) {
      removeCuesFromTrack(start2, end, this.inbandTextTracks_[track]);
    }
    removeCuesFromTrack(start2, end, this.segmentMetadataTrack_);
    removeFinished();
  };
  _proto.monitorBuffer_ = function monitorBuffer_() {
    if (this.checkBufferTimeout_) {
      import_window6.default.clearTimeout(this.checkBufferTimeout_);
    }
    this.checkBufferTimeout_ = import_window6.default.setTimeout(this.monitorBufferTick_.bind(this), 1);
  };
  _proto.monitorBufferTick_ = function monitorBufferTick_() {
    if (this.state === "READY") {
      this.fillBuffer_();
    }
    if (this.checkBufferTimeout_) {
      import_window6.default.clearTimeout(this.checkBufferTimeout_);
    }
    this.checkBufferTimeout_ = import_window6.default.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  };
  _proto.fillBuffer_ = function fillBuffer_() {
    if (this.sourceUpdater_.updating()) {
      return;
    }
    var segmentInfo = this.chooseNextRequest_();
    if (!segmentInfo) {
      return;
    }
    if (typeof segmentInfo.timestampOffset === "number") {
      this.isPendingTimestampOffset_ = false;
      this.timelineChangeController_.pendingTimelineChange({
        type: this.loaderType_,
        from: this.currentTimeline_,
        to: segmentInfo.timeline
      });
    }
    this.loadSegment_(segmentInfo);
  };
  _proto.isEndOfStream_ = function isEndOfStream_(mediaIndex, playlist, partIndex) {
    if (mediaIndex === void 0) {
      mediaIndex = this.mediaIndex;
    }
    if (playlist === void 0) {
      playlist = this.playlist_;
    }
    if (partIndex === void 0) {
      partIndex = this.partIndex;
    }
    if (!playlist || !this.mediaSource_) {
      return false;
    }
    var segment = typeof mediaIndex === "number" && playlist.segments[mediaIndex];
    var appendedLastSegment = mediaIndex + 1 === playlist.segments.length;
    var appendedLastPart = !segment || !segment.parts || partIndex + 1 === segment.parts.length;
    return playlist.endList && this.mediaSource_.readyState === "open" && appendedLastSegment && appendedLastPart;
  };
  _proto.chooseNextRequest_ = function chooseNextRequest_() {
    var buffered = this.buffered_();
    var bufferedEnd = lastBufferedEnd(buffered) || 0;
    var bufferedTime = timeAheadOf(buffered, this.currentTime_());
    var preloaded = !this.hasPlayed_() && bufferedTime >= 1;
    var haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
    var segments = this.playlist_.segments;
    if (!segments.length || preloaded || haveEnoughBuffer) {
      return null;
    }
    this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
    var next = {
      partIndex: null,
      mediaIndex: null,
      startOfSegment: null,
      playlist: this.playlist_,
      isSyncRequest: Boolean(!this.syncPoint_)
    };
    if (next.isSyncRequest) {
      next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
    } else if (this.mediaIndex !== null) {
      var segment = segments[this.mediaIndex];
      var partIndex = typeof this.partIndex === "number" ? this.partIndex : -1;
      next.startOfSegment = segment.end ? segment.end : bufferedEnd;
      if (segment.parts && segment.parts[partIndex + 1]) {
        next.mediaIndex = this.mediaIndex;
        next.partIndex = partIndex + 1;
      } else {
        next.mediaIndex = this.mediaIndex + 1;
      }
    } else {
      var _Playlist$getMediaInf = Playlist.getMediaInfoForTime({
        experimentalExactManifestTimings: this.experimentalExactManifestTimings,
        playlist: this.playlist_,
        currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
        startingPartIndex: this.syncPoint_.partIndex,
        startingSegmentIndex: this.syncPoint_.segmentIndex,
        startTime: this.syncPoint_.time
      }), segmentIndex = _Playlist$getMediaInf.segmentIndex, startTime = _Playlist$getMediaInf.startTime, _partIndex = _Playlist$getMediaInf.partIndex;
      next.getMediaInfoForTime = this.fetchAtBuffer_ ? "bufferedEnd " + bufferedEnd : "currentTime " + this.currentTime_();
      next.mediaIndex = segmentIndex;
      next.startOfSegment = startTime;
      next.partIndex = _partIndex;
    }
    var nextSegment = segments[next.mediaIndex];
    var nextPart = nextSegment && typeof next.partIndex === "number" && nextSegment.parts && nextSegment.parts[next.partIndex];
    if (!nextSegment || typeof next.partIndex === "number" && !nextPart) {
      return null;
    }
    if (typeof next.partIndex !== "number" && nextSegment.parts) {
      next.partIndex = 0;
      nextPart = nextSegment.parts[0];
    }
    if (!bufferedTime && nextPart && !nextPart.independent) {
      if (next.partIndex === 0) {
        var lastSegment = segments[next.mediaIndex - 1];
        var lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
        if (lastSegmentLastPart && lastSegmentLastPart.independent) {
          next.mediaIndex -= 1;
          next.partIndex = lastSegment.parts.length - 1;
          next.independent = "previous segment";
        }
      } else if (nextSegment.parts[next.partIndex - 1].independent) {
        next.partIndex -= 1;
        next.independent = "previous part";
      }
    }
    var ended = this.mediaSource_ && this.mediaSource_.readyState === "ended";
    if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
      return null;
    }
    return this.generateSegmentInfo_(next);
  };
  _proto.generateSegmentInfo_ = function generateSegmentInfo_(options) {
    var independent = options.independent, playlist = options.playlist, mediaIndex = options.mediaIndex, startOfSegment = options.startOfSegment, isSyncRequest = options.isSyncRequest, partIndex = options.partIndex, forceTimestampOffset = options.forceTimestampOffset, getMediaInfoForTime3 = options.getMediaInfoForTime;
    var segment = playlist.segments[mediaIndex];
    var part = typeof partIndex === "number" && segment.parts[partIndex];
    var segmentInfo = {
      requestId: "segment-loader-" + Math.random(),
      // resolve the segment URL relative to the playlist
      uri: part && part.resolvedUri || segment.resolvedUri,
      // the segment's mediaIndex at the time it was requested
      mediaIndex,
      partIndex: part ? partIndex : null,
      // whether or not to update the SegmentLoader's state with this
      // segment's mediaIndex
      isSyncRequest,
      startOfSegment,
      // the segment's playlist
      playlist,
      // unencrypted bytes of the segment
      bytes: null,
      // when a key is defined for this segment, the encrypted bytes
      encryptedBytes: null,
      // The target timestampOffset for this segment when we append it
      // to the source buffer
      timestampOffset: null,
      // The timeline that the segment is in
      timeline: segment.timeline,
      // The expected duration of the segment in seconds
      duration: part && part.duration || segment.duration,
      // retain the segment in case the playlist updates while doing an async process
      segment,
      part,
      byteLength: 0,
      transmuxer: this.transmuxer_,
      // type of getMediaInfoForTime that was used to get this segment
      getMediaInfoForTime: getMediaInfoForTime3,
      independent
    };
    var overrideCheck = typeof forceTimestampOffset !== "undefined" ? forceTimestampOffset : this.isPendingTimestampOffset_;
    segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
      segmentTimeline: segment.timeline,
      currentTimeline: this.currentTimeline_,
      startOfSegment,
      buffered: this.buffered_(),
      overrideCheck
    });
    var audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
    if (typeof audioBufferedEnd === "number") {
      segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
    }
    if (this.sourceUpdater_.videoBuffered().length) {
      segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(
        this.gopBuffer_,
        // since the transmuxer is using the actual timing values, but the time is
        // adjusted by the timestmap offset, we must adjust the value here
        this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(),
        this.timeMapping_
      );
    }
    return segmentInfo;
  };
  _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_(options) {
    return timestampOffsetForSegment(options);
  };
  _proto.earlyAbortWhenNeeded_ = function earlyAbortWhenNeeded_(stats) {
    if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
    // TODO: Replace using timeout with a boolean indicating whether this playlist is
    //       the lowestEnabledRendition.
    !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
    !this.playlist_.attributes.BANDWIDTH) {
      return;
    }
    if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1e3) {
      return;
    }
    var currentTime = this.currentTime_();
    var measuredBandwidth = stats.bandwidth;
    var segmentDuration = this.pendingSegment_.duration;
    var requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived);
    var timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1;
    if (requestTimeRemaining <= timeUntilRebuffer$1) {
      return;
    }
    var switchCandidate = minRebufferMaxBandwidthSelector({
      master: this.vhs_.playlists.master,
      currentTime,
      bandwidth: measuredBandwidth,
      duration: this.duration_(),
      segmentDuration,
      timeUntilRebuffer: timeUntilRebuffer$1,
      currentTimeline: this.currentTimeline_,
      syncController: this.syncController_
    });
    if (!switchCandidate) {
      return;
    }
    var rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
    var timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
    var minimumTimeSaving = 0.5;
    if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
      minimumTimeSaving = 1;
    }
    if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
      return;
    }
    this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
    this.trigger("earlyabort");
  };
  _proto.handleAbort_ = function handleAbort_(segmentInfo) {
    this.logger_("Aborting " + segmentInfoString(segmentInfo));
    this.mediaRequestsAborted += 1;
  };
  _proto.handleProgress_ = function handleProgress_(event, simpleSegment) {
    this.earlyAbortWhenNeeded_(simpleSegment.stats);
    if (this.checkForAbort_(simpleSegment.requestId)) {
      return;
    }
    this.trigger("progress");
  };
  _proto.handleTrackInfo_ = function handleTrackInfo_(simpleSegment, trackInfo) {
    this.earlyAbortWhenNeeded_(simpleSegment.stats);
    if (this.checkForAbort_(simpleSegment.requestId)) {
      return;
    }
    if (this.checkForIllegalMediaSwitch(trackInfo)) {
      return;
    }
    trackInfo = trackInfo || {};
    if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
      this.appendInitSegment_ = {
        audio: true,
        video: true
      };
      this.startingMediaInfo_ = trackInfo;
      this.currentMediaInfo_ = trackInfo;
      this.logger_("trackinfo update", trackInfo);
      this.trigger("trackinfo");
    }
    if (this.checkForAbort_(simpleSegment.requestId)) {
      return;
    }
    this.pendingSegment_.trackInfo = trackInfo;
    if (this.hasEnoughInfoToAppend_()) {
      this.processCallQueue_();
    }
  };
  _proto.handleTimingInfo_ = function handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
    this.earlyAbortWhenNeeded_(simpleSegment.stats);
    if (this.checkForAbort_(simpleSegment.requestId)) {
      return;
    }
    var segmentInfo = this.pendingSegment_;
    var timingInfoProperty = timingInfoPropertyForMedia(mediaType);
    segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
    segmentInfo[timingInfoProperty][timeType] = time;
    this.logger_("timinginfo: " + mediaType + " - " + timeType + " - " + time);
    if (this.hasEnoughInfoToAppend_()) {
      this.processCallQueue_();
    }
  };
  _proto.handleCaptions_ = function handleCaptions_(simpleSegment, captionData) {
    var _this2 = this;
    this.earlyAbortWhenNeeded_(simpleSegment.stats);
    if (this.checkForAbort_(simpleSegment.requestId)) {
      return;
    }
    if (captionData.length === 0) {
      this.logger_("SegmentLoader received no captions from a caption event");
      return;
    }
    var segmentInfo = this.pendingSegment_;
    if (!segmentInfo.hasAppendedData_) {
      this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
      return;
    }
    var timestampOffset2 = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
    var captionTracks = {};
    captionData.forEach(function(caption) {
      captionTracks[caption.stream] = captionTracks[caption.stream] || {
        // Infinity, as any other value will be less than this
        startTime: Infinity,
        captions: [],
        // 0 as an other value will be more than this
        endTime: 0
      };
      var captionTrack = captionTracks[caption.stream];
      captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset2);
      captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset2);
      captionTrack.captions.push(caption);
    });
    Object.keys(captionTracks).forEach(function(trackName) {
      var _captionTracks$trackN = captionTracks[trackName], startTime = _captionTracks$trackN.startTime, endTime = _captionTracks$trackN.endTime, captions = _captionTracks$trackN.captions;
      var inbandTextTracks = _this2.inbandTextTracks_;
      _this2.logger_("adding cues from " + startTime + " -> " + endTime + " for " + trackName);
      createCaptionsTrackIfNotExists(inbandTextTracks, _this2.vhs_.tech_, trackName);
      removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
      addCaptionData({
        captionArray: captions,
        inbandTextTracks,
        timestampOffset: timestampOffset2
      });
    });
    if (this.transmuxer_) {
      this.transmuxer_.postMessage({
        action: "clearParsedMp4Captions"
      });
    }
  };
  _proto.handleId3_ = function handleId3_(simpleSegment, id3Frames, dispatchType) {
    this.earlyAbortWhenNeeded_(simpleSegment.stats);
    if (this.checkForAbort_(simpleSegment.requestId)) {
      return;
    }
    var segmentInfo = this.pendingSegment_;
    if (!segmentInfo.hasAppendedData_) {
      this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
      return;
    }
    var timestampOffset2 = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
    createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
    addMetadata({
      inbandTextTracks: this.inbandTextTracks_,
      metadataArray: id3Frames,
      timestampOffset: timestampOffset2,
      videoDuration: this.duration_()
    });
  };
  _proto.processMetadataQueue_ = function processMetadataQueue_() {
    this.metadataQueue_.id3.forEach(function(fn) {
      return fn();
    });
    this.metadataQueue_.caption.forEach(function(fn) {
      return fn();
    });
    this.metadataQueue_.id3 = [];
    this.metadataQueue_.caption = [];
  };
  _proto.processCallQueue_ = function processCallQueue_() {
    var callQueue = this.callQueue_;
    this.callQueue_ = [];
    callQueue.forEach(function(fun) {
      return fun();
    });
  };
  _proto.processLoadQueue_ = function processLoadQueue_() {
    var loadQueue = this.loadQueue_;
    this.loadQueue_ = [];
    loadQueue.forEach(function(fun) {
      return fun();
    });
  };
  _proto.hasEnoughInfoToLoad_ = function hasEnoughInfoToLoad_() {
    if (this.loaderType_ !== "audio") {
      return true;
    }
    var segmentInfo = this.pendingSegment_;
    if (!segmentInfo) {
      return false;
    }
    if (!this.getCurrentMediaInfo_()) {
      return true;
    }
    if (
      // Technically, instead of waiting to load a segment on timeline changes, a segment
      // can be requested and downloaded and only wait before it is transmuxed or parsed.
      // But in practice, there are a few reasons why it is better to wait until a loader
      // is ready to append that segment before requesting and downloading:
      //
      // 1. Because audio and main loaders cross discontinuities together, if this loader
      //    is waiting for the other to catch up, then instead of requesting another
      //    segment and using up more bandwidth, by not yet loading, more bandwidth is
      //    allotted to the loader currently behind.
      // 2. media-segment-request doesn't have to have logic to consider whether a segment
      // is ready to be processed or not, isolating the queueing behavior to the loader.
      // 3. The audio loader bases some of its segment properties on timing information
      //    provided by the main loader, meaning that, if the logic for waiting on
      //    processing was in media-segment-request, then it would also need to know how
      //    to re-generate the segment information after the main loader caught up.
      shouldWaitForTimelineChange({
        timelineChangeController: this.timelineChangeController_,
        currentTimeline: this.currentTimeline_,
        segmentTimeline: segmentInfo.timeline,
        loaderType: this.loaderType_,
        audioDisabled: this.audioDisabled_
      })
    ) {
      return false;
    }
    return true;
  };
  _proto.getCurrentMediaInfo_ = function getCurrentMediaInfo_(segmentInfo) {
    if (segmentInfo === void 0) {
      segmentInfo = this.pendingSegment_;
    }
    return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  };
  _proto.getMediaInfo_ = function getMediaInfo_(segmentInfo) {
    if (segmentInfo === void 0) {
      segmentInfo = this.pendingSegment_;
    }
    return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  };
  _proto.hasEnoughInfoToAppend_ = function hasEnoughInfoToAppend_() {
    if (!this.sourceUpdater_.ready()) {
      return false;
    }
    if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
      return false;
    }
    var segmentInfo = this.pendingSegment_;
    var trackInfo = this.getCurrentMediaInfo_();
    if (!segmentInfo || !trackInfo) {
      return false;
    }
    var hasAudio = trackInfo.hasAudio, hasVideo = trackInfo.hasVideo, isMuxed3 = trackInfo.isMuxed;
    if (hasVideo && !segmentInfo.videoTimingInfo) {
      return false;
    }
    if (hasAudio && !this.audioDisabled_ && !isMuxed3 && !segmentInfo.audioTimingInfo) {
      return false;
    }
    if (shouldWaitForTimelineChange({
      timelineChangeController: this.timelineChangeController_,
      currentTimeline: this.currentTimeline_,
      segmentTimeline: segmentInfo.timeline,
      loaderType: this.loaderType_,
      audioDisabled: this.audioDisabled_
    })) {
      return false;
    }
    return true;
  };
  _proto.handleData_ = function handleData_3(simpleSegment, result) {
    this.earlyAbortWhenNeeded_(simpleSegment.stats);
    if (this.checkForAbort_(simpleSegment.requestId)) {
      return;
    }
    if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
      this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
      return;
    }
    var segmentInfo = this.pendingSegment_;
    this.setTimeMapping_(segmentInfo.timeline);
    this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment);
    if (this.mediaSource_.readyState === "closed") {
      return;
    }
    if (simpleSegment.map) {
      simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true);
      segmentInfo.segment.map = simpleSegment.map;
    }
    if (simpleSegment.key) {
      this.segmentKey(simpleSegment.key, true);
    }
    segmentInfo.isFmp4 = simpleSegment.isFmp4;
    segmentInfo.timingInfo = segmentInfo.timingInfo || {};
    if (segmentInfo.isFmp4) {
      this.trigger("fmp4");
      segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
    } else {
      var trackInfo = this.getCurrentMediaInfo_();
      var useVideoTimingInfo = this.loaderType_ === "main" && trackInfo && trackInfo.hasVideo;
      var firstVideoFrameTimeForData;
      if (useVideoTimingInfo) {
        firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
      }
      segmentInfo.timingInfo.start = this.trueSegmentStart_({
        currentStart: segmentInfo.timingInfo.start,
        playlist: segmentInfo.playlist,
        mediaIndex: segmentInfo.mediaIndex,
        currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
        useVideoTimingInfo,
        firstVideoFrameTimeForData,
        videoTimingInfo: segmentInfo.videoTimingInfo,
        audioTimingInfo: segmentInfo.audioTimingInfo
      });
    }
    this.updateAppendInitSegmentStatus(segmentInfo, result.type);
    this.updateSourceBufferTimestampOffset_(segmentInfo);
    if (segmentInfo.isSyncRequest) {
      this.updateTimingInfoEnd_(segmentInfo);
      this.syncController_.saveSegmentTimingInfo({
        segmentInfo,
        shouldSaveTimelineMapping: this.loaderType_ === "main"
      });
      var next = this.chooseNextRequest_();
      if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
        this.logger_("sync segment was incorrect, not appending");
        return;
      }
      this.logger_("sync segment was correct, appending");
    }
    segmentInfo.hasAppendedData_ = true;
    this.processMetadataQueue_();
    this.appendData_(segmentInfo, result);
  };
  _proto.updateAppendInitSegmentStatus = function updateAppendInitSegmentStatus(segmentInfo, type2) {
    if (this.loaderType_ === "main" && typeof segmentInfo.timestampOffset === "number" && // in the case that we're handling partial data, we don't want to append an init
    // segment for each chunk
    !segmentInfo.changedTimestampOffset) {
      this.appendInitSegment_ = {
        audio: true,
        video: true
      };
    }
    if (this.playlistOfLastInitSegment_[type2] !== segmentInfo.playlist) {
      this.appendInitSegment_[type2] = true;
    }
  };
  _proto.getInitSegmentAndUpdateState_ = function getInitSegmentAndUpdateState_(_ref4) {
    var type2 = _ref4.type, initSegment = _ref4.initSegment, map = _ref4.map, playlist = _ref4.playlist;
    if (map) {
      var id = initSegmentId(map);
      if (this.activeInitSegmentId_ === id) {
        return null;
      }
      initSegment = this.initSegmentForMap(map, true).bytes;
      this.activeInitSegmentId_ = id;
    }
    if (initSegment && this.appendInitSegment_[type2]) {
      this.playlistOfLastInitSegment_[type2] = playlist;
      this.appendInitSegment_[type2] = false;
      this.activeInitSegmentId_ = null;
      return initSegment;
    }
    return null;
  };
  _proto.handleQuotaExceededError_ = function handleQuotaExceededError_(_ref5, error) {
    var _this3 = this;
    var segmentInfo = _ref5.segmentInfo, type2 = _ref5.type, bytes = _ref5.bytes;
    var audioBuffered = this.sourceUpdater_.audioBuffered();
    var videoBuffered = this.sourceUpdater_.videoBuffered();
    if (audioBuffered.length > 1) {
      this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: " + timeRangesToArray(audioBuffered).join(", "));
    }
    if (videoBuffered.length > 1) {
      this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: " + timeRangesToArray(videoBuffered).join(", "));
    }
    var audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
    var audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
    var videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
    var videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
    if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
      this.logger_("On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. " + ("Appended byte length: " + bytes.byteLength + ", ") + ("audio buffer: " + timeRangesToArray(audioBuffered).join(", ") + ", ") + ("video buffer: " + timeRangesToArray(videoBuffered).join(", ") + ", "));
      this.error({
        message: "Quota exceeded error with append of a single segment of content",
        excludeUntil: Infinity
      });
      this.trigger("error");
      return;
    }
    this.waitingOnRemove_ = true;
    this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
      segmentInfo,
      type: type2,
      bytes
    }));
    var currentTime = this.currentTime_();
    var timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
    this.logger_("On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to " + timeToRemoveUntil);
    this.remove(0, timeToRemoveUntil, function() {
      _this3.logger_("On QUOTA_EXCEEDED_ERR, retrying append in " + MIN_BACK_BUFFER + "s");
      _this3.waitingOnRemove_ = false;
      _this3.quotaExceededErrorRetryTimeout_ = import_window6.default.setTimeout(function() {
        _this3.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue");
        _this3.quotaExceededErrorRetryTimeout_ = null;
        _this3.processCallQueue_();
      }, MIN_BACK_BUFFER * 1e3);
    }, true);
  };
  _proto.handleAppendError_ = function handleAppendError_(_ref6, error) {
    var segmentInfo = _ref6.segmentInfo, type2 = _ref6.type, bytes = _ref6.bytes;
    if (!error) {
      return;
    }
    if (error.code === QUOTA_EXCEEDED_ERR) {
      this.handleQuotaExceededError_({
        segmentInfo,
        type: type2,
        bytes
      });
      return;
    }
    this.logger_("Received non QUOTA_EXCEEDED_ERR on append", error);
    this.error(type2 + " append of " + bytes.length + "b failed for segment " + ("#" + segmentInfo.mediaIndex + " in playlist " + segmentInfo.playlist.id));
    this.trigger("appenderror");
  };
  _proto.appendToSourceBuffer_ = function appendToSourceBuffer_(_ref7) {
    var segmentInfo = _ref7.segmentInfo, type2 = _ref7.type, initSegment = _ref7.initSegment, data = _ref7.data, bytes = _ref7.bytes;
    if (!bytes) {
      var segments = [data];
      var byteLength = data.byteLength;
      if (initSegment) {
        segments.unshift(initSegment);
        byteLength += initSegment.byteLength;
      }
      bytes = concatSegments({
        bytes: byteLength,
        segments
      });
    }
    this.sourceUpdater_.appendBuffer({
      segmentInfo,
      type: type2,
      bytes
    }, this.handleAppendError_.bind(this, {
      segmentInfo,
      type: type2,
      bytes
    }));
  };
  _proto.handleSegmentTimingInfo_ = function handleSegmentTimingInfo_(type2, requestId, segmentTimingInfo) {
    if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
      return;
    }
    var segment = this.pendingSegment_.segment;
    var timingInfoProperty = type2 + "TimingInfo";
    if (!segment[timingInfoProperty]) {
      segment[timingInfoProperty] = {};
    }
    segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
    segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
    segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
    segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
    segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode;
    segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  };
  _proto.appendData_ = function appendData_(segmentInfo, result) {
    var type2 = result.type, data = result.data;
    if (!data || !data.byteLength) {
      return;
    }
    if (type2 === "audio" && this.audioDisabled_) {
      return;
    }
    var initSegment = this.getInitSegmentAndUpdateState_({
      type: type2,
      initSegment: result.initSegment,
      playlist: segmentInfo.playlist,
      map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
    });
    this.appendToSourceBuffer_({
      segmentInfo,
      type: type2,
      initSegment,
      data
    });
  };
  _proto.loadSegment_ = function loadSegment_(segmentInfo) {
    var _this4 = this;
    this.state = "WAITING";
    this.pendingSegment_ = segmentInfo;
    this.trimBackBuffer_(segmentInfo);
    if (typeof segmentInfo.timestampOffset === "number") {
      if (this.transmuxer_) {
        this.transmuxer_.postMessage({
          action: "clearAllMp4Captions"
        });
      }
    }
    if (!this.hasEnoughInfoToLoad_()) {
      this.loadQueue_.push(function() {
        var options = _extends2({}, segmentInfo, {
          forceTimestampOffset: true
        });
        _extends2(segmentInfo, _this4.generateSegmentInfo_(options));
        _this4.isPendingTimestampOffset_ = false;
        _this4.updateTransmuxerAndRequestSegment_(segmentInfo);
      });
      return;
    }
    this.updateTransmuxerAndRequestSegment_(segmentInfo);
  };
  _proto.updateTransmuxerAndRequestSegment_ = function updateTransmuxerAndRequestSegment_(segmentInfo) {
    var _this5 = this;
    if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
      this.gopBuffer_.length = 0;
      segmentInfo.gopsToAlignWith = [];
      this.timeMapping_ = 0;
      this.transmuxer_.postMessage({
        action: "reset"
      });
      this.transmuxer_.postMessage({
        action: "setTimestampOffset",
        timestampOffset: segmentInfo.timestampOffset
      });
    }
    var simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
    var isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
    var isWalkingForward = this.mediaIndex !== null;
    var isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
    // the first timeline
    segmentInfo.timeline > 0;
    var isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
    this.logger_("Requesting " + segmentInfoString(segmentInfo));
    if (simpleSegment.map && !simpleSegment.map.bytes) {
      this.logger_("going to request init segment.");
      this.appendInitSegment_ = {
        video: true,
        audio: true
      };
    }
    segmentInfo.abortRequests = mediaSegmentRequest({
      xhr: this.vhs_.xhr,
      xhrOptions: this.xhrOptions_,
      decryptionWorker: this.decrypter_,
      segment: simpleSegment,
      abortFn: this.handleAbort_.bind(this, segmentInfo),
      progressFn: this.handleProgress_.bind(this),
      trackInfoFn: this.handleTrackInfo_.bind(this),
      timingInfoFn: this.handleTimingInfo_.bind(this),
      videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, "video", segmentInfo.requestId),
      audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, "audio", segmentInfo.requestId),
      captionsFn: this.handleCaptions_.bind(this),
      isEndOfTimeline,
      endedTimelineFn: function endedTimelineFn() {
        _this5.logger_("received endedtimeline callback");
      },
      id3Fn: this.handleId3_.bind(this),
      dataFn: this.handleData_.bind(this),
      doneFn: this.segmentRequestFinished_.bind(this),
      onTransmuxerLog: function onTransmuxerLog(_ref8) {
        var message = _ref8.message, level = _ref8.level, stream = _ref8.stream;
        _this5.logger_(segmentInfoString(segmentInfo) + " logged from transmuxer stream " + stream + " as a " + level + ": " + message);
      }
    });
  };
  _proto.trimBackBuffer_ = function trimBackBuffer_(segmentInfo) {
    var removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10);
    if (removeToTime > 0) {
      this.remove(0, removeToTime);
    }
  };
  _proto.createSimplifiedSegmentObj_ = function createSimplifiedSegmentObj_(segmentInfo) {
    var segment = segmentInfo.segment;
    var part = segmentInfo.part;
    var simpleSegment = {
      resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
      byterange: part ? part.byterange : segment.byterange,
      requestId: segmentInfo.requestId,
      transmuxer: segmentInfo.transmuxer,
      audioAppendStart: segmentInfo.audioAppendStart,
      gopsToAlignWith: segmentInfo.gopsToAlignWith,
      part: segmentInfo.part
    };
    var previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
    if (previousSegment && previousSegment.timeline === segment.timeline) {
      if (previousSegment.videoTimingInfo) {
        simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
      } else if (previousSegment.audioTimingInfo) {
        simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
      }
    }
    if (segment.key) {
      var iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
      simpleSegment.key = this.segmentKey(segment.key);
      simpleSegment.key.iv = iv;
    }
    if (segment.map) {
      simpleSegment.map = this.initSegmentForMap(segment.map);
    }
    return simpleSegment;
  };
  _proto.saveTransferStats_ = function saveTransferStats_(stats) {
    this.mediaRequests += 1;
    if (stats) {
      this.mediaBytesTransferred += stats.bytesReceived;
      this.mediaTransferDuration += stats.roundTripTime;
    }
  };
  _proto.saveBandwidthRelatedStats_ = function saveBandwidthRelatedStats_(duration5, stats) {
    this.pendingSegment_.byteLength = stats.bytesReceived;
    if (duration5 < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
      this.logger_("Ignoring segment's bandwidth because its duration of " + duration5 + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
      return;
    }
    this.bandwidth = stats.bandwidth;
    this.roundTrip = stats.roundTripTime;
  };
  _proto.handleTimeout_ = function handleTimeout_() {
    this.mediaRequestsTimedout += 1;
    this.bandwidth = 1;
    this.roundTrip = NaN;
    this.trigger("bandwidthupdate");
  };
  _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
    if (this.callQueue_.length) {
      this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
      return;
    }
    this.saveTransferStats_(simpleSegment.stats);
    if (!this.pendingSegment_) {
      return;
    }
    if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
      return;
    }
    if (error) {
      this.pendingSegment_ = null;
      this.state = "READY";
      if (error.code === REQUEST_ERRORS.ABORTED) {
        return;
      }
      this.pause();
      if (error.code === REQUEST_ERRORS.TIMEOUT) {
        this.handleTimeout_();
        return;
      }
      this.mediaRequestsErrored += 1;
      this.error(error);
      this.trigger("error");
      return;
    }
    var segmentInfo = this.pendingSegment_;
    this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
    segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
    if (result.gopInfo) {
      this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
    }
    this.state = "APPENDING";
    this.trigger("appending");
    this.waitForAppendsToComplete_(segmentInfo);
  };
  _proto.setTimeMapping_ = function setTimeMapping_(timeline) {
    var timelineMapping = this.syncController_.mappingForTimeline(timeline);
    if (timelineMapping !== null) {
      this.timeMapping_ = timelineMapping;
    }
  };
  _proto.updateMediaSecondsLoaded_ = function updateMediaSecondsLoaded_(segment) {
    if (typeof segment.start === "number" && typeof segment.end === "number") {
      this.mediaSecondsLoaded += segment.end - segment.start;
    } else {
      this.mediaSecondsLoaded += segment.duration;
    }
  };
  _proto.shouldUpdateTransmuxerTimestampOffset_ = function shouldUpdateTransmuxerTimestampOffset_(timestampOffset2) {
    if (timestampOffset2 === null) {
      return false;
    }
    if (this.loaderType_ === "main" && timestampOffset2 !== this.sourceUpdater_.videoTimestampOffset()) {
      return true;
    }
    if (!this.audioDisabled_ && timestampOffset2 !== this.sourceUpdater_.audioTimestampOffset()) {
      return true;
    }
    return false;
  };
  _proto.trueSegmentStart_ = function trueSegmentStart_(_ref9) {
    var currentStart = _ref9.currentStart, playlist = _ref9.playlist, mediaIndex = _ref9.mediaIndex, firstVideoFrameTimeForData = _ref9.firstVideoFrameTimeForData, currentVideoTimestampOffset = _ref9.currentVideoTimestampOffset, useVideoTimingInfo = _ref9.useVideoTimingInfo, videoTimingInfo = _ref9.videoTimingInfo, audioTimingInfo = _ref9.audioTimingInfo;
    if (typeof currentStart !== "undefined") {
      return currentStart;
    }
    if (!useVideoTimingInfo) {
      return audioTimingInfo.start;
    }
    var previousSegment = playlist.segments[mediaIndex - 1];
    if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === "undefined" || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
      return firstVideoFrameTimeForData;
    }
    return videoTimingInfo.start;
  };
  _proto.waitForAppendsToComplete_ = function waitForAppendsToComplete_(segmentInfo) {
    var trackInfo = this.getCurrentMediaInfo_(segmentInfo);
    if (!trackInfo) {
      this.error({
        message: "No starting media returned, likely due to an unsupported media format.",
        blacklistDuration: Infinity
      });
      this.trigger("error");
      return;
    }
    var hasAudio = trackInfo.hasAudio, hasVideo = trackInfo.hasVideo, isMuxed3 = trackInfo.isMuxed;
    var waitForVideo = this.loaderType_ === "main" && hasVideo;
    var waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed3;
    segmentInfo.waitingOnAppends = 0;
    if (!segmentInfo.hasAppendedData_) {
      if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === "number") {
        this.isPendingTimestampOffset_ = true;
      }
      segmentInfo.timingInfo = {
        start: 0
      };
      segmentInfo.waitingOnAppends++;
      if (!this.isPendingTimestampOffset_) {
        this.updateSourceBufferTimestampOffset_(segmentInfo);
        this.processMetadataQueue_();
      }
      this.checkAppendsDone_(segmentInfo);
      return;
    }
    if (waitForVideo) {
      segmentInfo.waitingOnAppends++;
    }
    if (waitForAudio) {
      segmentInfo.waitingOnAppends++;
    }
    if (waitForVideo) {
      this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
    }
    if (waitForAudio) {
      this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
    }
  };
  _proto.checkAppendsDone_ = function checkAppendsDone_(segmentInfo) {
    if (this.checkForAbort_(segmentInfo.requestId)) {
      return;
    }
    segmentInfo.waitingOnAppends--;
    if (segmentInfo.waitingOnAppends === 0) {
      this.handleAppendsDone_();
    }
  };
  _proto.checkForIllegalMediaSwitch = function checkForIllegalMediaSwitch(trackInfo) {
    var illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
    if (illegalMediaSwitchError) {
      this.error({
        message: illegalMediaSwitchError,
        blacklistDuration: Infinity
      });
      this.trigger("error");
      return true;
    }
    return false;
  };
  _proto.updateSourceBufferTimestampOffset_ = function updateSourceBufferTimestampOffset_(segmentInfo) {
    if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
    // priority, timing-wise, so we must wait
    typeof segmentInfo.timingInfo.start !== "number" || // already updated the timestamp offset for this segment
    segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
    this.loaderType_ !== "main") {
      return;
    }
    var didChange = false;
    segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
      videoTimingInfo: segmentInfo.segment.videoTimingInfo,
      audioTimingInfo: segmentInfo.segment.audioTimingInfo,
      timingInfo: segmentInfo.timingInfo
    });
    segmentInfo.changedTimestampOffset = true;
    if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
      this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
      didChange = true;
    }
    if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
      this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
      didChange = true;
    }
    if (didChange) {
      this.trigger("timestampoffset");
    }
  };
  _proto.getSegmentStartTimeForTimestampOffsetCalculation_ = function getSegmentStartTimeForTimestampOffsetCalculation_(_ref10) {
    var videoTimingInfo = _ref10.videoTimingInfo, audioTimingInfo = _ref10.audioTimingInfo, timingInfo = _ref10.timingInfo;
    if (!this.useDtsForTimestampOffset_) {
      return timingInfo.start;
    }
    if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === "number") {
      return videoTimingInfo.transmuxedDecodeStart;
    }
    if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === "number") {
      return audioTimingInfo.transmuxedDecodeStart;
    }
    return timingInfo.start;
  };
  _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_(segmentInfo) {
    segmentInfo.timingInfo = segmentInfo.timingInfo || {};
    var trackInfo = this.getMediaInfo_();
    var useVideoTimingInfo = this.loaderType_ === "main" && trackInfo && trackInfo.hasVideo;
    var prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
    if (!prioritizedTimingInfo) {
      return;
    }
    segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === "number" ? (
      // End time may not exist in a case where we aren't parsing the full segment (one
      // current example is the case of fmp4), so use the rough duration to calculate an
      // end time.
      prioritizedTimingInfo.end
    ) : prioritizedTimingInfo.start + segmentInfo.duration;
  };
  _proto.handleAppendsDone_ = function handleAppendsDone_() {
    if (this.pendingSegment_) {
      this.trigger("appendsdone");
    }
    if (!this.pendingSegment_) {
      this.state = "READY";
      if (!this.paused()) {
        this.monitorBuffer_();
      }
      return;
    }
    var segmentInfo = this.pendingSegment_;
    this.updateTimingInfoEnd_(segmentInfo);
    if (this.shouldSaveSegmentTimingInfo_) {
      this.syncController_.saveSegmentTimingInfo({
        segmentInfo,
        shouldSaveTimelineMapping: this.loaderType_ === "main"
      });
    }
    var segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
    if (segmentDurationMessage) {
      if (segmentDurationMessage.severity === "warn") {
        videojs.log.warn(segmentDurationMessage.message);
      } else {
        this.logger_(segmentDurationMessage.message);
      }
    }
    this.recordThroughput_(segmentInfo);
    this.pendingSegment_ = null;
    this.state = "READY";
    if (segmentInfo.isSyncRequest) {
      this.trigger("syncinfoupdate");
      if (!segmentInfo.hasAppendedData_) {
        this.logger_("Throwing away un-appended sync request " + segmentInfoString(segmentInfo));
        return;
      }
    }
    this.logger_("Appended " + segmentInfoString(segmentInfo));
    this.addSegmentMetadataCue_(segmentInfo);
    this.fetchAtBuffer_ = true;
    if (this.currentTimeline_ !== segmentInfo.timeline) {
      this.timelineChangeController_.lastTimelineChange({
        type: this.loaderType_,
        from: this.currentTimeline_,
        to: segmentInfo.timeline
      });
      if (this.loaderType_ === "main" && !this.audioDisabled_) {
        this.timelineChangeController_.lastTimelineChange({
          type: "audio",
          from: this.currentTimeline_,
          to: segmentInfo.timeline
        });
      }
    }
    this.currentTimeline_ = segmentInfo.timeline;
    this.trigger("syncinfoupdate");
    var segment = segmentInfo.segment;
    var part = segmentInfo.part;
    var badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
    var badPartGuess = part && part.end && this.currentTime_() - part.end > segmentInfo.playlist.partTargetDuration * 3;
    if (badSegmentGuess || badPartGuess) {
      this.logger_("bad " + (badSegmentGuess ? "segment" : "part") + " " + segmentInfoString(segmentInfo));
      this.resetEverything();
      return;
    }
    var isWalkingForward = this.mediaIndex !== null;
    if (isWalkingForward) {
      this.trigger("bandwidthupdate");
    }
    this.trigger("progress");
    this.mediaIndex = segmentInfo.mediaIndex;
    this.partIndex = segmentInfo.partIndex;
    if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
      this.endOfStream();
    }
    this.trigger("appended");
    if (segmentInfo.hasAppendedData_) {
      this.mediaAppends++;
    }
    if (!this.paused()) {
      this.monitorBuffer_();
    }
  };
  _proto.recordThroughput_ = function recordThroughput_(segmentInfo) {
    if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
      this.logger_("Ignoring segment's throughput because its duration of " + segmentInfo.duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
      return;
    }
    var rate = this.throughput.rate;
    var segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1;
    var segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1e3);
    this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  };
  _proto.addSegmentMetadataCue_ = function addSegmentMetadataCue_(segmentInfo) {
    if (!this.segmentMetadataTrack_) {
      return;
    }
    var segment = segmentInfo.segment;
    var start2 = segment.start;
    var end = segment.end;
    if (!finite(start2) || !finite(end)) {
      return;
    }
    removeCuesFromTrack(start2, end, this.segmentMetadataTrack_);
    var Cue = import_window6.default.WebKitDataCue || import_window6.default.VTTCue;
    var value = {
      custom: segment.custom,
      dateTimeObject: segment.dateTimeObject,
      dateTimeString: segment.dateTimeString,
      bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
      resolution: segmentInfo.playlist.attributes.RESOLUTION,
      codecs: segmentInfo.playlist.attributes.CODECS,
      byteLength: segmentInfo.byteLength,
      uri: segmentInfo.uri,
      timeline: segmentInfo.timeline,
      playlist: segmentInfo.playlist.id,
      start: start2,
      end
    };
    var data = JSON.stringify(value);
    var cue = new Cue(start2, end, data);
    cue.value = value;
    this.segmentMetadataTrack_.addCue(cue);
  };
  return SegmentLoader2;
}(videojs.EventTarget);
function noop3() {
}
var toTitleCase2 = function toTitleCase3(string) {
  if (typeof string !== "string") {
    return string;
  }
  return string.replace(/./, function(w) {
    return w.toUpperCase();
  });
};
var bufferTypes = ["video", "audio"];
var _updating = function updating(type2, sourceUpdater) {
  var sourceBuffer = sourceUpdater[type2 + "Buffer"];
  return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type2];
};
var nextQueueIndexOfType = function nextQueueIndexOfType2(type2, queue) {
  for (var i = 0; i < queue.length; i++) {
    var queueEntry = queue[i];
    if (queueEntry.type === "mediaSource") {
      return null;
    }
    if (queueEntry.type === type2) {
      return i;
    }
  }
  return null;
};
var shiftQueue = function shiftQueue2(type2, sourceUpdater) {
  if (sourceUpdater.queue.length === 0) {
    return;
  }
  var queueIndex = 0;
  var queueEntry = sourceUpdater.queue[queueIndex];
  if (queueEntry.type === "mediaSource") {
    if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== "closed") {
      sourceUpdater.queue.shift();
      queueEntry.action(sourceUpdater);
      if (queueEntry.doneFn) {
        queueEntry.doneFn();
      }
      shiftQueue2("audio", sourceUpdater);
      shiftQueue2("video", sourceUpdater);
    }
    return;
  }
  if (type2 === "mediaSource") {
    return;
  }
  if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === "closed" || _updating(type2, sourceUpdater)) {
    return;
  }
  if (queueEntry.type !== type2) {
    queueIndex = nextQueueIndexOfType(type2, sourceUpdater.queue);
    if (queueIndex === null) {
      return;
    }
    queueEntry = sourceUpdater.queue[queueIndex];
  }
  sourceUpdater.queue.splice(queueIndex, 1);
  sourceUpdater.queuePending[type2] = queueEntry;
  queueEntry.action(type2, sourceUpdater);
  if (!queueEntry.doneFn) {
    sourceUpdater.queuePending[type2] = null;
    shiftQueue2(type2, sourceUpdater);
    return;
  }
};
var cleanupBuffer = function cleanupBuffer2(type2, sourceUpdater) {
  var buffer = sourceUpdater[type2 + "Buffer"];
  var titleType = toTitleCase2(type2);
  if (!buffer) {
    return;
  }
  buffer.removeEventListener("updateend", sourceUpdater["on" + titleType + "UpdateEnd_"]);
  buffer.removeEventListener("error", sourceUpdater["on" + titleType + "Error_"]);
  sourceUpdater.codecs[type2] = null;
  sourceUpdater[type2 + "Buffer"] = null;
};
var inSourceBuffers = function inSourceBuffers2(mediaSource, sourceBuffer) {
  return mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
};
var actions = {
  appendBuffer: function appendBuffer(bytes, segmentInfo, onError2) {
    return function(type2, sourceUpdater) {
      var sourceBuffer = sourceUpdater[type2 + "Buffer"];
      if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
        return;
      }
      sourceUpdater.logger_("Appending segment " + segmentInfo.mediaIndex + "'s " + bytes.length + " bytes to " + type2 + "Buffer");
      try {
        sourceBuffer.appendBuffer(bytes);
      } catch (e) {
        sourceUpdater.logger_("Error with code " + e.code + " " + (e.code === QUOTA_EXCEEDED_ERR ? "(QUOTA_EXCEEDED_ERR) " : "") + ("when appending segment " + segmentInfo.mediaIndex + " to " + type2 + "Buffer"));
        sourceUpdater.queuePending[type2] = null;
        onError2(e);
      }
    };
  },
  remove: function remove(start2, end) {
    return function(type2, sourceUpdater) {
      var sourceBuffer = sourceUpdater[type2 + "Buffer"];
      if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
        return;
      }
      sourceUpdater.logger_("Removing " + start2 + " to " + end + " from " + type2 + "Buffer");
      try {
        sourceBuffer.remove(start2, end);
      } catch (e) {
        sourceUpdater.logger_("Remove " + start2 + " to " + end + " from " + type2 + "Buffer failed");
      }
    };
  },
  timestampOffset: function timestampOffset(offset) {
    return function(type2, sourceUpdater) {
      var sourceBuffer = sourceUpdater[type2 + "Buffer"];
      if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
        return;
      }
      sourceUpdater.logger_("Setting " + type2 + "timestampOffset to " + offset);
      sourceBuffer.timestampOffset = offset;
    };
  },
  callback: function callback(_callback) {
    return function(type2, sourceUpdater) {
      _callback();
    };
  },
  endOfStream: function endOfStream(error) {
    return function(sourceUpdater) {
      if (sourceUpdater.mediaSource.readyState !== "open") {
        return;
      }
      sourceUpdater.logger_("Calling mediaSource endOfStream(" + (error || "") + ")");
      try {
        sourceUpdater.mediaSource.endOfStream(error);
      } catch (e) {
        videojs.log.warn("Failed to call media source endOfStream", e);
      }
    };
  },
  duration: function duration4(_duration) {
    return function(sourceUpdater) {
      sourceUpdater.logger_("Setting mediaSource duration to " + _duration);
      try {
        sourceUpdater.mediaSource.duration = _duration;
      } catch (e) {
        videojs.log.warn("Failed to set media source duration", e);
      }
    };
  },
  abort: function abort() {
    return function(type2, sourceUpdater) {
      if (sourceUpdater.mediaSource.readyState !== "open") {
        return;
      }
      var sourceBuffer = sourceUpdater[type2 + "Buffer"];
      if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
        return;
      }
      sourceUpdater.logger_("calling abort on " + type2 + "Buffer");
      try {
        sourceBuffer.abort();
      } catch (e) {
        videojs.log.warn("Failed to abort on " + type2 + "Buffer", e);
      }
    };
  },
  addSourceBuffer: function addSourceBuffer(type2, codec) {
    return function(sourceUpdater) {
      var titleType = toTitleCase2(type2);
      var mime = getMimeForCodec(codec);
      sourceUpdater.logger_("Adding " + type2 + "Buffer with codec " + codec + " to mediaSource");
      var sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
      sourceBuffer.addEventListener("updateend", sourceUpdater["on" + titleType + "UpdateEnd_"]);
      sourceBuffer.addEventListener("error", sourceUpdater["on" + titleType + "Error_"]);
      sourceUpdater.codecs[type2] = codec;
      sourceUpdater[type2 + "Buffer"] = sourceBuffer;
    };
  },
  removeSourceBuffer: function removeSourceBuffer(type2) {
    return function(sourceUpdater) {
      var sourceBuffer = sourceUpdater[type2 + "Buffer"];
      cleanupBuffer(type2, sourceUpdater);
      if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
        return;
      }
      sourceUpdater.logger_("Removing " + type2 + "Buffer with codec " + sourceUpdater.codecs[type2] + " from mediaSource");
      try {
        sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
      } catch (e) {
        videojs.log.warn("Failed to removeSourceBuffer " + type2 + "Buffer", e);
      }
    };
  },
  changeType: function changeType(codec) {
    return function(type2, sourceUpdater) {
      var sourceBuffer = sourceUpdater[type2 + "Buffer"];
      var mime = getMimeForCodec(codec);
      if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
        return;
      }
      if (sourceUpdater.codecs[type2] === codec) {
        return;
      }
      sourceUpdater.logger_("changing " + type2 + "Buffer codec from " + sourceUpdater.codecs[type2] + " to " + codec);
      sourceBuffer.changeType(mime);
      sourceUpdater.codecs[type2] = codec;
    };
  }
};
var pushQueue = function pushQueue2(_ref) {
  var type2 = _ref.type, sourceUpdater = _ref.sourceUpdater, action = _ref.action, doneFn = _ref.doneFn, name = _ref.name;
  sourceUpdater.queue.push({
    type: type2,
    action,
    doneFn,
    name
  });
  shiftQueue(type2, sourceUpdater);
};
var onUpdateend = function onUpdateend2(type2, sourceUpdater) {
  return function(e) {
    if (sourceUpdater.queuePending[type2]) {
      var doneFn = sourceUpdater.queuePending[type2].doneFn;
      sourceUpdater.queuePending[type2] = null;
      if (doneFn) {
        doneFn(sourceUpdater[type2 + "Error_"]);
      }
    }
    shiftQueue(type2, sourceUpdater);
  };
};
var SourceUpdater = /* @__PURE__ */ function(_videojs$EventTarget) {
  _inheritsLoose(SourceUpdater2, _videojs$EventTarget);
  function SourceUpdater2(mediaSource) {
    var _this;
    _this = _videojs$EventTarget.call(this) || this;
    _this.mediaSource = mediaSource;
    _this.sourceopenListener_ = function() {
      return shiftQueue("mediaSource", _assertThisInitialized(_this));
    };
    _this.mediaSource.addEventListener("sourceopen", _this.sourceopenListener_);
    _this.logger_ = logger2("SourceUpdater");
    _this.audioTimestampOffset_ = 0;
    _this.videoTimestampOffset_ = 0;
    _this.queue = [];
    _this.queuePending = {
      audio: null,
      video: null
    };
    _this.delayedAudioAppendQueue_ = [];
    _this.videoAppendQueued_ = false;
    _this.codecs = {};
    _this.onVideoUpdateEnd_ = onUpdateend("video", _assertThisInitialized(_this));
    _this.onAudioUpdateEnd_ = onUpdateend("audio", _assertThisInitialized(_this));
    _this.onVideoError_ = function(e) {
      _this.videoError_ = e;
    };
    _this.onAudioError_ = function(e) {
      _this.audioError_ = e;
    };
    _this.createdSourceBuffers_ = false;
    _this.initializedEme_ = false;
    _this.triggeredReady_ = false;
    return _this;
  }
  var _proto = SourceUpdater2.prototype;
  _proto.initializedEme = function initializedEme() {
    this.initializedEme_ = true;
    this.triggerReady();
  };
  _proto.hasCreatedSourceBuffers = function hasCreatedSourceBuffers() {
    return this.createdSourceBuffers_;
  };
  _proto.hasInitializedAnyEme = function hasInitializedAnyEme() {
    return this.initializedEme_;
  };
  _proto.ready = function ready() {
    return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  };
  _proto.createSourceBuffers = function createSourceBuffers(codecs) {
    if (this.hasCreatedSourceBuffers()) {
      return;
    }
    this.addOrChangeSourceBuffers(codecs);
    this.createdSourceBuffers_ = true;
    this.trigger("createdsourcebuffers");
    this.triggerReady();
  };
  _proto.triggerReady = function triggerReady() {
    if (this.ready() && !this.triggeredReady_) {
      this.triggeredReady_ = true;
      this.trigger("ready");
    }
  };
  _proto.addSourceBuffer = function addSourceBuffer2(type2, codec) {
    pushQueue({
      type: "mediaSource",
      sourceUpdater: this,
      action: actions.addSourceBuffer(type2, codec),
      name: "addSourceBuffer"
    });
  };
  _proto.abort = function abort2(type2) {
    pushQueue({
      type: type2,
      sourceUpdater: this,
      action: actions.abort(type2),
      name: "abort"
    });
  };
  _proto.removeSourceBuffer = function removeSourceBuffer2(type2) {
    if (!this.canRemoveSourceBuffer()) {
      videojs.log.error("removeSourceBuffer is not supported!");
      return;
    }
    pushQueue({
      type: "mediaSource",
      sourceUpdater: this,
      action: actions.removeSourceBuffer(type2),
      name: "removeSourceBuffer"
    });
  };
  _proto.canRemoveSourceBuffer = function canRemoveSourceBuffer() {
    return !videojs.browser.IE_VERSION && !videojs.browser.IS_FIREFOX && import_window6.default.MediaSource && import_window6.default.MediaSource.prototype && typeof import_window6.default.MediaSource.prototype.removeSourceBuffer === "function";
  };
  SourceUpdater2.canChangeType = function canChangeType() {
    return import_window6.default.SourceBuffer && import_window6.default.SourceBuffer.prototype && typeof import_window6.default.SourceBuffer.prototype.changeType === "function";
  };
  _proto.canChangeType = function canChangeType() {
    return this.constructor.canChangeType();
  };
  _proto.changeType = function changeType2(type2, codec) {
    if (!this.canChangeType()) {
      videojs.log.error("changeType is not supported!");
      return;
    }
    pushQueue({
      type: type2,
      sourceUpdater: this,
      action: actions.changeType(codec),
      name: "changeType"
    });
  };
  _proto.addOrChangeSourceBuffers = function addOrChangeSourceBuffers(codecs) {
    var _this2 = this;
    if (!codecs || typeof codecs !== "object" || Object.keys(codecs).length === 0) {
      throw new Error("Cannot addOrChangeSourceBuffers to undefined codecs");
    }
    Object.keys(codecs).forEach(function(type2) {
      var codec = codecs[type2];
      if (!_this2.hasCreatedSourceBuffers()) {
        return _this2.addSourceBuffer(type2, codec);
      }
      if (_this2.canChangeType()) {
        _this2.changeType(type2, codec);
      }
    });
  };
  _proto.appendBuffer = function appendBuffer2(options, doneFn) {
    var _this3 = this;
    var segmentInfo = options.segmentInfo, type2 = options.type, bytes = options.bytes;
    this.processedAppend_ = true;
    if (type2 === "audio" && this.videoBuffer && !this.videoAppendQueued_) {
      this.delayedAudioAppendQueue_.push([options, doneFn]);
      this.logger_("delayed audio append of " + bytes.length + " until video append");
      return;
    }
    var onError2 = doneFn;
    pushQueue({
      type: type2,
      sourceUpdater: this,
      action: actions.appendBuffer(bytes, segmentInfo || {
        mediaIndex: -1
      }, onError2),
      doneFn,
      name: "appendBuffer"
    });
    if (type2 === "video") {
      this.videoAppendQueued_ = true;
      if (!this.delayedAudioAppendQueue_.length) {
        return;
      }
      var queue = this.delayedAudioAppendQueue_.slice();
      this.logger_("queuing delayed audio " + queue.length + " appendBuffers");
      this.delayedAudioAppendQueue_.length = 0;
      queue.forEach(function(que) {
        _this3.appendBuffer.apply(_this3, que);
      });
    }
  };
  _proto.audioBuffered = function audioBuffered() {
    if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
      return videojs.createTimeRange();
    }
    return this.audioBuffer.buffered ? this.audioBuffer.buffered : videojs.createTimeRange();
  };
  _proto.videoBuffered = function videoBuffered() {
    if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
      return videojs.createTimeRange();
    }
    return this.videoBuffer.buffered ? this.videoBuffer.buffered : videojs.createTimeRange();
  };
  _proto.buffered = function buffered() {
    var video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
    var audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
    if (audio && !video) {
      return this.audioBuffered();
    }
    if (video && !audio) {
      return this.videoBuffered();
    }
    return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  };
  _proto.setDuration = function setDuration(duration5, doneFn) {
    if (doneFn === void 0) {
      doneFn = noop3;
    }
    pushQueue({
      type: "mediaSource",
      sourceUpdater: this,
      action: actions.duration(duration5),
      name: "duration",
      doneFn
    });
  };
  _proto.endOfStream = function endOfStream2(error, doneFn) {
    if (error === void 0) {
      error = null;
    }
    if (doneFn === void 0) {
      doneFn = noop3;
    }
    if (typeof error !== "string") {
      error = void 0;
    }
    pushQueue({
      type: "mediaSource",
      sourceUpdater: this,
      action: actions.endOfStream(error),
      name: "endOfStream",
      doneFn
    });
  };
  _proto.removeAudio = function removeAudio(start2, end, done) {
    if (done === void 0) {
      done = noop3;
    }
    if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
      done();
      return;
    }
    pushQueue({
      type: "audio",
      sourceUpdater: this,
      action: actions.remove(start2, end),
      doneFn: done,
      name: "remove"
    });
  };
  _proto.removeVideo = function removeVideo(start2, end, done) {
    if (done === void 0) {
      done = noop3;
    }
    if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
      done();
      return;
    }
    pushQueue({
      type: "video",
      sourceUpdater: this,
      action: actions.remove(start2, end),
      doneFn: done,
      name: "remove"
    });
  };
  _proto.updating = function updating2() {
    if (_updating("audio", this) || _updating("video", this)) {
      return true;
    }
    return false;
  };
  _proto.audioTimestampOffset = function audioTimestampOffset(offset) {
    if (typeof offset !== "undefined" && this.audioBuffer && // no point in updating if it's the same
    this.audioTimestampOffset_ !== offset) {
      pushQueue({
        type: "audio",
        sourceUpdater: this,
        action: actions.timestampOffset(offset),
        name: "timestampOffset"
      });
      this.audioTimestampOffset_ = offset;
    }
    return this.audioTimestampOffset_;
  };
  _proto.videoTimestampOffset = function videoTimestampOffset(offset) {
    if (typeof offset !== "undefined" && this.videoBuffer && // no point in updating if it's the same
    this.videoTimestampOffset !== offset) {
      pushQueue({
        type: "video",
        sourceUpdater: this,
        action: actions.timestampOffset(offset),
        name: "timestampOffset"
      });
      this.videoTimestampOffset_ = offset;
    }
    return this.videoTimestampOffset_;
  };
  _proto.audioQueueCallback = function audioQueueCallback(callback2) {
    if (!this.audioBuffer) {
      return;
    }
    pushQueue({
      type: "audio",
      sourceUpdater: this,
      action: actions.callback(callback2),
      name: "callback"
    });
  };
  _proto.videoQueueCallback = function videoQueueCallback(callback2) {
    if (!this.videoBuffer) {
      return;
    }
    pushQueue({
      type: "video",
      sourceUpdater: this,
      action: actions.callback(callback2),
      name: "callback"
    });
  };
  _proto.dispose = function dispose() {
    var _this4 = this;
    this.trigger("dispose");
    bufferTypes.forEach(function(type2) {
      _this4.abort(type2);
      if (_this4.canRemoveSourceBuffer()) {
        _this4.removeSourceBuffer(type2);
      } else {
        _this4[type2 + "QueueCallback"](function() {
          return cleanupBuffer(type2, _this4);
        });
      }
    });
    this.videoAppendQueued_ = false;
    this.delayedAudioAppendQueue_.length = 0;
    if (this.sourceopenListener_) {
      this.mediaSource.removeEventListener("sourceopen", this.sourceopenListener_);
    }
    this.off();
  };
  return SourceUpdater2;
}(videojs.EventTarget);
var uint8ToUtf8 = function uint8ToUtf82(uintArray) {
  return decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
};
var VTT_LINE_TERMINATORS = new Uint8Array("\n\n".split("").map(function(_char3) {
  return _char3.charCodeAt(0);
}));
var VTTSegmentLoader = /* @__PURE__ */ function(_SegmentLoader) {
  _inheritsLoose(VTTSegmentLoader2, _SegmentLoader);
  function VTTSegmentLoader2(settings, options) {
    var _this;
    if (options === void 0) {
      options = {};
    }
    _this = _SegmentLoader.call(this, settings, options) || this;
    _this.mediaSource_ = null;
    _this.subtitlesTrack_ = null;
    _this.loaderType_ = "subtitle";
    _this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
    _this.shouldSaveSegmentTimingInfo_ = false;
    return _this;
  }
  var _proto = VTTSegmentLoader2.prototype;
  _proto.createTransmuxer_ = function createTransmuxer_() {
    return null;
  };
  _proto.buffered_ = function buffered_() {
    if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
      return videojs.createTimeRanges();
    }
    var cues = this.subtitlesTrack_.cues;
    var start2 = cues[0].startTime;
    var end = cues[cues.length - 1].startTime;
    return videojs.createTimeRanges([[start2, end]]);
  };
  _proto.initSegmentForMap = function initSegmentForMap(map, set4) {
    if (set4 === void 0) {
      set4 = false;
    }
    if (!map) {
      return null;
    }
    var id = initSegmentId(map);
    var storedMap = this.initSegments_[id];
    if (set4 && !storedMap && map.bytes) {
      var combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
      var combinedSegment = new Uint8Array(combinedByteLength);
      combinedSegment.set(map.bytes);
      combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
      this.initSegments_[id] = storedMap = {
        resolvedUri: map.resolvedUri,
        byterange: map.byterange,
        bytes: combinedSegment
      };
    }
    return storedMap || map;
  };
  _proto.couldBeginLoading_ = function couldBeginLoading_() {
    return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  };
  _proto.init_ = function init_() {
    this.state = "READY";
    this.resetEverything();
    return this.monitorBuffer_();
  };
  _proto.track = function track(_track) {
    if (typeof _track === "undefined") {
      return this.subtitlesTrack_;
    }
    this.subtitlesTrack_ = _track;
    if (this.state === "INIT" && this.couldBeginLoading_()) {
      this.init_();
    }
    return this.subtitlesTrack_;
  };
  _proto.remove = function remove2(start2, end) {
    removeCuesFromTrack(start2, end, this.subtitlesTrack_);
  };
  _proto.fillBuffer_ = function fillBuffer_() {
    var _this2 = this;
    var segmentInfo = this.chooseNextRequest_();
    if (!segmentInfo) {
      return;
    }
    if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
      var checkTimestampOffset = function checkTimestampOffset2() {
        _this2.state = "READY";
        if (!_this2.paused()) {
          _this2.monitorBuffer_();
        }
      };
      this.syncController_.one("timestampoffset", checkTimestampOffset);
      this.state = "WAITING_ON_TIMELINE";
      return;
    }
    this.loadSegment_(segmentInfo);
  };
  _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_() {
    return null;
  };
  _proto.chooseNextRequest_ = function chooseNextRequest_() {
    return this.skipEmptySegments_(_SegmentLoader.prototype.chooseNextRequest_.call(this));
  };
  _proto.skipEmptySegments_ = function skipEmptySegments_(segmentInfo) {
    while (segmentInfo && segmentInfo.segment.empty) {
      if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
        segmentInfo = null;
        break;
      }
      segmentInfo = this.generateSegmentInfo_({
        playlist: segmentInfo.playlist,
        mediaIndex: segmentInfo.mediaIndex + 1,
        startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
        isSyncRequest: segmentInfo.isSyncRequest
      });
    }
    return segmentInfo;
  };
  _proto.stopForError = function stopForError(error) {
    this.error(error);
    this.state = "READY";
    this.pause();
    this.trigger("error");
  };
  _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
    var _this3 = this;
    if (!this.subtitlesTrack_) {
      this.state = "READY";
      return;
    }
    this.saveTransferStats_(simpleSegment.stats);
    if (!this.pendingSegment_) {
      this.state = "READY";
      this.mediaRequestsAborted += 1;
      return;
    }
    if (error) {
      if (error.code === REQUEST_ERRORS.TIMEOUT) {
        this.handleTimeout_();
      }
      if (error.code === REQUEST_ERRORS.ABORTED) {
        this.mediaRequestsAborted += 1;
      } else {
        this.mediaRequestsErrored += 1;
      }
      this.stopForError(error);
      return;
    }
    var segmentInfo = this.pendingSegment_;
    this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
    if (simpleSegment.key) {
      this.segmentKey(simpleSegment.key, true);
    }
    this.state = "APPENDING";
    this.trigger("appending");
    var segment = segmentInfo.segment;
    if (segment.map) {
      segment.map.bytes = simpleSegment.map.bytes;
    }
    segmentInfo.bytes = simpleSegment.bytes;
    if (typeof import_window6.default.WebVTT !== "function" && this.subtitlesTrack_ && this.subtitlesTrack_.tech_) {
      var loadHandler;
      var errorHandler = function errorHandler2() {
        _this3.subtitlesTrack_.tech_.off("vttjsloaded", loadHandler);
        _this3.stopForError({
          message: "Error loading vtt.js"
        });
        return;
      };
      loadHandler = function loadHandler2() {
        _this3.subtitlesTrack_.tech_.off("vttjserror", errorHandler);
        _this3.segmentRequestFinished_(error, simpleSegment, result);
      };
      this.state = "WAITING_ON_VTTJS";
      this.subtitlesTrack_.tech_.one("vttjsloaded", loadHandler);
      this.subtitlesTrack_.tech_.one("vttjserror", errorHandler);
      return;
    }
    segment.requested = true;
    try {
      this.parseVTTCues_(segmentInfo);
    } catch (e) {
      this.stopForError({
        message: e.message
      });
      return;
    }
    this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
    if (segmentInfo.cues.length) {
      segmentInfo.timingInfo = {
        start: segmentInfo.cues[0].startTime,
        end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
      };
    } else {
      segmentInfo.timingInfo = {
        start: segmentInfo.startOfSegment,
        end: segmentInfo.startOfSegment + segmentInfo.duration
      };
    }
    if (segmentInfo.isSyncRequest) {
      this.trigger("syncinfoupdate");
      this.pendingSegment_ = null;
      this.state = "READY";
      return;
    }
    segmentInfo.byteLength = segmentInfo.bytes.byteLength;
    this.mediaSecondsLoaded += segment.duration;
    segmentInfo.cues.forEach(function(cue) {
      _this3.subtitlesTrack_.addCue(_this3.featuresNativeTextTracks_ ? new import_window6.default.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
    });
    removeDuplicateCuesFromTrack(this.subtitlesTrack_);
    this.handleAppendsDone_();
  };
  _proto.handleData_ = function handleData_3() {
  };
  _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_() {
  };
  _proto.parseVTTCues_ = function parseVTTCues_(segmentInfo) {
    var decoder;
    var decodeBytesToString = false;
    if (typeof import_window6.default.TextDecoder === "function") {
      decoder = new import_window6.default.TextDecoder("utf8");
    } else {
      decoder = import_window6.default.WebVTT.StringDecoder();
      decodeBytesToString = true;
    }
    var parser6 = new import_window6.default.WebVTT.Parser(import_window6.default, import_window6.default.vttjs, decoder);
    segmentInfo.cues = [];
    segmentInfo.timestampmap = {
      MPEGTS: 0,
      LOCAL: 0
    };
    parser6.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
    parser6.ontimestampmap = function(map) {
      segmentInfo.timestampmap = map;
    };
    parser6.onparsingerror = function(error) {
      videojs.log.warn("Error encountered when parsing cues: " + error.message);
    };
    if (segmentInfo.segment.map) {
      var mapData = segmentInfo.segment.map.bytes;
      if (decodeBytesToString) {
        mapData = uint8ToUtf8(mapData);
      }
      parser6.parse(mapData);
    }
    var segmentData = segmentInfo.bytes;
    if (decodeBytesToString) {
      segmentData = uint8ToUtf8(segmentData);
    }
    parser6.parse(segmentData);
    parser6.flush();
  };
  _proto.updateTimeMapping_ = function updateTimeMapping_(segmentInfo, mappingObj, playlist) {
    var segment = segmentInfo.segment;
    if (!mappingObj) {
      return;
    }
    if (!segmentInfo.cues.length) {
      segment.empty = true;
      return;
    }
    var timestampmap = segmentInfo.timestampmap;
    var diff = timestampmap.MPEGTS / import_clock.ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
    segmentInfo.cues.forEach(function(cue) {
      cue.startTime += diff;
      cue.endTime += diff;
    });
    if (!playlist.syncInfo) {
      var firstStart = segmentInfo.cues[0].startTime;
      var lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
      playlist.syncInfo = {
        mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
        time: Math.min(firstStart, lastStart - segment.duration)
      };
    }
  };
  return VTTSegmentLoader2;
}(SegmentLoader);
var findAdCue = function findAdCue2(track, mediaTime) {
  var cues = track.cues;
  for (var i = 0; i < cues.length; i++) {
    var cue = cues[i];
    if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
      return cue;
    }
  }
  return null;
};
var updateAdCues = function updateAdCues2(media, track, offset) {
  if (offset === void 0) {
    offset = 0;
  }
  if (!media.segments) {
    return;
  }
  var mediaTime = offset;
  var cue;
  for (var i = 0; i < media.segments.length; i++) {
    var segment = media.segments[i];
    if (!cue) {
      cue = findAdCue(track, mediaTime + segment.duration / 2);
    }
    if (cue) {
      if ("cueIn" in segment) {
        cue.endTime = mediaTime;
        cue.adEndTime = mediaTime;
        mediaTime += segment.duration;
        cue = null;
        continue;
      }
      if (mediaTime < cue.endTime) {
        mediaTime += segment.duration;
        continue;
      }
      cue.endTime += segment.duration;
    } else {
      if ("cueOut" in segment) {
        cue = new import_window6.default.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
        cue.adStartTime = mediaTime;
        cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
        track.addCue(cue);
      }
      if ("cueOutCont" in segment) {
        var _segment$cueOutCont$s = segment.cueOutCont.split("/").map(parseFloat), adOffset = _segment$cueOutCont$s[0], adTotal = _segment$cueOutCont$s[1];
        cue = new import_window6.default.VTTCue(mediaTime, mediaTime + segment.duration, "");
        cue.adStartTime = mediaTime - adOffset;
        cue.adEndTime = cue.adStartTime + adTotal;
        track.addCue(cue);
      }
    }
    mediaTime += segment.duration;
  }
};
var MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
var syncPointStrategies = [
  // Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  //                the equivalence display-time 0 === segment-index 0
  {
    name: "VOD",
    run: function run(syncController, playlist, duration5, currentTimeline, currentTime) {
      if (duration5 !== Infinity) {
        var syncPoint = {
          time: 0,
          segmentIndex: 0,
          partIndex: null
        };
        return syncPoint;
      }
      return null;
    }
  },
  // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  {
    name: "ProgramDateTime",
    run: function run2(syncController, playlist, duration5, currentTimeline, currentTime) {
      if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
        return null;
      }
      var syncPoint = null;
      var lastDistance = null;
      var partsAndSegments = getPartsAndSegments(playlist);
      currentTime = currentTime || 0;
      for (var i = 0; i < partsAndSegments.length; i++) {
        var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
        var partAndSegment = partsAndSegments[index];
        var segment = partAndSegment.segment;
        var datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
        if (!datetimeMapping || !segment.dateTimeObject) {
          continue;
        }
        var segmentTime = segment.dateTimeObject.getTime() / 1e3;
        var start2 = segmentTime + datetimeMapping;
        if (segment.parts && typeof partAndSegment.partIndex === "number") {
          for (var z = 0; z < partAndSegment.partIndex; z++) {
            start2 += segment.parts[z].duration;
          }
        }
        var distance = Math.abs(currentTime - start2);
        if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
          break;
        }
        lastDistance = distance;
        syncPoint = {
          time: start2,
          segmentIndex: partAndSegment.segmentIndex,
          partIndex: partAndSegment.partIndex
        };
      }
      return syncPoint;
    }
  },
  // Stategy "Segment": We have a known time mapping for a timeline and a
  //                    segment in the current timeline with timing data
  {
    name: "Segment",
    run: function run3(syncController, playlist, duration5, currentTimeline, currentTime) {
      var syncPoint = null;
      var lastDistance = null;
      currentTime = currentTime || 0;
      var partsAndSegments = getPartsAndSegments(playlist);
      for (var i = 0; i < partsAndSegments.length; i++) {
        var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
        var partAndSegment = partsAndSegments[index];
        var segment = partAndSegment.segment;
        var start2 = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
        if (segment.timeline === currentTimeline && typeof start2 !== "undefined") {
          var distance = Math.abs(currentTime - start2);
          if (lastDistance !== null && lastDistance < distance) {
            break;
          }
          if (!syncPoint || lastDistance === null || lastDistance >= distance) {
            lastDistance = distance;
            syncPoint = {
              time: start2,
              segmentIndex: partAndSegment.segmentIndex,
              partIndex: partAndSegment.partIndex
            };
          }
        }
      }
      return syncPoint;
    }
  },
  // Stategy "Discontinuity": We have a discontinuity with a known
  //                          display-time
  {
    name: "Discontinuity",
    run: function run4(syncController, playlist, duration5, currentTimeline, currentTime) {
      var syncPoint = null;
      currentTime = currentTime || 0;
      if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
        var lastDistance = null;
        for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
          var segmentIndex = playlist.discontinuityStarts[i];
          var discontinuity = playlist.discontinuitySequence + i + 1;
          var discontinuitySync = syncController.discontinuities[discontinuity];
          if (discontinuitySync) {
            var distance = Math.abs(currentTime - discontinuitySync.time);
            if (lastDistance !== null && lastDistance < distance) {
              break;
            }
            if (!syncPoint || lastDistance === null || lastDistance >= distance) {
              lastDistance = distance;
              syncPoint = {
                time: discontinuitySync.time,
                segmentIndex,
                partIndex: null
              };
            }
          }
        }
      }
      return syncPoint;
    }
  },
  // Stategy "Playlist": We have a playlist with a known mapping of
  //                     segment index to display time
  {
    name: "Playlist",
    run: function run5(syncController, playlist, duration5, currentTimeline, currentTime) {
      if (playlist.syncInfo) {
        var syncPoint = {
          time: playlist.syncInfo.time,
          segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
          partIndex: null
        };
        return syncPoint;
      }
      return null;
    }
  }
];
var SyncController = /* @__PURE__ */ function(_videojs$EventTarget) {
  _inheritsLoose(SyncController2, _videojs$EventTarget);
  function SyncController2(options) {
    var _this;
    _this = _videojs$EventTarget.call(this) || this;
    _this.timelines = [];
    _this.discontinuities = [];
    _this.timelineToDatetimeMappings = {};
    _this.logger_ = logger2("SyncController");
    return _this;
  }
  var _proto = SyncController2.prototype;
  _proto.getSyncPoint = function getSyncPoint(playlist, duration5, currentTimeline, currentTime) {
    var syncPoints = this.runStrategies_(playlist, duration5, currentTimeline, currentTime);
    if (!syncPoints.length) {
      return null;
    }
    return this.selectSyncPoint_(syncPoints, {
      key: "time",
      value: currentTime
    });
  };
  _proto.getExpiredTime = function getExpiredTime(playlist, duration5) {
    if (!playlist || !playlist.segments) {
      return null;
    }
    var syncPoints = this.runStrategies_(playlist, duration5, playlist.discontinuitySequence, 0);
    if (!syncPoints.length) {
      return null;
    }
    var syncPoint = this.selectSyncPoint_(syncPoints, {
      key: "segmentIndex",
      value: 0
    });
    if (syncPoint.segmentIndex > 0) {
      syncPoint.time *= -1;
    }
    return Math.abs(syncPoint.time + sumDurations({
      defaultDuration: playlist.targetDuration,
      durationList: playlist.segments,
      startIndex: syncPoint.segmentIndex,
      endIndex: 0
    }));
  };
  _proto.runStrategies_ = function runStrategies_(playlist, duration5, currentTimeline, currentTime) {
    var syncPoints = [];
    for (var i = 0; i < syncPointStrategies.length; i++) {
      var strategy = syncPointStrategies[i];
      var syncPoint = strategy.run(this, playlist, duration5, currentTimeline, currentTime);
      if (syncPoint) {
        syncPoint.strategy = strategy.name;
        syncPoints.push({
          strategy: strategy.name,
          syncPoint
        });
      }
    }
    return syncPoints;
  };
  _proto.selectSyncPoint_ = function selectSyncPoint_(syncPoints, target) {
    var bestSyncPoint = syncPoints[0].syncPoint;
    var bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
    var bestStrategy = syncPoints[0].strategy;
    for (var i = 1; i < syncPoints.length; i++) {
      var newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
      if (newDistance < bestDistance) {
        bestDistance = newDistance;
        bestSyncPoint = syncPoints[i].syncPoint;
        bestStrategy = syncPoints[i].strategy;
      }
    }
    this.logger_("syncPoint for [" + target.key + ": " + target.value + "] chosen with strategy" + (" [" + bestStrategy + "]: [time:" + bestSyncPoint.time + ",") + (" segmentIndex:" + bestSyncPoint.segmentIndex) + (typeof bestSyncPoint.partIndex === "number" ? ",partIndex:" + bestSyncPoint.partIndex : "") + "]");
    return bestSyncPoint;
  };
  _proto.saveExpiredSegmentInfo = function saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
    var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
    if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
      videojs.log.warn("Not saving expired segment info. Media sequence gap " + mediaSequenceDiff + " is too large.");
      return;
    }
    for (var i = mediaSequenceDiff - 1; i >= 0; i--) {
      var lastRemovedSegment = oldPlaylist.segments[i];
      if (lastRemovedSegment && typeof lastRemovedSegment.start !== "undefined") {
        newPlaylist.syncInfo = {
          mediaSequence: oldPlaylist.mediaSequence + i,
          time: lastRemovedSegment.start
        };
        this.logger_("playlist refresh sync: [time:" + newPlaylist.syncInfo.time + "," + (" mediaSequence: " + newPlaylist.syncInfo.mediaSequence + "]"));
        this.trigger("syncinfoupdate");
        break;
      }
    }
  };
  _proto.setDateTimeMappingForStart = function setDateTimeMappingForStart(playlist) {
    this.timelineToDatetimeMappings = {};
    if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
      var firstSegment = playlist.segments[0];
      var playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1e3;
      this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
    }
  };
  _proto.saveSegmentTimingInfo = function saveSegmentTimingInfo(_ref) {
    var segmentInfo = _ref.segmentInfo, shouldSaveTimelineMapping = _ref.shouldSaveTimelineMapping;
    var didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
    var segment = segmentInfo.segment;
    if (didCalculateSegmentTimeMapping) {
      this.saveDiscontinuitySyncInfo_(segmentInfo);
      if (!segmentInfo.playlist.syncInfo) {
        segmentInfo.playlist.syncInfo = {
          mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
          time: segment.start
        };
      }
    }
    var dateTime = segment.dateTimeObject;
    if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
      this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1e3);
    }
  };
  _proto.timestampOffsetForTimeline = function timestampOffsetForTimeline(timeline) {
    if (typeof this.timelines[timeline] === "undefined") {
      return null;
    }
    return this.timelines[timeline].time;
  };
  _proto.mappingForTimeline = function mappingForTimeline(timeline) {
    if (typeof this.timelines[timeline] === "undefined") {
      return null;
    }
    return this.timelines[timeline].mapping;
  };
  _proto.calculateSegmentTimeMapping_ = function calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
    var segment = segmentInfo.segment;
    var part = segmentInfo.part;
    var mappingObj = this.timelines[segmentInfo.timeline];
    var start2;
    var end;
    if (typeof segmentInfo.timestampOffset === "number") {
      mappingObj = {
        time: segmentInfo.startOfSegment,
        mapping: segmentInfo.startOfSegment - timingInfo.start
      };
      if (shouldSaveTimelineMapping) {
        this.timelines[segmentInfo.timeline] = mappingObj;
        this.trigger("timestampoffset");
        this.logger_("time mapping for timeline " + segmentInfo.timeline + ": " + ("[time: " + mappingObj.time + "] [mapping: " + mappingObj.mapping + "]"));
      }
      start2 = segmentInfo.startOfSegment;
      end = timingInfo.end + mappingObj.mapping;
    } else if (mappingObj) {
      start2 = timingInfo.start + mappingObj.mapping;
      end = timingInfo.end + mappingObj.mapping;
    } else {
      return false;
    }
    if (part) {
      part.start = start2;
      part.end = end;
    }
    if (!segment.start || start2 < segment.start) {
      segment.start = start2;
    }
    segment.end = end;
    return true;
  };
  _proto.saveDiscontinuitySyncInfo_ = function saveDiscontinuitySyncInfo_(segmentInfo) {
    var playlist = segmentInfo.playlist;
    var segment = segmentInfo.segment;
    if (segment.discontinuity) {
      this.discontinuities[segment.timeline] = {
        time: segment.start,
        accuracy: 0
      };
    } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
      for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
        var segmentIndex = playlist.discontinuityStarts[i];
        var discontinuity = playlist.discontinuitySequence + i + 1;
        var mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
        var accuracy = Math.abs(mediaIndexDiff);
        if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
          var time = void 0;
          if (mediaIndexDiff < 0) {
            time = segment.start - sumDurations({
              defaultDuration: playlist.targetDuration,
              durationList: playlist.segments,
              startIndex: segmentInfo.mediaIndex,
              endIndex: segmentIndex
            });
          } else {
            time = segment.end + sumDurations({
              defaultDuration: playlist.targetDuration,
              durationList: playlist.segments,
              startIndex: segmentInfo.mediaIndex + 1,
              endIndex: segmentIndex
            });
          }
          this.discontinuities[discontinuity] = {
            time,
            accuracy
          };
        }
      }
    }
  };
  _proto.dispose = function dispose() {
    this.trigger("dispose");
    this.off();
  };
  return SyncController2;
}(videojs.EventTarget);
var TimelineChangeController = /* @__PURE__ */ function(_videojs$EventTarget) {
  _inheritsLoose(TimelineChangeController2, _videojs$EventTarget);
  function TimelineChangeController2() {
    var _this;
    _this = _videojs$EventTarget.call(this) || this;
    _this.pendingTimelineChanges_ = {};
    _this.lastTimelineChanges_ = {};
    return _this;
  }
  var _proto = TimelineChangeController2.prototype;
  _proto.clearPendingTimelineChange = function clearPendingTimelineChange(type2) {
    this.pendingTimelineChanges_[type2] = null;
    this.trigger("pendingtimelinechange");
  };
  _proto.pendingTimelineChange = function pendingTimelineChange(_ref) {
    var type2 = _ref.type, from3 = _ref.from, to = _ref.to;
    if (typeof from3 === "number" && typeof to === "number") {
      this.pendingTimelineChanges_[type2] = {
        type: type2,
        from: from3,
        to
      };
      this.trigger("pendingtimelinechange");
    }
    return this.pendingTimelineChanges_[type2];
  };
  _proto.lastTimelineChange = function lastTimelineChange(_ref2) {
    var type2 = _ref2.type, from3 = _ref2.from, to = _ref2.to;
    if (typeof from3 === "number" && typeof to === "number") {
      this.lastTimelineChanges_[type2] = {
        type: type2,
        from: from3,
        to
      };
      delete this.pendingTimelineChanges_[type2];
      this.trigger("timelinechange");
    }
    return this.lastTimelineChanges_[type2];
  };
  _proto.dispose = function dispose() {
    this.trigger("dispose");
    this.pendingTimelineChanges_ = {};
    this.lastTimelineChanges_ = {};
    this.off();
  };
  return TimelineChangeController2;
}(videojs.EventTarget);
var workerCode = transform(getWorkerString(function() {
  var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
  function createCommonjsModule(fn, basedir, module) {
    return module = {
      path: basedir,
      exports: {},
      require: function require2(path, base) {
        return commonjsRequire(path, base === void 0 || base === null ? module.path : base);
      }
    }, fn(module, module.exports), module.exports;
  }
  function commonjsRequire() {
    throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");
  }
  var createClass = createCommonjsModule(function(module) {
    function _defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
      }
    }
    function _createClass(Constructor, protoProps, staticProps) {
      if (protoProps) _defineProperties(Constructor.prototype, protoProps);
      if (staticProps) _defineProperties(Constructor, staticProps);
      return Constructor;
    }
    module.exports = _createClass;
    module.exports["default"] = module.exports, module.exports.__esModule = true;
  });
  var setPrototypeOf = createCommonjsModule(function(module) {
    function _setPrototypeOf2(o, p) {
      module.exports = _setPrototypeOf2 = Object.setPrototypeOf || function _setPrototypeOf3(o2, p2) {
        o2.__proto__ = p2;
        return o2;
      };
      module.exports["default"] = module.exports, module.exports.__esModule = true;
      return _setPrototypeOf2(o, p);
    }
    module.exports = _setPrototypeOf2;
    module.exports["default"] = module.exports, module.exports.__esModule = true;
  });
  var inheritsLoose = createCommonjsModule(function(module) {
    function _inheritsLoose4(subClass, superClass) {
      subClass.prototype = Object.create(superClass.prototype);
      subClass.prototype.constructor = subClass;
      setPrototypeOf(subClass, superClass);
    }
    module.exports = _inheritsLoose4;
    module.exports["default"] = module.exports, module.exports.__esModule = true;
  });
  var Stream2 = /* @__PURE__ */ function() {
    function Stream3() {
      this.listeners = {};
    }
    var _proto = Stream3.prototype;
    _proto.on = function on3(type2, listener) {
      if (!this.listeners[type2]) {
        this.listeners[type2] = [];
      }
      this.listeners[type2].push(listener);
    };
    _proto.off = function off2(type2, listener) {
      if (!this.listeners[type2]) {
        return false;
      }
      var index = this.listeners[type2].indexOf(listener);
      this.listeners[type2] = this.listeners[type2].slice(0);
      this.listeners[type2].splice(index, 1);
      return index > -1;
    };
    _proto.trigger = function trigger2(type2) {
      var callbacks = this.listeners[type2];
      if (!callbacks) {
        return;
      }
      if (arguments.length === 2) {
        var length = callbacks.length;
        for (var i = 0; i < length; ++i) {
          callbacks[i].call(this, arguments[1]);
        }
      } else {
        var args = Array.prototype.slice.call(arguments, 1);
        var _length = callbacks.length;
        for (var _i = 0; _i < _length; ++_i) {
          callbacks[_i].apply(this, args);
        }
      }
    };
    _proto.dispose = function dispose() {
      this.listeners = {};
    };
    _proto.pipe = function pipe(destination) {
      this.on("data", function(data) {
        destination.push(data);
      });
    };
    return Stream3;
  }();
  function unpad(padded) {
    return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  }
  var precompute = function precompute2() {
    var tables = [[[], [], [], [], []], [[], [], [], [], []]];
    var encTable = tables[0];
    var decTable = tables[1];
    var sbox = encTable[4];
    var sboxInv = decTable[4];
    var i;
    var x;
    var xInv;
    var d2 = [];
    var th = [];
    var x2;
    var x4;
    var x8;
    var s;
    var tEnc;
    var tDec;
    for (i = 0; i < 256; i++) {
      th[(d2[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
    }
    for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
      s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
      s = s >> 8 ^ s & 255 ^ 99;
      sbox[x] = s;
      sboxInv[s] = x;
      x8 = d2[x4 = d2[x2 = d2[x]]];
      tDec = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008;
      tEnc = d2[s] * 257 ^ s * 16843008;
      for (i = 0; i < 4; i++) {
        encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
        decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
      }
    }
    for (i = 0; i < 5; i++) {
      encTable[i] = encTable[i].slice(0);
      decTable[i] = decTable[i].slice(0);
    }
    return tables;
  };
  var aesTables = null;
  var AES = /* @__PURE__ */ function() {
    function AES2(key) {
      if (!aesTables) {
        aesTables = precompute();
      }
      this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
      var i;
      var j;
      var tmp;
      var sbox = this._tables[0][4];
      var decTable = this._tables[1];
      var keyLen = key.length;
      var rcon = 1;
      if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
        throw new Error("Invalid aes key size");
      }
      var encKey = key.slice(0);
      var decKey = [];
      this._key = [encKey, decKey];
      for (i = keyLen; i < 4 * keyLen + 28; i++) {
        tmp = encKey[i - 1];
        if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
          tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
          if (i % keyLen === 0) {
            tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
            rcon = rcon << 1 ^ (rcon >> 7) * 283;
          }
        }
        encKey[i] = encKey[i - keyLen] ^ tmp;
      }
      for (j = 0; i; j++, i--) {
        tmp = encKey[j & 3 ? i : i - 4];
        if (i <= 4 || j < 4) {
          decKey[j] = tmp;
        } else {
          decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
        }
      }
    }
    var _proto = AES2.prototype;
    _proto.decrypt = function decrypt4(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
      var key = this._key[1];
      var a = encrypted0 ^ key[0];
      var b = encrypted3 ^ key[1];
      var c = encrypted2 ^ key[2];
      var d2 = encrypted1 ^ key[3];
      var a2;
      var b2;
      var c2;
      var nInnerRounds = key.length / 4 - 2;
      var i;
      var kIndex = 4;
      var table = this._tables[1];
      var table0 = table[0];
      var table1 = table[1];
      var table2 = table[2];
      var table3 = table[3];
      var sbox = table[4];
      for (i = 0; i < nInnerRounds; i++) {
        a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d2 & 255] ^ key[kIndex];
        b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d2 >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
        c2 = table0[c >>> 24] ^ table1[d2 >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
        d2 = table0[d2 >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
        kIndex += 4;
        a = a2;
        b = b2;
        c = c2;
      }
      for (i = 0; i < 4; i++) {
        out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d2 & 255] ^ key[kIndex++];
        a2 = a;
        a = b;
        b = c;
        c = d2;
        d2 = a2;
      }
    };
    return AES2;
  }();
  var AsyncStream = /* @__PURE__ */ function(_Stream) {
    inheritsLoose(AsyncStream2, _Stream);
    function AsyncStream2() {
      var _this;
      _this = _Stream.call(this, Stream2) || this;
      _this.jobs = [];
      _this.delay = 1;
      _this.timeout_ = null;
      return _this;
    }
    var _proto = AsyncStream2.prototype;
    _proto.processJob_ = function processJob_() {
      this.jobs.shift()();
      if (this.jobs.length) {
        this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
      } else {
        this.timeout_ = null;
      }
    };
    _proto.push = function push2(job) {
      this.jobs.push(job);
      if (!this.timeout_) {
        this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
      }
    };
    return AsyncStream2;
  }(Stream2);
  var ntoh = function ntoh2(word) {
    return word << 24 | (word & 65280) << 8 | (word & 16711680) >> 8 | word >>> 24;
  };
  var decrypt3 = function decrypt4(encrypted, key, initVector) {
    var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
    var decipher = new AES(Array.prototype.slice.call(key));
    var decrypted = new Uint8Array(encrypted.byteLength);
    var decrypted32 = new Int32Array(decrypted.buffer);
    var init0;
    var init1;
    var init2;
    var init3;
    var encrypted0;
    var encrypted1;
    var encrypted2;
    var encrypted3;
    var wordIx;
    init0 = initVector[0];
    init1 = initVector[1];
    init2 = initVector[2];
    init3 = initVector[3];
    for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
      encrypted0 = ntoh(encrypted32[wordIx]);
      encrypted1 = ntoh(encrypted32[wordIx + 1]);
      encrypted2 = ntoh(encrypted32[wordIx + 2]);
      encrypted3 = ntoh(encrypted32[wordIx + 3]);
      decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx);
      decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
      decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
      decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
      decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3);
      init0 = encrypted0;
      init1 = encrypted1;
      init2 = encrypted2;
      init3 = encrypted3;
    }
    return decrypted;
  };
  var Decrypter3 = /* @__PURE__ */ function() {
    function Decrypter4(encrypted, key, initVector, done) {
      var step = Decrypter4.STEP;
      var encrypted32 = new Int32Array(encrypted.buffer);
      var decrypted = new Uint8Array(encrypted.byteLength);
      var i = 0;
      this.asyncStream_ = new AsyncStream();
      this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
      for (i = step; i < encrypted32.length; i += step) {
        initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
        this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
      }
      this.asyncStream_.push(function() {
        done(null, unpad(decrypted));
      });
    }
    var _proto = Decrypter4.prototype;
    _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
      return function() {
        var bytes = decrypt3(encrypted, key, initVector);
        decrypted.set(bytes, encrypted.byteOffset);
      };
    };
    createClass(Decrypter4, null, [{
      key: "STEP",
      get: function get7() {
        return 32e3;
      }
    }]);
    return Decrypter4;
  }();
  var win;
  if (typeof window !== "undefined") {
    win = window;
  } else if (typeof commonjsGlobal !== "undefined") {
    win = commonjsGlobal;
  } else if (typeof self !== "undefined") {
    win = self;
  } else {
    win = {};
  }
  var window_1 = win;
  var isArrayBufferView4 = function isArrayBufferView5(obj) {
    if (ArrayBuffer.isView === "function") {
      return ArrayBuffer.isView(obj);
    }
    return obj && obj.buffer instanceof ArrayBuffer;
  };
  var BigInt3 = window_1.BigInt || Number;
  [BigInt3("0x1"), BigInt3("0x100"), BigInt3("0x10000"), BigInt3("0x1000000"), BigInt3("0x100000000"), BigInt3("0x10000000000"), BigInt3("0x1000000000000"), BigInt3("0x100000000000000"), BigInt3("0x10000000000000000")];
  var createTransferableMessage3 = function createTransferableMessage4(message) {
    var transferable = {};
    Object.keys(message).forEach(function(key) {
      var value = message[key];
      if (isArrayBufferView4(value)) {
        transferable[key] = {
          bytes: value.buffer,
          byteOffset: value.byteOffset,
          byteLength: value.byteLength
        };
      } else {
        transferable[key] = value;
      }
    });
    return transferable;
  };
  self.onmessage = function(event) {
    var data = event.data;
    var encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
    var key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
    var iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
    new Decrypter3(encrypted, key, iv, function(err, bytes) {
      self.postMessage(createTransferableMessage3({
        source: data.source,
        decrypted: bytes
      }), [bytes.buffer]);
    });
  };
}));
var Decrypter2 = factory(workerCode);
var audioTrackKind_ = function audioTrackKind_2(properties) {
  var kind = properties["default"] ? "main" : "alternative";
  if (properties.characteristics && properties.characteristics.indexOf("public.accessibility.describes-video") >= 0) {
    kind = "main-desc";
  }
  return kind;
};
var stopLoaders = function stopLoaders2(segmentLoader, mediaType) {
  segmentLoader.abort();
  segmentLoader.pause();
  if (mediaType && mediaType.activePlaylistLoader) {
    mediaType.activePlaylistLoader.pause();
    mediaType.activePlaylistLoader = null;
  }
};
var startLoaders = function startLoaders2(playlistLoader, mediaType) {
  mediaType.activePlaylistLoader = playlistLoader;
  playlistLoader.load();
};
var onGroupChanged = function onGroupChanged2(type2, settings) {
  return function() {
    var _settings$segmentLoad = settings.segmentLoaders, segmentLoader = _settings$segmentLoad[type2], mainSegmentLoader = _settings$segmentLoad.main, mediaType = settings.mediaTypes[type2];
    var activeTrack2 = mediaType.activeTrack();
    var activeGroup3 = mediaType.getActiveGroup();
    var previousActiveLoader = mediaType.activePlaylistLoader;
    var lastGroup = mediaType.lastGroup_;
    if (activeGroup3 && lastGroup && activeGroup3.id === lastGroup.id) {
      return;
    }
    mediaType.lastGroup_ = activeGroup3;
    mediaType.lastTrack_ = activeTrack2;
    stopLoaders(segmentLoader, mediaType);
    if (!activeGroup3 || activeGroup3.isMasterPlaylist) {
      return;
    }
    if (!activeGroup3.playlistLoader) {
      if (previousActiveLoader) {
        mainSegmentLoader.resetEverything();
      }
      return;
    }
    segmentLoader.resyncLoader();
    startLoaders(activeGroup3.playlistLoader, mediaType);
  };
};
var onGroupChanging = function onGroupChanging2(type2, settings) {
  return function() {
    var segmentLoader = settings.segmentLoaders[type2], mediaType = settings.mediaTypes[type2];
    mediaType.lastGroup_ = null;
    segmentLoader.abort();
    segmentLoader.pause();
  };
};
var onTrackChanged = function onTrackChanged2(type2, settings) {
  return function() {
    var masterPlaylistLoader = settings.masterPlaylistLoader, _settings$segmentLoad2 = settings.segmentLoaders, segmentLoader = _settings$segmentLoad2[type2], mainSegmentLoader = _settings$segmentLoad2.main, mediaType = settings.mediaTypes[type2];
    var activeTrack2 = mediaType.activeTrack();
    var activeGroup3 = mediaType.getActiveGroup();
    var previousActiveLoader = mediaType.activePlaylistLoader;
    var lastTrack = mediaType.lastTrack_;
    if (lastTrack && activeTrack2 && lastTrack.id === activeTrack2.id) {
      return;
    }
    mediaType.lastGroup_ = activeGroup3;
    mediaType.lastTrack_ = activeTrack2;
    stopLoaders(segmentLoader, mediaType);
    if (!activeGroup3) {
      return;
    }
    if (activeGroup3.isMasterPlaylist) {
      if (!activeTrack2 || !lastTrack || activeTrack2.id === lastTrack.id) {
        return;
      }
      var mpc = settings.vhs.masterPlaylistController_;
      var newPlaylist = mpc.selectPlaylist();
      if (mpc.media() === newPlaylist) {
        return;
      }
      mediaType.logger_("track change. Switching master audio from " + lastTrack.id + " to " + activeTrack2.id);
      masterPlaylistLoader.pause();
      mainSegmentLoader.resetEverything();
      mpc.fastQualityChange_(newPlaylist);
      return;
    }
    if (type2 === "AUDIO") {
      if (!activeGroup3.playlistLoader) {
        mainSegmentLoader.setAudio(true);
        mainSegmentLoader.resetEverything();
        return;
      }
      segmentLoader.setAudio(true);
      mainSegmentLoader.setAudio(false);
    }
    if (previousActiveLoader === activeGroup3.playlistLoader) {
      startLoaders(activeGroup3.playlistLoader, mediaType);
      return;
    }
    if (segmentLoader.track) {
      segmentLoader.track(activeTrack2);
    }
    segmentLoader.resetEverything();
    startLoaders(activeGroup3.playlistLoader, mediaType);
  };
};
var onError = {
  /**
   * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
   * an error.
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @return {Function}
   *         Error handler. Logs warning (or error if the playlist is blacklisted) to
   *         console and switches back to default audio track.
   * @function onError.AUDIO
   */
  AUDIO: function AUDIO(type2, settings) {
    return function() {
      var segmentLoader = settings.segmentLoaders[type2], mediaType = settings.mediaTypes[type2], blacklistCurrentPlaylist = settings.blacklistCurrentPlaylist;
      stopLoaders(segmentLoader, mediaType);
      var activeTrack2 = mediaType.activeTrack();
      var activeGroup3 = mediaType.activeGroup();
      var id = (activeGroup3.filter(function(group) {
        return group["default"];
      })[0] || activeGroup3[0]).id;
      var defaultTrack = mediaType.tracks[id];
      if (activeTrack2 === defaultTrack) {
        blacklistCurrentPlaylist({
          message: "Problem encountered loading the default audio track."
        });
        return;
      }
      videojs.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");
      for (var trackId in mediaType.tracks) {
        mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
      }
      mediaType.onTrackChanged();
    };
  },
  /**
   * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
   * an error.
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @return {Function}
   *         Error handler. Logs warning to console and disables the active subtitle track
   * @function onError.SUBTITLES
   */
  SUBTITLES: function SUBTITLES(type2, settings) {
    return function() {
      var segmentLoader = settings.segmentLoaders[type2], mediaType = settings.mediaTypes[type2];
      videojs.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");
      stopLoaders(segmentLoader, mediaType);
      var track = mediaType.activeTrack();
      if (track) {
        track.mode = "disabled";
      }
      mediaType.onTrackChanged();
    };
  }
};
var setupListeners = {
  /**
   * Setup event listeners for audio playlist loader
   *
   * @param {string} type
   *        MediaGroup type
   * @param {PlaylistLoader|null} playlistLoader
   *        PlaylistLoader to register listeners on
   * @param {Object} settings
   *        Object containing required information for media groups
   * @function setupListeners.AUDIO
   */
  AUDIO: function AUDIO2(type2, playlistLoader, settings) {
    if (!playlistLoader) {
      return;
    }
    var tech = settings.tech, requestOptions = settings.requestOptions, segmentLoader = settings.segmentLoaders[type2];
    playlistLoader.on("loadedmetadata", function() {
      var media = playlistLoader.media();
      segmentLoader.playlist(media, requestOptions);
      if (!tech.paused() || media.endList && tech.preload() !== "none") {
        segmentLoader.load();
      }
    });
    playlistLoader.on("loadedplaylist", function() {
      segmentLoader.playlist(playlistLoader.media(), requestOptions);
      if (!tech.paused()) {
        segmentLoader.load();
      }
    });
    playlistLoader.on("error", onError[type2](type2, settings));
  },
  /**
   * Setup event listeners for subtitle playlist loader
   *
   * @param {string} type
   *        MediaGroup type
   * @param {PlaylistLoader|null} playlistLoader
   *        PlaylistLoader to register listeners on
   * @param {Object} settings
   *        Object containing required information for media groups
   * @function setupListeners.SUBTITLES
   */
  SUBTITLES: function SUBTITLES2(type2, playlistLoader, settings) {
    var tech = settings.tech, requestOptions = settings.requestOptions, segmentLoader = settings.segmentLoaders[type2], mediaType = settings.mediaTypes[type2];
    playlistLoader.on("loadedmetadata", function() {
      var media = playlistLoader.media();
      segmentLoader.playlist(media, requestOptions);
      segmentLoader.track(mediaType.activeTrack());
      if (!tech.paused() || media.endList && tech.preload() !== "none") {
        segmentLoader.load();
      }
    });
    playlistLoader.on("loadedplaylist", function() {
      segmentLoader.playlist(playlistLoader.media(), requestOptions);
      if (!tech.paused()) {
        segmentLoader.load();
      }
    });
    playlistLoader.on("error", onError[type2](type2, settings));
  }
};
var initialize = {
  /**
   * Setup PlaylistLoaders and AudioTracks for the audio groups
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @function initialize.AUDIO
   */
  "AUDIO": function AUDIO3(type2, settings) {
    var vhs = settings.vhs, sourceType = settings.sourceType, segmentLoader = settings.segmentLoaders[type2], requestOptions = settings.requestOptions, mediaGroups = settings.master.mediaGroups, _settings$mediaTypes$ = settings.mediaTypes[type2], groups = _settings$mediaTypes$.groups, tracks = _settings$mediaTypes$.tracks, logger_ = _settings$mediaTypes$.logger_, masterPlaylistLoader = settings.masterPlaylistLoader;
    var audioOnlyMaster = isAudioOnly(masterPlaylistLoader.master);
    if (!mediaGroups[type2] || Object.keys(mediaGroups[type2]).length === 0) {
      mediaGroups[type2] = {
        main: {
          "default": {
            "default": true
          }
        }
      };
      if (audioOnlyMaster) {
        mediaGroups[type2].main["default"].playlists = masterPlaylistLoader.master.playlists;
      }
    }
    for (var groupId in mediaGroups[type2]) {
      if (!groups[groupId]) {
        groups[groupId] = [];
      }
      for (var variantLabel in mediaGroups[type2][groupId]) {
        var properties = mediaGroups[type2][groupId][variantLabel];
        var playlistLoader = void 0;
        if (audioOnlyMaster) {
          logger_("AUDIO group '" + groupId + "' label '" + variantLabel + "' is a master playlist");
          properties.isMasterPlaylist = true;
          playlistLoader = null;
        } else if (sourceType === "vhs-json" && properties.playlists) {
          playlistLoader = new PlaylistLoader2(properties.playlists[0], vhs, requestOptions);
        } else if (properties.resolvedUri) {
          playlistLoader = new PlaylistLoader2(properties.resolvedUri, vhs, requestOptions);
        } else if (properties.playlists && sourceType === "dash") {
          playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
        } else {
          playlistLoader = null;
        }
        properties = videojs.mergeOptions({
          id: variantLabel,
          playlistLoader
        }, properties);
        setupListeners[type2](type2, properties.playlistLoader, settings);
        groups[groupId].push(properties);
        if (typeof tracks[variantLabel] === "undefined") {
          var track = new videojs.AudioTrack({
            id: variantLabel,
            kind: audioTrackKind_(properties),
            enabled: false,
            language: properties.language,
            "default": properties["default"],
            label: variantLabel
          });
          tracks[variantLabel] = track;
        }
      }
    }
    segmentLoader.on("error", onError[type2](type2, settings));
  },
  /**
   * Setup PlaylistLoaders and TextTracks for the subtitle groups
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @function initialize.SUBTITLES
   */
  "SUBTITLES": function SUBTITLES3(type2, settings) {
    var tech = settings.tech, vhs = settings.vhs, sourceType = settings.sourceType, segmentLoader = settings.segmentLoaders[type2], requestOptions = settings.requestOptions, mediaGroups = settings.master.mediaGroups, _settings$mediaTypes$2 = settings.mediaTypes[type2], groups = _settings$mediaTypes$2.groups, tracks = _settings$mediaTypes$2.tracks, masterPlaylistLoader = settings.masterPlaylistLoader;
    for (var groupId in mediaGroups[type2]) {
      if (!groups[groupId]) {
        groups[groupId] = [];
      }
      for (var variantLabel in mediaGroups[type2][groupId]) {
        if (mediaGroups[type2][groupId][variantLabel].forced) {
          continue;
        }
        var properties = mediaGroups[type2][groupId][variantLabel];
        var playlistLoader = void 0;
        if (sourceType === "hls") {
          playlistLoader = new PlaylistLoader2(properties.resolvedUri, vhs, requestOptions);
        } else if (sourceType === "dash") {
          var playlists = properties.playlists.filter(function(p) {
            return p.excludeUntil !== Infinity;
          });
          if (!playlists.length) {
            return;
          }
          playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
        } else if (sourceType === "vhs-json") {
          playlistLoader = new PlaylistLoader2(
            // if the vhs-json object included the media playlist, use the media playlist
            // as provided, otherwise use the resolved URI to load the playlist
            properties.playlists ? properties.playlists[0] : properties.resolvedUri,
            vhs,
            requestOptions
          );
        }
        properties = videojs.mergeOptions({
          id: variantLabel,
          playlistLoader
        }, properties);
        setupListeners[type2](type2, properties.playlistLoader, settings);
        groups[groupId].push(properties);
        if (typeof tracks[variantLabel] === "undefined") {
          var track = tech.addRemoteTextTrack({
            id: variantLabel,
            kind: "subtitles",
            "default": properties["default"] && properties.autoselect,
            language: properties.language,
            label: variantLabel
          }, false).track;
          tracks[variantLabel] = track;
        }
      }
    }
    segmentLoader.on("error", onError[type2](type2, settings));
  },
  /**
   * Setup TextTracks for the closed-caption groups
   *
   * @param {String} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @function initialize['CLOSED-CAPTIONS']
   */
  "CLOSED-CAPTIONS": function CLOSEDCAPTIONS(type2, settings) {
    var tech = settings.tech, mediaGroups = settings.master.mediaGroups, _settings$mediaTypes$3 = settings.mediaTypes[type2], groups = _settings$mediaTypes$3.groups, tracks = _settings$mediaTypes$3.tracks;
    for (var groupId in mediaGroups[type2]) {
      if (!groups[groupId]) {
        groups[groupId] = [];
      }
      for (var variantLabel in mediaGroups[type2][groupId]) {
        var properties = mediaGroups[type2][groupId][variantLabel];
        if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
          continue;
        }
        var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
        var newProps = {
          label: variantLabel,
          language: properties.language,
          instreamId: properties.instreamId,
          "default": properties["default"] && properties.autoselect
        };
        if (captionServices[newProps.instreamId]) {
          newProps = videojs.mergeOptions(newProps, captionServices[newProps.instreamId]);
        }
        if (newProps["default"] === void 0) {
          delete newProps["default"];
        }
        groups[groupId].push(videojs.mergeOptions({
          id: variantLabel
        }, properties));
        if (typeof tracks[variantLabel] === "undefined") {
          var track = tech.addRemoteTextTrack({
            id: newProps.instreamId,
            kind: "captions",
            "default": newProps["default"],
            language: newProps.language,
            label: newProps.label
          }, false).track;
          tracks[variantLabel] = track;
        }
      }
    }
  }
};
var groupMatch = function groupMatch2(list, media) {
  for (var i = 0; i < list.length; i++) {
    if (playlistMatch(media, list[i])) {
      return true;
    }
    if (list[i].playlists && groupMatch2(list[i].playlists, media)) {
      return true;
    }
  }
  return false;
};
var activeGroup = function activeGroup2(type2, settings) {
  return function(track) {
    var masterPlaylistLoader = settings.masterPlaylistLoader, groups = settings.mediaTypes[type2].groups;
    var media = masterPlaylistLoader.media();
    if (!media) {
      return null;
    }
    var variants = null;
    if (media.attributes[type2]) {
      variants = groups[media.attributes[type2]];
    }
    var groupKeys = Object.keys(groups);
    if (!variants) {
      if (type2 === "AUDIO" && groupKeys.length > 1 && isAudioOnly(settings.master)) {
        for (var i = 0; i < groupKeys.length; i++) {
          var groupPropertyList = groups[groupKeys[i]];
          if (groupMatch(groupPropertyList, media)) {
            variants = groupPropertyList;
            break;
          }
        }
      } else if (groups.main) {
        variants = groups.main;
      } else if (groupKeys.length === 1) {
        variants = groups[groupKeys[0]];
      }
    }
    if (typeof track === "undefined") {
      return variants;
    }
    if (track === null || !variants) {
      return null;
    }
    return variants.filter(function(props) {
      return props.id === track.id;
    })[0] || null;
  };
};
var activeTrack = {
  /**
   * Returns a function used to get the active track of type provided
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @return {Function}
   *         Function that returns the active media track for the provided type. Returns
   *         null if no track is active
   * @function activeTrack.AUDIO
   */
  AUDIO: function AUDIO4(type2, settings) {
    return function() {
      var tracks = settings.mediaTypes[type2].tracks;
      for (var id in tracks) {
        if (tracks[id].enabled) {
          return tracks[id];
        }
      }
      return null;
    };
  },
  /**
   * Returns a function used to get the active track of type provided
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @return {Function}
   *         Function that returns the active media track for the provided type. Returns
   *         null if no track is active
   * @function activeTrack.SUBTITLES
   */
  SUBTITLES: function SUBTITLES4(type2, settings) {
    return function() {
      var tracks = settings.mediaTypes[type2].tracks;
      for (var id in tracks) {
        if (tracks[id].mode === "showing" || tracks[id].mode === "hidden") {
          return tracks[id];
        }
      }
      return null;
    };
  }
};
var getActiveGroup = function getActiveGroup2(type2, _ref) {
  var mediaTypes2 = _ref.mediaTypes;
  return function() {
    var activeTrack_ = mediaTypes2[type2].activeTrack();
    if (!activeTrack_) {
      return null;
    }
    return mediaTypes2[type2].activeGroup(activeTrack_);
  };
};
var setupMediaGroups = function setupMediaGroups2(settings) {
  ["AUDIO", "SUBTITLES", "CLOSED-CAPTIONS"].forEach(function(type2) {
    initialize[type2](type2, settings);
  });
  var mediaTypes2 = settings.mediaTypes, masterPlaylistLoader = settings.masterPlaylistLoader, tech = settings.tech, vhs = settings.vhs, _settings$segmentLoad3 = settings.segmentLoaders, audioSegmentLoader = _settings$segmentLoad3["AUDIO"], mainSegmentLoader = _settings$segmentLoad3.main;
  ["AUDIO", "SUBTITLES"].forEach(function(type2) {
    mediaTypes2[type2].activeGroup = activeGroup(type2, settings);
    mediaTypes2[type2].activeTrack = activeTrack[type2](type2, settings);
    mediaTypes2[type2].onGroupChanged = onGroupChanged(type2, settings);
    mediaTypes2[type2].onGroupChanging = onGroupChanging(type2, settings);
    mediaTypes2[type2].onTrackChanged = onTrackChanged(type2, settings);
    mediaTypes2[type2].getActiveGroup = getActiveGroup(type2, settings);
  });
  var audioGroup = mediaTypes2.AUDIO.activeGroup();
  if (audioGroup) {
    var groupId = (audioGroup.filter(function(group) {
      return group["default"];
    })[0] || audioGroup[0]).id;
    mediaTypes2.AUDIO.tracks[groupId].enabled = true;
    mediaTypes2.AUDIO.onGroupChanged();
    mediaTypes2.AUDIO.onTrackChanged();
    var activeAudioGroup = mediaTypes2.AUDIO.getActiveGroup();
    if (!activeAudioGroup.playlistLoader) {
      mainSegmentLoader.setAudio(true);
    } else {
      mainSegmentLoader.setAudio(false);
      audioSegmentLoader.setAudio(true);
    }
  }
  masterPlaylistLoader.on("mediachange", function() {
    ["AUDIO", "SUBTITLES"].forEach(function(type2) {
      return mediaTypes2[type2].onGroupChanged();
    });
  });
  masterPlaylistLoader.on("mediachanging", function() {
    ["AUDIO", "SUBTITLES"].forEach(function(type2) {
      return mediaTypes2[type2].onGroupChanging();
    });
  });
  var onAudioTrackChanged = function onAudioTrackChanged2() {
    mediaTypes2.AUDIO.onTrackChanged();
    tech.trigger({
      type: "usage",
      name: "vhs-audio-change"
    });
    tech.trigger({
      type: "usage",
      name: "hls-audio-change"
    });
  };
  tech.audioTracks().addEventListener("change", onAudioTrackChanged);
  tech.remoteTextTracks().addEventListener("change", mediaTypes2.SUBTITLES.onTrackChanged);
  vhs.on("dispose", function() {
    tech.audioTracks().removeEventListener("change", onAudioTrackChanged);
    tech.remoteTextTracks().removeEventListener("change", mediaTypes2.SUBTITLES.onTrackChanged);
  });
  tech.clearTracks("audio");
  for (var id in mediaTypes2.AUDIO.tracks) {
    tech.audioTracks().addTrack(mediaTypes2.AUDIO.tracks[id]);
  }
};
var createMediaTypes = function createMediaTypes2() {
  var mediaTypes2 = {};
  ["AUDIO", "SUBTITLES", "CLOSED-CAPTIONS"].forEach(function(type2) {
    mediaTypes2[type2] = {
      groups: {},
      tracks: {},
      activePlaylistLoader: null,
      activeGroup: noop3,
      activeTrack: noop3,
      getActiveGroup: noop3,
      onGroupChanged: noop3,
      onTrackChanged: noop3,
      lastTrack_: null,
      logger_: logger2("MediaGroups[" + type2 + "]")
    };
  });
  return mediaTypes2;
};
var ABORT_EARLY_BLACKLIST_SECONDS = 60 * 2;
var Vhs$1;
var loaderStats = ["mediaRequests", "mediaRequestsAborted", "mediaRequestsTimedout", "mediaRequestsErrored", "mediaTransferDuration", "mediaBytesTransferred", "mediaAppends"];
var sumLoaderStat = function sumLoaderStat2(stat) {
  return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
};
var shouldSwitchToMedia = function shouldSwitchToMedia2(_ref) {
  var currentPlaylist = _ref.currentPlaylist, buffered = _ref.buffered, currentTime = _ref.currentTime, nextPlaylist = _ref.nextPlaylist, bufferLowWaterLine = _ref.bufferLowWaterLine, bufferHighWaterLine = _ref.bufferHighWaterLine, duration5 = _ref.duration, experimentalBufferBasedABR = _ref.experimentalBufferBasedABR, log2 = _ref.log;
  if (!nextPlaylist) {
    videojs.log.warn("We received no playlist to switch to. Please check your stream.");
    return false;
  }
  var sharedLogLine = "allowing switch " + (currentPlaylist && currentPlaylist.id || "null") + " -> " + nextPlaylist.id;
  if (!currentPlaylist) {
    log2(sharedLogLine + " as current playlist is not set");
    return true;
  }
  if (nextPlaylist.id === currentPlaylist.id) {
    return false;
  }
  var isBuffered = Boolean(findRange(buffered, currentTime).length);
  if (!currentPlaylist.endList) {
    if (!isBuffered && typeof currentPlaylist.partTargetDuration === "number") {
      log2("not " + sharedLogLine + " as current playlist is live llhls, but currentTime isn't in buffered.");
      return false;
    }
    log2(sharedLogLine + " as current playlist is live");
    return true;
  }
  var forwardBuffer = timeAheadOf(buffered, currentTime);
  var maxBufferLowWaterLine = experimentalBufferBasedABR ? Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE : Config.MAX_BUFFER_LOW_WATER_LINE;
  if (duration5 < maxBufferLowWaterLine) {
    log2(sharedLogLine + " as duration < max low water line (" + duration5 + " < " + maxBufferLowWaterLine + ")");
    return true;
  }
  var nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  var currBandwidth = currentPlaylist.attributes.BANDWIDTH;
  if (nextBandwidth < currBandwidth && (!experimentalBufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
    var logLine = sharedLogLine + " as next bandwidth < current bandwidth (" + nextBandwidth + " < " + currBandwidth + ")";
    if (experimentalBufferBasedABR) {
      logLine += " and forwardBuffer < bufferHighWaterLine (" + forwardBuffer + " < " + bufferHighWaterLine + ")";
    }
    log2(logLine);
    return true;
  }
  if ((!experimentalBufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
    var _logLine = sharedLogLine + " as forwardBuffer >= bufferLowWaterLine (" + forwardBuffer + " >= " + bufferLowWaterLine + ")";
    if (experimentalBufferBasedABR) {
      _logLine += " and next bandwidth > current bandwidth (" + nextBandwidth + " > " + currBandwidth + ")";
    }
    log2(_logLine);
    return true;
  }
  log2("not " + sharedLogLine + " as no switching criteria met");
  return false;
};
var MasterPlaylistController = /* @__PURE__ */ function(_videojs$EventTarget) {
  _inheritsLoose(MasterPlaylistController2, _videojs$EventTarget);
  function MasterPlaylistController2(options) {
    var _this;
    _this = _videojs$EventTarget.call(this) || this;
    var src = options.src, handleManifestRedirects = options.handleManifestRedirects, withCredentials = options.withCredentials, tech = options.tech, bandwidth2 = options.bandwidth, externVhs = options.externVhs, useCueTags = options.useCueTags, blacklistDuration = options.blacklistDuration, enableLowInitialPlaylist = options.enableLowInitialPlaylist, sourceType = options.sourceType, cacheEncryptionKeys = options.cacheEncryptionKeys, experimentalBufferBasedABR = options.experimentalBufferBasedABR, experimentalLeastPixelDiffSelector = options.experimentalLeastPixelDiffSelector, captionServices = options.captionServices;
    if (!src) {
      throw new Error("A non-empty playlist URL or JSON manifest string is required");
    }
    var maxPlaylistRetries = options.maxPlaylistRetries;
    if (maxPlaylistRetries === null || typeof maxPlaylistRetries === "undefined") {
      maxPlaylistRetries = Infinity;
    }
    Vhs$1 = externVhs;
    _this.experimentalBufferBasedABR = Boolean(experimentalBufferBasedABR);
    _this.experimentalLeastPixelDiffSelector = Boolean(experimentalLeastPixelDiffSelector);
    _this.withCredentials = withCredentials;
    _this.tech_ = tech;
    _this.vhs_ = tech.vhs;
    _this.sourceType_ = sourceType;
    _this.useCueTags_ = useCueTags;
    _this.blacklistDuration = blacklistDuration;
    _this.maxPlaylistRetries = maxPlaylistRetries;
    _this.enableLowInitialPlaylist = enableLowInitialPlaylist;
    if (_this.useCueTags_) {
      _this.cueTagsTrack_ = _this.tech_.addTextTrack("metadata", "ad-cues");
      _this.cueTagsTrack_.inBandMetadataTrackDispatchType = "";
    }
    _this.requestOptions_ = {
      withCredentials,
      handleManifestRedirects,
      maxPlaylistRetries,
      timeout: null
    };
    _this.on("error", _this.pauseLoading);
    _this.mediaTypes_ = createMediaTypes();
    _this.mediaSource = new import_window6.default.MediaSource();
    _this.handleDurationChange_ = _this.handleDurationChange_.bind(_assertThisInitialized(_this));
    _this.handleSourceOpen_ = _this.handleSourceOpen_.bind(_assertThisInitialized(_this));
    _this.handleSourceEnded_ = _this.handleSourceEnded_.bind(_assertThisInitialized(_this));
    _this.mediaSource.addEventListener("durationchange", _this.handleDurationChange_);
    _this.mediaSource.addEventListener("sourceopen", _this.handleSourceOpen_);
    _this.mediaSource.addEventListener("sourceended", _this.handleSourceEnded_);
    _this.seekable_ = videojs.createTimeRanges();
    _this.hasPlayed_ = false;
    _this.syncController_ = new SyncController(options);
    _this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
      kind: "metadata",
      label: "segment-metadata"
    }, false).track;
    _this.decrypter_ = new Decrypter2();
    _this.sourceUpdater_ = new SourceUpdater(_this.mediaSource);
    _this.inbandTextTracks_ = {};
    _this.timelineChangeController_ = new TimelineChangeController();
    var segmentLoaderSettings = {
      vhs: _this.vhs_,
      parse708captions: options.parse708captions,
      useDtsForTimestampOffset: options.useDtsForTimestampOffset,
      captionServices,
      mediaSource: _this.mediaSource,
      currentTime: _this.tech_.currentTime.bind(_this.tech_),
      seekable: function seekable3() {
        return _this.seekable();
      },
      seeking: function seeking() {
        return _this.tech_.seeking();
      },
      duration: function duration5() {
        return _this.duration();
      },
      hasPlayed: function hasPlayed() {
        return _this.hasPlayed_;
      },
      goalBufferLength: function goalBufferLength() {
        return _this.goalBufferLength();
      },
      bandwidth: bandwidth2,
      syncController: _this.syncController_,
      decrypter: _this.decrypter_,
      sourceType: _this.sourceType_,
      inbandTextTracks: _this.inbandTextTracks_,
      cacheEncryptionKeys,
      sourceUpdater: _this.sourceUpdater_,
      timelineChangeController: _this.timelineChangeController_,
      experimentalExactManifestTimings: options.experimentalExactManifestTimings
    };
    _this.masterPlaylistLoader_ = _this.sourceType_ === "dash" ? new DashPlaylistLoader(src, _this.vhs_, _this.requestOptions_) : new PlaylistLoader2(src, _this.vhs_, _this.requestOptions_);
    _this.setupMasterPlaylistLoaderListeners_();
    _this.mainSegmentLoader_ = new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
      segmentMetadataTrack: _this.segmentMetadataTrack_,
      loaderType: "main"
    }), options);
    _this.audioSegmentLoader_ = new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
      loaderType: "audio"
    }), options);
    _this.subtitleSegmentLoader_ = new VTTSegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
      loaderType: "vtt",
      featuresNativeTextTracks: _this.tech_.featuresNativeTextTracks
    }), options);
    _this.setupSegmentLoaderListeners_();
    if (_this.experimentalBufferBasedABR) {
      _this.masterPlaylistLoader_.one("loadedplaylist", function() {
        return _this.startABRTimer_();
      });
      _this.tech_.on("pause", function() {
        return _this.stopABRTimer_();
      });
      _this.tech_.on("play", function() {
        return _this.startABRTimer_();
      });
    }
    loaderStats.forEach(function(stat) {
      _this[stat + "_"] = sumLoaderStat.bind(_assertThisInitialized(_this), stat);
    });
    _this.logger_ = logger2("MPC");
    _this.triggeredFmp4Usage = false;
    if (_this.tech_.preload() === "none") {
      _this.loadOnPlay_ = function() {
        _this.loadOnPlay_ = null;
        _this.masterPlaylistLoader_.load();
      };
      _this.tech_.one("play", _this.loadOnPlay_);
    } else {
      _this.masterPlaylistLoader_.load();
    }
    _this.timeToLoadedData__ = -1;
    _this.mainAppendsToLoadedData__ = -1;
    _this.audioAppendsToLoadedData__ = -1;
    var event = _this.tech_.preload() === "none" ? "play" : "loadstart";
    _this.tech_.one(event, function() {
      var timeToLoadedDataStart = Date.now();
      _this.tech_.one("loadeddata", function() {
        _this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
        _this.mainAppendsToLoadedData__ = _this.mainSegmentLoader_.mediaAppends;
        _this.audioAppendsToLoadedData__ = _this.audioSegmentLoader_.mediaAppends;
      });
    });
    return _this;
  }
  var _proto = MasterPlaylistController2.prototype;
  _proto.mainAppendsToLoadedData_ = function mainAppendsToLoadedData_() {
    return this.mainAppendsToLoadedData__;
  };
  _proto.audioAppendsToLoadedData_ = function audioAppendsToLoadedData_() {
    return this.audioAppendsToLoadedData__;
  };
  _proto.appendsToLoadedData_ = function appendsToLoadedData_() {
    var main = this.mainAppendsToLoadedData_();
    var audio = this.audioAppendsToLoadedData_();
    if (main === -1 || audio === -1) {
      return -1;
    }
    return main + audio;
  };
  _proto.timeToLoadedData_ = function timeToLoadedData_() {
    return this.timeToLoadedData__;
  };
  _proto.checkABR_ = function checkABR_() {
    var nextPlaylist = this.selectPlaylist();
    if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
      this.switchMedia_(nextPlaylist, "abr");
    }
  };
  _proto.switchMedia_ = function switchMedia_(playlist, cause, delay) {
    var oldMedia = this.media();
    var oldId = oldMedia && (oldMedia.id || oldMedia.uri);
    var newId = playlist.id || playlist.uri;
    if (oldId && oldId !== newId) {
      this.logger_("switch media " + oldId + " -> " + newId + " from " + cause);
      this.tech_.trigger({
        type: "usage",
        name: "vhs-rendition-change-" + cause
      });
    }
    this.masterPlaylistLoader_.media(playlist, delay);
  };
  _proto.startABRTimer_ = function startABRTimer_() {
    var _this2 = this;
    this.stopABRTimer_();
    this.abrTimer_ = import_window6.default.setInterval(function() {
      return _this2.checkABR_();
    }, 250);
  };
  _proto.stopABRTimer_ = function stopABRTimer_() {
    if (this.tech_.scrubbing && this.tech_.scrubbing()) {
      return;
    }
    import_window6.default.clearInterval(this.abrTimer_);
    this.abrTimer_ = null;
  };
  _proto.getAudioTrackPlaylists_ = function getAudioTrackPlaylists_() {
    var master = this.master();
    var defaultPlaylists = master && master.playlists || [];
    if (!master || !master.mediaGroups || !master.mediaGroups.AUDIO) {
      return defaultPlaylists;
    }
    var AUDIO5 = master.mediaGroups.AUDIO;
    var groupKeys = Object.keys(AUDIO5);
    var track;
    if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
      track = this.mediaTypes_.AUDIO.activeTrack();
    } else {
      var defaultGroup = AUDIO5.main || groupKeys.length && AUDIO5[groupKeys[0]];
      for (var label in defaultGroup) {
        if (defaultGroup[label]["default"]) {
          track = {
            label
          };
          break;
        }
      }
    }
    if (!track) {
      return defaultPlaylists;
    }
    var playlists = [];
    for (var group in AUDIO5) {
      if (AUDIO5[group][track.label]) {
        var properties = AUDIO5[group][track.label];
        if (properties.playlists && properties.playlists.length) {
          playlists.push.apply(playlists, properties.playlists);
        } else if (properties.uri) {
          playlists.push(properties);
        } else if (master.playlists.length) {
          for (var i = 0; i < master.playlists.length; i++) {
            var playlist = master.playlists[i];
            if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
              playlists.push(playlist);
            }
          }
        }
      }
    }
    if (!playlists.length) {
      return defaultPlaylists;
    }
    return playlists;
  };
  _proto.setupMasterPlaylistLoaderListeners_ = function setupMasterPlaylistLoaderListeners_() {
    var _this3 = this;
    this.masterPlaylistLoader_.on("loadedmetadata", function() {
      var media = _this3.masterPlaylistLoader_.media();
      var requestTimeout = media.targetDuration * 1.5 * 1e3;
      if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
        _this3.requestOptions_.timeout = 0;
      } else {
        _this3.requestOptions_.timeout = requestTimeout;
      }
      if (media.endList && _this3.tech_.preload() !== "none") {
        _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
        _this3.mainSegmentLoader_.load();
      }
      setupMediaGroups({
        sourceType: _this3.sourceType_,
        segmentLoaders: {
          AUDIO: _this3.audioSegmentLoader_,
          SUBTITLES: _this3.subtitleSegmentLoader_,
          main: _this3.mainSegmentLoader_
        },
        tech: _this3.tech_,
        requestOptions: _this3.requestOptions_,
        masterPlaylistLoader: _this3.masterPlaylistLoader_,
        vhs: _this3.vhs_,
        master: _this3.master(),
        mediaTypes: _this3.mediaTypes_,
        blacklistCurrentPlaylist: _this3.blacklistCurrentPlaylist.bind(_this3)
      });
      _this3.triggerPresenceUsage_(_this3.master(), media);
      _this3.setupFirstPlay();
      if (!_this3.mediaTypes_.AUDIO.activePlaylistLoader || _this3.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
        _this3.trigger("selectedinitialmedia");
      } else {
        _this3.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata", function() {
          _this3.trigger("selectedinitialmedia");
        });
      }
    });
    this.masterPlaylistLoader_.on("loadedplaylist", function() {
      if (_this3.loadOnPlay_) {
        _this3.tech_.off("play", _this3.loadOnPlay_);
      }
      var updatedPlaylist = _this3.masterPlaylistLoader_.media();
      if (!updatedPlaylist) {
        _this3.excludeUnsupportedVariants_();
        var selectedMedia;
        if (_this3.enableLowInitialPlaylist) {
          selectedMedia = _this3.selectInitialPlaylist();
        }
        if (!selectedMedia) {
          selectedMedia = _this3.selectPlaylist();
        }
        if (!selectedMedia || !_this3.shouldSwitchToMedia_(selectedMedia)) {
          return;
        }
        _this3.initialMedia_ = selectedMedia;
        _this3.switchMedia_(_this3.initialMedia_, "initial");
        var haveJsonSource = _this3.sourceType_ === "vhs-json" && _this3.initialMedia_.segments;
        if (!haveJsonSource) {
          return;
        }
        updatedPlaylist = _this3.initialMedia_;
      }
      _this3.handleUpdatedMediaPlaylist(updatedPlaylist);
    });
    this.masterPlaylistLoader_.on("error", function() {
      _this3.blacklistCurrentPlaylist(_this3.masterPlaylistLoader_.error);
    });
    this.masterPlaylistLoader_.on("mediachanging", function() {
      _this3.mainSegmentLoader_.abort();
      _this3.mainSegmentLoader_.pause();
    });
    this.masterPlaylistLoader_.on("mediachange", function() {
      var media = _this3.masterPlaylistLoader_.media();
      var requestTimeout = media.targetDuration * 1.5 * 1e3;
      if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
        _this3.requestOptions_.timeout = 0;
      } else {
        _this3.requestOptions_.timeout = requestTimeout;
      }
      _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
      _this3.mainSegmentLoader_.load();
      _this3.tech_.trigger({
        type: "mediachange",
        bubbles: true
      });
    });
    this.masterPlaylistLoader_.on("playlistunchanged", function() {
      var updatedPlaylist = _this3.masterPlaylistLoader_.media();
      if (updatedPlaylist.lastExcludeReason_ === "playlist-unchanged") {
        return;
      }
      var playlistOutdated = _this3.stuckAtPlaylistEnd_(updatedPlaylist);
      if (playlistOutdated) {
        _this3.blacklistCurrentPlaylist({
          message: "Playlist no longer updating.",
          reason: "playlist-unchanged"
        });
        _this3.tech_.trigger("playliststuck");
      }
    });
    this.masterPlaylistLoader_.on("renditiondisabled", function() {
      _this3.tech_.trigger({
        type: "usage",
        name: "vhs-rendition-disabled"
      });
      _this3.tech_.trigger({
        type: "usage",
        name: "hls-rendition-disabled"
      });
    });
    this.masterPlaylistLoader_.on("renditionenabled", function() {
      _this3.tech_.trigger({
        type: "usage",
        name: "vhs-rendition-enabled"
      });
      _this3.tech_.trigger({
        type: "usage",
        name: "hls-rendition-enabled"
      });
    });
  };
  _proto.handleUpdatedMediaPlaylist = function handleUpdatedMediaPlaylist(updatedPlaylist) {
    if (this.useCueTags_) {
      this.updateAdCues_(updatedPlaylist);
    }
    this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
    this.updateDuration(!updatedPlaylist.endList);
    if (!this.tech_.paused()) {
      this.mainSegmentLoader_.load();
      if (this.audioSegmentLoader_) {
        this.audioSegmentLoader_.load();
      }
    }
  };
  _proto.triggerPresenceUsage_ = function triggerPresenceUsage_(master, media) {
    var mediaGroups = master.mediaGroups || {};
    var defaultDemuxed = true;
    var audioGroupKeys = Object.keys(mediaGroups.AUDIO);
    for (var mediaGroup in mediaGroups.AUDIO) {
      for (var label in mediaGroups.AUDIO[mediaGroup]) {
        var properties = mediaGroups.AUDIO[mediaGroup][label];
        if (!properties.uri) {
          defaultDemuxed = false;
        }
      }
    }
    if (defaultDemuxed) {
      this.tech_.trigger({
        type: "usage",
        name: "vhs-demuxed"
      });
      this.tech_.trigger({
        type: "usage",
        name: "hls-demuxed"
      });
    }
    if (Object.keys(mediaGroups.SUBTITLES).length) {
      this.tech_.trigger({
        type: "usage",
        name: "vhs-webvtt"
      });
      this.tech_.trigger({
        type: "usage",
        name: "hls-webvtt"
      });
    }
    if (Vhs$1.Playlist.isAes(media)) {
      this.tech_.trigger({
        type: "usage",
        name: "vhs-aes"
      });
      this.tech_.trigger({
        type: "usage",
        name: "hls-aes"
      });
    }
    if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
      this.tech_.trigger({
        type: "usage",
        name: "vhs-alternate-audio"
      });
      this.tech_.trigger({
        type: "usage",
        name: "hls-alternate-audio"
      });
    }
    if (this.useCueTags_) {
      this.tech_.trigger({
        type: "usage",
        name: "vhs-playlist-cue-tags"
      });
      this.tech_.trigger({
        type: "usage",
        name: "hls-playlist-cue-tags"
      });
    }
  };
  _proto.shouldSwitchToMedia_ = function shouldSwitchToMedia_(nextPlaylist) {
    var currentPlaylist = this.masterPlaylistLoader_.media() || this.masterPlaylistLoader_.pendingMedia_;
    var currentTime = this.tech_.currentTime();
    var bufferLowWaterLine = this.bufferLowWaterLine();
    var bufferHighWaterLine = this.bufferHighWaterLine();
    var buffered = this.tech_.buffered();
    return shouldSwitchToMedia({
      buffered,
      currentTime,
      currentPlaylist,
      nextPlaylist,
      bufferLowWaterLine,
      bufferHighWaterLine,
      duration: this.duration(),
      experimentalBufferBasedABR: this.experimentalBufferBasedABR,
      log: this.logger_
    });
  };
  _proto.setupSegmentLoaderListeners_ = function setupSegmentLoaderListeners_() {
    var _this4 = this;
    if (!this.experimentalBufferBasedABR) {
      this.mainSegmentLoader_.on("bandwidthupdate", function() {
        var nextPlaylist = _this4.selectPlaylist();
        if (_this4.shouldSwitchToMedia_(nextPlaylist)) {
          _this4.switchMedia_(nextPlaylist, "bandwidthupdate");
        }
        _this4.tech_.trigger("bandwidthupdate");
      });
      this.mainSegmentLoader_.on("progress", function() {
        _this4.trigger("progress");
      });
    }
    this.mainSegmentLoader_.on("error", function() {
      _this4.blacklistCurrentPlaylist(_this4.mainSegmentLoader_.error());
    });
    this.mainSegmentLoader_.on("appenderror", function() {
      _this4.error = _this4.mainSegmentLoader_.error_;
      _this4.trigger("error");
    });
    this.mainSegmentLoader_.on("syncinfoupdate", function() {
      _this4.onSyncInfoUpdate_();
    });
    this.mainSegmentLoader_.on("timestampoffset", function() {
      _this4.tech_.trigger({
        type: "usage",
        name: "vhs-timestamp-offset"
      });
      _this4.tech_.trigger({
        type: "usage",
        name: "hls-timestamp-offset"
      });
    });
    this.audioSegmentLoader_.on("syncinfoupdate", function() {
      _this4.onSyncInfoUpdate_();
    });
    this.audioSegmentLoader_.on("appenderror", function() {
      _this4.error = _this4.audioSegmentLoader_.error_;
      _this4.trigger("error");
    });
    this.mainSegmentLoader_.on("ended", function() {
      _this4.logger_("main segment loader ended");
      _this4.onEndOfStream();
    });
    this.mainSegmentLoader_.on("earlyabort", function(event) {
      if (_this4.experimentalBufferBasedABR) {
        return;
      }
      _this4.delegateLoaders_("all", ["abort"]);
      _this4.blacklistCurrentPlaylist({
        message: "Aborted early because there isn't enough bandwidth to complete the request without rebuffering."
      }, ABORT_EARLY_BLACKLIST_SECONDS);
    });
    var updateCodecs = function updateCodecs2() {
      if (!_this4.sourceUpdater_.hasCreatedSourceBuffers()) {
        return _this4.tryToCreateSourceBuffers_();
      }
      var codecs = _this4.getCodecsOrExclude_();
      if (!codecs) {
        return;
      }
      _this4.sourceUpdater_.addOrChangeSourceBuffers(codecs);
    };
    this.mainSegmentLoader_.on("trackinfo", updateCodecs);
    this.audioSegmentLoader_.on("trackinfo", updateCodecs);
    this.mainSegmentLoader_.on("fmp4", function() {
      if (!_this4.triggeredFmp4Usage) {
        _this4.tech_.trigger({
          type: "usage",
          name: "vhs-fmp4"
        });
        _this4.tech_.trigger({
          type: "usage",
          name: "hls-fmp4"
        });
        _this4.triggeredFmp4Usage = true;
      }
    });
    this.audioSegmentLoader_.on("fmp4", function() {
      if (!_this4.triggeredFmp4Usage) {
        _this4.tech_.trigger({
          type: "usage",
          name: "vhs-fmp4"
        });
        _this4.tech_.trigger({
          type: "usage",
          name: "hls-fmp4"
        });
        _this4.triggeredFmp4Usage = true;
      }
    });
    this.audioSegmentLoader_.on("ended", function() {
      _this4.logger_("audioSegmentLoader ended");
      _this4.onEndOfStream();
    });
  };
  _proto.mediaSecondsLoaded_ = function mediaSecondsLoaded_() {
    return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  };
  _proto.load = function load() {
    this.mainSegmentLoader_.load();
    if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
      this.audioSegmentLoader_.load();
    }
    if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
      this.subtitleSegmentLoader_.load();
    }
  };
  _proto.smoothQualityChange_ = function smoothQualityChange_(media) {
    if (media === void 0) {
      media = this.selectPlaylist();
    }
    this.fastQualityChange_(media);
  };
  _proto.fastQualityChange_ = function fastQualityChange_(media) {
    var _this5 = this;
    if (media === void 0) {
      media = this.selectPlaylist();
    }
    if (media === this.masterPlaylistLoader_.media()) {
      this.logger_("skipping fastQualityChange because new media is same as old");
      return;
    }
    this.switchMedia_(media, "fast-quality");
    this.mainSegmentLoader_.resetEverything(function() {
      if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
        _this5.tech_.setCurrentTime(_this5.tech_.currentTime() + 0.04);
      } else {
        _this5.tech_.setCurrentTime(_this5.tech_.currentTime());
      }
    });
  };
  _proto.play = function play() {
    if (this.setupFirstPlay()) {
      return;
    }
    if (this.tech_.ended()) {
      this.tech_.setCurrentTime(0);
    }
    if (this.hasPlayed_) {
      this.load();
    }
    var seekable3 = this.tech_.seekable();
    if (this.tech_.duration() === Infinity) {
      if (this.tech_.currentTime() < seekable3.start(0)) {
        return this.tech_.setCurrentTime(seekable3.end(seekable3.length - 1));
      }
    }
  };
  _proto.setupFirstPlay = function setupFirstPlay() {
    var _this6 = this;
    var media = this.masterPlaylistLoader_.media();
    if (!media || this.tech_.paused() || this.hasPlayed_) {
      return false;
    }
    if (!media.endList) {
      var seekable3 = this.seekable();
      if (!seekable3.length) {
        return false;
      }
      if (videojs.browser.IE_VERSION && this.tech_.readyState() === 0) {
        this.tech_.one("loadedmetadata", function() {
          _this6.trigger("firstplay");
          _this6.tech_.setCurrentTime(seekable3.end(0));
          _this6.hasPlayed_ = true;
        });
        return false;
      }
      this.trigger("firstplay");
      this.tech_.setCurrentTime(seekable3.end(0));
    }
    this.hasPlayed_ = true;
    this.load();
    return true;
  };
  _proto.handleSourceOpen_ = function handleSourceOpen_() {
    this.tryToCreateSourceBuffers_();
    if (this.tech_.autoplay()) {
      var playPromise = this.tech_.play();
      if (typeof playPromise !== "undefined" && typeof playPromise.then === "function") {
        playPromise.then(null, function(e) {
        });
      }
    }
    this.trigger("sourceopen");
  };
  _proto.handleSourceEnded_ = function handleSourceEnded_() {
    if (!this.inbandTextTracks_.metadataTrack_) {
      return;
    }
    var cues = this.inbandTextTracks_.metadataTrack_.cues;
    if (!cues || !cues.length) {
      return;
    }
    var duration5 = this.duration();
    cues[cues.length - 1].endTime = isNaN(duration5) || Math.abs(duration5) === Infinity ? Number.MAX_VALUE : duration5;
  };
  _proto.handleDurationChange_ = function handleDurationChange_() {
    this.tech_.trigger("durationchange");
  };
  _proto.onEndOfStream = function onEndOfStream() {
    var isEndOfStream = this.mainSegmentLoader_.ended_;
    if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
      var mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_();
      if (!mainMediaInfo || mainMediaInfo.hasVideo) {
        isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
      } else {
        isEndOfStream = this.audioSegmentLoader_.ended_;
      }
    }
    if (!isEndOfStream) {
      return;
    }
    this.stopABRTimer_();
    this.sourceUpdater_.endOfStream();
  };
  _proto.stuckAtPlaylistEnd_ = function stuckAtPlaylistEnd_(playlist) {
    var seekable3 = this.seekable();
    if (!seekable3.length) {
      return false;
    }
    var expired = this.syncController_.getExpiredTime(playlist, this.duration());
    if (expired === null) {
      return false;
    }
    var absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
    var currentTime = this.tech_.currentTime();
    var buffered = this.tech_.buffered();
    if (!buffered.length) {
      return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
    }
    var bufferedEnd = buffered.end(buffered.length - 1);
    return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  };
  _proto.blacklistCurrentPlaylist = function blacklistCurrentPlaylist(error, blacklistDuration) {
    if (error === void 0) {
      error = {};
    }
    var currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
    blacklistDuration = blacklistDuration || error.blacklistDuration || this.blacklistDuration;
    if (!currentPlaylist) {
      this.error = error;
      if (this.mediaSource.readyState !== "open") {
        this.trigger("error");
      } else {
        this.sourceUpdater_.endOfStream("network");
      }
      return;
    }
    currentPlaylist.playlistErrors_++;
    var playlists = this.masterPlaylistLoader_.master.playlists;
    var enabledPlaylists = playlists.filter(isEnabled);
    var isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === currentPlaylist;
    if (playlists.length === 1 && blacklistDuration !== Infinity) {
      videojs.log.warn("Problem encountered with playlist " + currentPlaylist.id + ". Trying again since it is the only playlist.");
      this.tech_.trigger("retryplaylist");
      return this.masterPlaylistLoader_.load(isFinalRendition);
    }
    if (isFinalRendition) {
      var reincluded = false;
      playlists.forEach(function(playlist) {
        if (playlist === currentPlaylist) {
          return;
        }
        var excludeUntil2 = playlist.excludeUntil;
        if (typeof excludeUntil2 !== "undefined" && excludeUntil2 !== Infinity) {
          reincluded = true;
          delete playlist.excludeUntil;
        }
      });
      if (reincluded) {
        videojs.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded.");
        this.tech_.trigger("retryplaylist");
      }
    }
    var excludeUntil;
    if (currentPlaylist.playlistErrors_ > this.maxPlaylistRetries) {
      excludeUntil = Infinity;
    } else {
      excludeUntil = Date.now() + blacklistDuration * 1e3;
    }
    currentPlaylist.excludeUntil = excludeUntil;
    if (error.reason) {
      currentPlaylist.lastExcludeReason_ = error.reason;
    }
    this.tech_.trigger("blacklistplaylist");
    this.tech_.trigger({
      type: "usage",
      name: "vhs-rendition-blacklisted"
    });
    this.tech_.trigger({
      type: "usage",
      name: "hls-rendition-blacklisted"
    });
    var nextPlaylist = this.selectPlaylist();
    if (!nextPlaylist) {
      this.error = "Playback cannot continue. No available working or supported playlists.";
      this.trigger("error");
      return;
    }
    var logFn2 = error.internal ? this.logger_ : videojs.log.warn;
    var errorMessage = error.message ? " " + error.message : "";
    logFn2((error.internal ? "Internal problem" : "Problem") + " encountered with playlist " + currentPlaylist.id + "." + (errorMessage + " Switching to playlist " + nextPlaylist.id + "."));
    if (nextPlaylist.attributes.AUDIO !== currentPlaylist.attributes.AUDIO) {
      this.delegateLoaders_("audio", ["abort", "pause"]);
    }
    if (nextPlaylist.attributes.SUBTITLES !== currentPlaylist.attributes.SUBTITLES) {
      this.delegateLoaders_("subtitle", ["abort", "pause"]);
    }
    this.delegateLoaders_("main", ["abort", "pause"]);
    var delayDuration = nextPlaylist.targetDuration / 2 * 1e3 || 5 * 1e3;
    var shouldDelay = typeof nextPlaylist.lastRequest === "number" && Date.now() - nextPlaylist.lastRequest <= delayDuration;
    return this.switchMedia_(nextPlaylist, "exclude", isFinalRendition || shouldDelay);
  };
  _proto.pauseLoading = function pauseLoading() {
    this.delegateLoaders_("all", ["abort", "pause"]);
    this.stopABRTimer_();
  };
  _proto.delegateLoaders_ = function delegateLoaders_(filter, fnNames) {
    var _this7 = this;
    var loaders = [];
    var dontFilterPlaylist = filter === "all";
    if (dontFilterPlaylist || filter === "main") {
      loaders.push(this.masterPlaylistLoader_);
    }
    var mediaTypes2 = [];
    if (dontFilterPlaylist || filter === "audio") {
      mediaTypes2.push("AUDIO");
    }
    if (dontFilterPlaylist || filter === "subtitle") {
      mediaTypes2.push("CLOSED-CAPTIONS");
      mediaTypes2.push("SUBTITLES");
    }
    mediaTypes2.forEach(function(mediaType) {
      var loader = _this7.mediaTypes_[mediaType] && _this7.mediaTypes_[mediaType].activePlaylistLoader;
      if (loader) {
        loaders.push(loader);
      }
    });
    ["main", "audio", "subtitle"].forEach(function(name) {
      var loader = _this7[name + "SegmentLoader_"];
      if (loader && (filter === name || filter === "all")) {
        loaders.push(loader);
      }
    });
    loaders.forEach(function(loader) {
      return fnNames.forEach(function(fnName) {
        if (typeof loader[fnName] === "function") {
          loader[fnName]();
        }
      });
    });
  };
  _proto.setCurrentTime = function setCurrentTime(currentTime) {
    var buffered = findRange(this.tech_.buffered(), currentTime);
    if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
      return 0;
    }
    if (!this.masterPlaylistLoader_.media().segments) {
      return 0;
    }
    if (buffered && buffered.length) {
      return currentTime;
    }
    this.mainSegmentLoader_.resetEverything();
    this.mainSegmentLoader_.abort();
    if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
      this.audioSegmentLoader_.resetEverything();
      this.audioSegmentLoader_.abort();
    }
    if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
      this.subtitleSegmentLoader_.resetEverything();
      this.subtitleSegmentLoader_.abort();
    }
    this.load();
  };
  _proto.duration = function duration5() {
    if (!this.masterPlaylistLoader_) {
      return 0;
    }
    var media = this.masterPlaylistLoader_.media();
    if (!media) {
      return 0;
    }
    if (!media.endList) {
      return Infinity;
    }
    if (this.mediaSource) {
      return this.mediaSource.duration;
    }
    return Vhs$1.Playlist.duration(media);
  };
  _proto.seekable = function seekable3() {
    return this.seekable_;
  };
  _proto.onSyncInfoUpdate_ = function onSyncInfoUpdate_() {
    var audioSeekable;
    if (!this.masterPlaylistLoader_) {
      return;
    }
    var media = this.masterPlaylistLoader_.media();
    if (!media) {
      return;
    }
    var expired = this.syncController_.getExpiredTime(media, this.duration());
    if (expired === null) {
      return;
    }
    var master = this.masterPlaylistLoader_.master;
    var mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
    if (mainSeekable.length === 0) {
      return;
    }
    if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
      media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
      expired = this.syncController_.getExpiredTime(media, this.duration());
      if (expired === null) {
        return;
      }
      audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
      if (audioSeekable.length === 0) {
        return;
      }
    }
    var oldEnd;
    var oldStart;
    if (this.seekable_ && this.seekable_.length) {
      oldEnd = this.seekable_.end(0);
      oldStart = this.seekable_.start(0);
    }
    if (!audioSeekable) {
      this.seekable_ = mainSeekable;
    } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
      this.seekable_ = mainSeekable;
    } else {
      this.seekable_ = videojs.createTimeRanges([[audioSeekable.start(0) > mainSeekable.start(0) ? audioSeekable.start(0) : mainSeekable.start(0), audioSeekable.end(0) < mainSeekable.end(0) ? audioSeekable.end(0) : mainSeekable.end(0)]]);
    }
    if (this.seekable_ && this.seekable_.length) {
      if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
        return;
      }
    }
    this.logger_("seekable updated [" + printableRange(this.seekable_) + "]");
    this.tech_.trigger("seekablechanged");
  };
  _proto.updateDuration = function updateDuration(isLive) {
    if (this.updateDuration_) {
      this.mediaSource.removeEventListener("sourceopen", this.updateDuration_);
      this.updateDuration_ = null;
    }
    if (this.mediaSource.readyState !== "open") {
      this.updateDuration_ = this.updateDuration.bind(this, isLive);
      this.mediaSource.addEventListener("sourceopen", this.updateDuration_);
      return;
    }
    if (isLive) {
      var seekable3 = this.seekable();
      if (!seekable3.length) {
        return;
      }
      if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable3.end(seekable3.length - 1)) {
        this.sourceUpdater_.setDuration(seekable3.end(seekable3.length - 1));
      }
      return;
    }
    var buffered = this.tech_.buffered();
    var duration5 = Vhs$1.Playlist.duration(this.masterPlaylistLoader_.media());
    if (buffered.length > 0) {
      duration5 = Math.max(duration5, buffered.end(buffered.length - 1));
    }
    if (this.mediaSource.duration !== duration5) {
      this.sourceUpdater_.setDuration(duration5);
    }
  };
  _proto.dispose = function dispose() {
    var _this8 = this;
    this.trigger("dispose");
    this.decrypter_.terminate();
    this.masterPlaylistLoader_.dispose();
    this.mainSegmentLoader_.dispose();
    if (this.loadOnPlay_) {
      this.tech_.off("play", this.loadOnPlay_);
    }
    ["AUDIO", "SUBTITLES"].forEach(function(type2) {
      var groups = _this8.mediaTypes_[type2].groups;
      for (var id in groups) {
        groups[id].forEach(function(group) {
          if (group.playlistLoader) {
            group.playlistLoader.dispose();
          }
        });
      }
    });
    this.audioSegmentLoader_.dispose();
    this.subtitleSegmentLoader_.dispose();
    this.sourceUpdater_.dispose();
    this.timelineChangeController_.dispose();
    this.stopABRTimer_();
    if (this.updateDuration_) {
      this.mediaSource.removeEventListener("sourceopen", this.updateDuration_);
    }
    this.mediaSource.removeEventListener("durationchange", this.handleDurationChange_);
    this.mediaSource.removeEventListener("sourceopen", this.handleSourceOpen_);
    this.mediaSource.removeEventListener("sourceended", this.handleSourceEnded_);
    this.off();
  };
  _proto.master = function master() {
    return this.masterPlaylistLoader_.master;
  };
  _proto.media = function media() {
    return this.masterPlaylistLoader_.media() || this.initialMedia_;
  };
  _proto.areMediaTypesKnown_ = function areMediaTypesKnown_() {
    var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
    var hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_();
    var hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_();
    if (!hasMainMediaInfo || !hasAudioMediaInfo) {
      return false;
    }
    return true;
  };
  _proto.getCodecsOrExclude_ = function getCodecsOrExclude_() {
    var _this9 = this;
    var media = {
      main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
      audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
    };
    media.video = media.main;
    var playlistCodecs = codecsForPlaylist(this.master(), this.media());
    var codecs = {};
    var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
    if (media.main.hasVideo) {
      codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
    }
    if (media.main.isMuxed) {
      codecs.video += "," + (playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC);
    }
    if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
      codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC;
      media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
    }
    if (!codecs.audio && !codecs.video) {
      this.blacklistCurrentPlaylist({
        playlist: this.media(),
        message: "Could not determine codecs for playlist.",
        blacklistDuration: Infinity
      });
      return;
    }
    var supportFunction = function supportFunction2(isFmp4, codec) {
      return isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
    };
    var unsupportedCodecs = {};
    var unsupportedAudio;
    ["video", "audio"].forEach(function(type2) {
      if (codecs.hasOwnProperty(type2) && !supportFunction(media[type2].isFmp4, codecs[type2])) {
        var supporter = media[type2].isFmp4 ? "browser" : "muxer";
        unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
        unsupportedCodecs[supporter].push(codecs[type2]);
        if (type2 === "audio") {
          unsupportedAudio = supporter;
        }
      }
    });
    if (usingAudioLoader && unsupportedAudio && this.media().attributes.AUDIO) {
      var audioGroup = this.media().attributes.AUDIO;
      this.master().playlists.forEach(function(variant) {
        var variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
        if (variantAudioGroup === audioGroup && variant !== _this9.media()) {
          variant.excludeUntil = Infinity;
        }
      });
      this.logger_("excluding audio group " + audioGroup + " as " + unsupportedAudio + ' does not support codec(s): "' + codecs.audio + '"');
    }
    if (Object.keys(unsupportedCodecs).length) {
      var message = Object.keys(unsupportedCodecs).reduce(function(acc, supporter) {
        if (acc) {
          acc += ", ";
        }
        acc += supporter + ' does not support codec(s): "' + unsupportedCodecs[supporter].join(",") + '"';
        return acc;
      }, "") + ".";
      this.blacklistCurrentPlaylist({
        playlist: this.media(),
        internal: true,
        message,
        blacklistDuration: Infinity
      });
      return;
    }
    if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
      var switchMessages = [];
      ["video", "audio"].forEach(function(type2) {
        var newCodec = (parseCodecs(_this9.sourceUpdater_.codecs[type2] || "")[0] || {}).type;
        var oldCodec = (parseCodecs(codecs[type2] || "")[0] || {}).type;
        if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
          switchMessages.push('"' + _this9.sourceUpdater_.codecs[type2] + '" -> "' + codecs[type2] + '"');
        }
      });
      if (switchMessages.length) {
        this.blacklistCurrentPlaylist({
          playlist: this.media(),
          message: "Codec switching not supported: " + switchMessages.join(", ") + ".",
          blacklistDuration: Infinity,
          internal: true
        });
        return;
      }
    }
    return codecs;
  };
  _proto.tryToCreateSourceBuffers_ = function tryToCreateSourceBuffers_() {
    if (this.mediaSource.readyState !== "open" || this.sourceUpdater_.hasCreatedSourceBuffers()) {
      return;
    }
    if (!this.areMediaTypesKnown_()) {
      return;
    }
    var codecs = this.getCodecsOrExclude_();
    if (!codecs) {
      return;
    }
    this.sourceUpdater_.createSourceBuffers(codecs);
    var codecString = [codecs.video, codecs.audio].filter(Boolean).join(",");
    this.excludeIncompatibleVariants_(codecString);
  };
  _proto.excludeUnsupportedVariants_ = function excludeUnsupportedVariants_() {
    var _this10 = this;
    var playlists = this.master().playlists;
    var ids = [];
    Object.keys(playlists).forEach(function(key) {
      var variant = playlists[key];
      if (ids.indexOf(variant.id) !== -1) {
        return;
      }
      ids.push(variant.id);
      var codecs = codecsForPlaylist(_this10.master, variant);
      var unsupported = [];
      if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
        unsupported.push("audio codec " + codecs.audio);
      }
      if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
        unsupported.push("video codec " + codecs.video);
      }
      if (codecs.text && codecs.text === "stpp.ttml.im1t") {
        unsupported.push("text codec " + codecs.text);
      }
      if (unsupported.length) {
        variant.excludeUntil = Infinity;
        _this10.logger_("excluding " + variant.id + " for unsupported: " + unsupported.join(", "));
      }
    });
  };
  _proto.excludeIncompatibleVariants_ = function excludeIncompatibleVariants_(codecString) {
    var _this11 = this;
    var ids = [];
    var playlists = this.master().playlists;
    var codecs = unwrapCodecList(parseCodecs(codecString));
    var codecCount_ = codecCount(codecs);
    var videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
    var audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
    Object.keys(playlists).forEach(function(key) {
      var variant = playlists[key];
      if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
        return;
      }
      ids.push(variant.id);
      var blacklistReasons = [];
      var variantCodecs = codecsForPlaylist(_this11.masterPlaylistLoader_.master, variant);
      var variantCodecCount = codecCount(variantCodecs);
      if (!variantCodecs.audio && !variantCodecs.video) {
        return;
      }
      if (variantCodecCount !== codecCount_) {
        blacklistReasons.push('codec count "' + variantCodecCount + '" !== "' + codecCount_ + '"');
      }
      if (!_this11.sourceUpdater_.canChangeType()) {
        var variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
        var variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null;
        if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
          blacklistReasons.push('video codec "' + variantVideoDetails.type + '" !== "' + videoDetails.type + '"');
        }
        if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
          blacklistReasons.push('audio codec "' + variantAudioDetails.type + '" !== "' + audioDetails.type + '"');
        }
      }
      if (blacklistReasons.length) {
        variant.excludeUntil = Infinity;
        _this11.logger_("blacklisting " + variant.id + ": " + blacklistReasons.join(" && "));
      }
    });
  };
  _proto.updateAdCues_ = function updateAdCues_(media) {
    var offset = 0;
    var seekable3 = this.seekable();
    if (seekable3.length) {
      offset = seekable3.start(0);
    }
    updateAdCues(media, this.cueTagsTrack_, offset);
  };
  _proto.goalBufferLength = function goalBufferLength() {
    var currentTime = this.tech_.currentTime();
    var initial = Config.GOAL_BUFFER_LENGTH;
    var rate = Config.GOAL_BUFFER_LENGTH_RATE;
    var max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
    return Math.min(initial + currentTime * rate, max);
  };
  _proto.bufferLowWaterLine = function bufferLowWaterLine() {
    var currentTime = this.tech_.currentTime();
    var initial = Config.BUFFER_LOW_WATER_LINE;
    var rate = Config.BUFFER_LOW_WATER_LINE_RATE;
    var max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
    var newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
    return Math.min(initial + currentTime * rate, this.experimentalBufferBasedABR ? newMax : max);
  };
  _proto.bufferHighWaterLine = function bufferHighWaterLine() {
    return Config.BUFFER_HIGH_WATER_LINE;
  };
  return MasterPlaylistController2;
}(videojs.EventTarget);
var enableFunction = function enableFunction2(loader, playlistID, changePlaylistFn) {
  return function(enable) {
    var playlist = loader.master.playlists[playlistID];
    var incompatible = isIncompatible(playlist);
    var currentlyEnabled = isEnabled(playlist);
    if (typeof enable === "undefined") {
      return currentlyEnabled;
    }
    if (enable) {
      delete playlist.disabled;
    } else {
      playlist.disabled = true;
    }
    if (enable !== currentlyEnabled && !incompatible) {
      changePlaylistFn();
      if (enable) {
        loader.trigger("renditionenabled");
      } else {
        loader.trigger("renditiondisabled");
      }
    }
    return enable;
  };
};
var Representation = function Representation2(vhsHandler, playlist, id) {
  var mpc = vhsHandler.masterPlaylistController_, smoothQualityChange = vhsHandler.options_.smoothQualityChange;
  var changeType2 = smoothQualityChange ? "smooth" : "fast";
  var qualityChangeFunction = mpc[changeType2 + "QualityChange_"].bind(mpc);
  if (playlist.attributes) {
    var resolution = playlist.attributes.RESOLUTION;
    this.width = resolution && resolution.width;
    this.height = resolution && resolution.height;
    this.bandwidth = playlist.attributes.BANDWIDTH;
  }
  this.codecs = codecsForPlaylist(mpc.master(), playlist);
  this.playlist = playlist;
  this.id = id;
  this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
};
var renditionSelectionMixin = function renditionSelectionMixin2(vhsHandler) {
  vhsHandler.representations = function() {
    var master = vhsHandler.masterPlaylistController_.master();
    var playlists = isAudioOnly(master) ? vhsHandler.masterPlaylistController_.getAudioTrackPlaylists_() : master.playlists;
    if (!playlists) {
      return [];
    }
    return playlists.filter(function(media) {
      return !isIncompatible(media);
    }).map(function(e, i) {
      return new Representation(vhsHandler, e, e.id);
    });
  };
};
var timerCancelEvents = ["seeking", "seeked", "pause", "playing", "error"];
var PlaybackWatcher = /* @__PURE__ */ function() {
  function PlaybackWatcher2(options) {
    var _this = this;
    this.masterPlaylistController_ = options.masterPlaylistController;
    this.tech_ = options.tech;
    this.seekable = options.seekable;
    this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
    this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
    this.media = options.media;
    this.consecutiveUpdates = 0;
    this.lastRecordedTime = null;
    this.timer_ = null;
    this.checkCurrentTimeTimeout_ = null;
    this.logger_ = logger2("PlaybackWatcher");
    this.logger_("initialize");
    var playHandler = function playHandler2() {
      return _this.monitorCurrentTime_();
    };
    var canPlayHandler = function canPlayHandler2() {
      return _this.monitorCurrentTime_();
    };
    var waitingHandler = function waitingHandler2() {
      return _this.techWaiting_();
    };
    var cancelTimerHandler = function cancelTimerHandler2() {
      return _this.cancelTimer_();
    };
    var mpc = this.masterPlaylistController_;
    var loaderTypes = ["main", "subtitle", "audio"];
    var loaderChecks = {};
    loaderTypes.forEach(function(type2) {
      loaderChecks[type2] = {
        reset: function reset3() {
          return _this.resetSegmentDownloads_(type2);
        },
        updateend: function updateend() {
          return _this.checkSegmentDownloads_(type2);
        }
      };
      mpc[type2 + "SegmentLoader_"].on("appendsdone", loaderChecks[type2].updateend);
      mpc[type2 + "SegmentLoader_"].on("playlistupdate", loaderChecks[type2].reset);
      _this.tech_.on(["seeked", "seeking"], loaderChecks[type2].reset);
    });
    var setSeekingHandlers = function setSeekingHandlers2(fn) {
      ["main", "audio"].forEach(function(type2) {
        mpc[type2 + "SegmentLoader_"][fn]("appended", _this.seekingAppendCheck_);
      });
    };
    this.seekingAppendCheck_ = function() {
      if (_this.fixesBadSeeks_()) {
        _this.consecutiveUpdates = 0;
        _this.lastRecordedTime = _this.tech_.currentTime();
        setSeekingHandlers("off");
      }
    };
    this.clearSeekingAppendCheck_ = function() {
      return setSeekingHandlers("off");
    };
    this.watchForBadSeeking_ = function() {
      _this.clearSeekingAppendCheck_();
      setSeekingHandlers("on");
    };
    this.tech_.on("seeked", this.clearSeekingAppendCheck_);
    this.tech_.on("seeking", this.watchForBadSeeking_);
    this.tech_.on("waiting", waitingHandler);
    this.tech_.on(timerCancelEvents, cancelTimerHandler);
    this.tech_.on("canplay", canPlayHandler);
    this.tech_.one("play", playHandler);
    this.dispose = function() {
      _this.clearSeekingAppendCheck_();
      _this.logger_("dispose");
      _this.tech_.off("waiting", waitingHandler);
      _this.tech_.off(timerCancelEvents, cancelTimerHandler);
      _this.tech_.off("canplay", canPlayHandler);
      _this.tech_.off("play", playHandler);
      _this.tech_.off("seeking", _this.watchForBadSeeking_);
      _this.tech_.off("seeked", _this.clearSeekingAppendCheck_);
      loaderTypes.forEach(function(type2) {
        mpc[type2 + "SegmentLoader_"].off("appendsdone", loaderChecks[type2].updateend);
        mpc[type2 + "SegmentLoader_"].off("playlistupdate", loaderChecks[type2].reset);
        _this.tech_.off(["seeked", "seeking"], loaderChecks[type2].reset);
      });
      if (_this.checkCurrentTimeTimeout_) {
        import_window6.default.clearTimeout(_this.checkCurrentTimeTimeout_);
      }
      _this.cancelTimer_();
    };
  }
  var _proto = PlaybackWatcher2.prototype;
  _proto.monitorCurrentTime_ = function monitorCurrentTime_() {
    this.checkCurrentTime_();
    if (this.checkCurrentTimeTimeout_) {
      import_window6.default.clearTimeout(this.checkCurrentTimeTimeout_);
    }
    this.checkCurrentTimeTimeout_ = import_window6.default.setTimeout(this.monitorCurrentTime_.bind(this), 250);
  };
  _proto.resetSegmentDownloads_ = function resetSegmentDownloads_(type2) {
    var loader = this.masterPlaylistController_[type2 + "SegmentLoader_"];
    if (this[type2 + "StalledDownloads_"] > 0) {
      this.logger_("resetting possible stalled download count for " + type2 + " loader");
    }
    this[type2 + "StalledDownloads_"] = 0;
    this[type2 + "Buffered_"] = loader.buffered_();
  };
  _proto.checkSegmentDownloads_ = function checkSegmentDownloads_(type2) {
    var mpc = this.masterPlaylistController_;
    var loader = mpc[type2 + "SegmentLoader_"];
    var buffered = loader.buffered_();
    var isBufferedDifferent = isRangeDifferent(this[type2 + "Buffered_"], buffered);
    this[type2 + "Buffered_"] = buffered;
    if (isBufferedDifferent) {
      this.resetSegmentDownloads_(type2);
      return;
    }
    this[type2 + "StalledDownloads_"]++;
    this.logger_("found #" + this[type2 + "StalledDownloads_"] + " " + type2 + " appends that did not increase buffer (possible stalled download)", {
      playlistId: loader.playlist_ && loader.playlist_.id,
      buffered: timeRangesToArray(buffered)
    });
    if (this[type2 + "StalledDownloads_"] < 10) {
      return;
    }
    this.logger_(type2 + " loader stalled download exclusion");
    this.resetSegmentDownloads_(type2);
    this.tech_.trigger({
      type: "usage",
      name: "vhs-" + type2 + "-download-exclusion"
    });
    if (type2 === "subtitle") {
      return;
    }
    mpc.blacklistCurrentPlaylist({
      message: "Excessive " + type2 + " segment downloading detected."
    }, Infinity);
  };
  _proto.checkCurrentTime_ = function checkCurrentTime_() {
    if (this.tech_.paused() || this.tech_.seeking()) {
      return;
    }
    var currentTime = this.tech_.currentTime();
    var buffered = this.tech_.buffered();
    if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
      return this.techWaiting_();
    }
    if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
      this.consecutiveUpdates++;
      this.waiting_();
    } else if (currentTime === this.lastRecordedTime) {
      this.consecutiveUpdates++;
    } else {
      this.consecutiveUpdates = 0;
      this.lastRecordedTime = currentTime;
    }
  };
  _proto.cancelTimer_ = function cancelTimer_() {
    this.consecutiveUpdates = 0;
    if (this.timer_) {
      this.logger_("cancelTimer_");
      clearTimeout(this.timer_);
    }
    this.timer_ = null;
  };
  _proto.fixesBadSeeks_ = function fixesBadSeeks_() {
    var seeking = this.tech_.seeking();
    if (!seeking) {
      return false;
    }
    var seekable3 = this.seekable();
    var currentTime = this.tech_.currentTime();
    var isAfterSeekableRange = this.afterSeekableWindow_(seekable3, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
    var seekTo;
    if (isAfterSeekableRange) {
      var seekableEnd = seekable3.end(seekable3.length - 1);
      seekTo = seekableEnd;
    }
    if (this.beforeSeekableWindow_(seekable3, currentTime)) {
      var seekableStart = seekable3.start(0);
      seekTo = seekableStart + // if the playlist is too short and the seekable range is an exact time (can
      // happen in live with a 3 segment playlist), then don't use a time delta
      (seekableStart === seekable3.end(0) ? 0 : SAFE_TIME_DELTA);
    }
    if (typeof seekTo !== "undefined") {
      this.logger_("Trying to seek outside of seekable at time " + currentTime + " with " + ("seekable range " + printableRange(seekable3) + ". Seeking to ") + (seekTo + "."));
      this.tech_.setCurrentTime(seekTo);
      return true;
    }
    var sourceUpdater = this.masterPlaylistController_.sourceUpdater_;
    var buffered = this.tech_.buffered();
    var audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
    var videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
    var media = this.media();
    var minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2;
    var bufferedToCheck = [audioBuffered, videoBuffered];
    for (var i = 0; i < bufferedToCheck.length; i++) {
      if (!bufferedToCheck[i]) {
        continue;
      }
      var timeAhead = timeAheadOf(bufferedToCheck[i], currentTime);
      if (timeAhead < minAppendedDuration) {
        return false;
      }
    }
    var nextRange = findNextRange(buffered, currentTime);
    if (nextRange.length === 0) {
      return false;
    }
    seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
    this.logger_("Buffered region starts (" + nextRange.start(0) + ") " + (" just beyond seek point (" + currentTime + "). Seeking to " + seekTo + "."));
    this.tech_.setCurrentTime(seekTo);
    return true;
  };
  _proto.waiting_ = function waiting_() {
    if (this.techWaiting_()) {
      return;
    }
    var currentTime = this.tech_.currentTime();
    var buffered = this.tech_.buffered();
    var currentRange = findRange(buffered, currentTime);
    if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
      this.cancelTimer_();
      this.tech_.setCurrentTime(currentTime);
      this.logger_("Stopped at " + currentTime + " while inside a buffered region " + ("[" + currentRange.start(0) + " -> " + currentRange.end(0) + "]. Attempting to resume ") + "playback by seeking to the current time.");
      this.tech_.trigger({
        type: "usage",
        name: "vhs-unknown-waiting"
      });
      this.tech_.trigger({
        type: "usage",
        name: "hls-unknown-waiting"
      });
      return;
    }
  };
  _proto.techWaiting_ = function techWaiting_() {
    var seekable3 = this.seekable();
    var currentTime = this.tech_.currentTime();
    if (this.tech_.seeking() || this.timer_ !== null) {
      return true;
    }
    if (this.beforeSeekableWindow_(seekable3, currentTime)) {
      var livePoint = seekable3.end(seekable3.length - 1);
      this.logger_("Fell out of live window at time " + currentTime + ". Seeking to " + ("live point (seekable end) " + livePoint));
      this.cancelTimer_();
      this.tech_.setCurrentTime(livePoint);
      this.tech_.trigger({
        type: "usage",
        name: "vhs-live-resync"
      });
      this.tech_.trigger({
        type: "usage",
        name: "hls-live-resync"
      });
      return true;
    }
    var sourceUpdater = this.tech_.vhs.masterPlaylistController_.sourceUpdater_;
    var buffered = this.tech_.buffered();
    var videoUnderflow = this.videoUnderflow_({
      audioBuffered: sourceUpdater.audioBuffered(),
      videoBuffered: sourceUpdater.videoBuffered(),
      currentTime
    });
    if (videoUnderflow) {
      this.cancelTimer_();
      this.tech_.setCurrentTime(currentTime);
      this.tech_.trigger({
        type: "usage",
        name: "vhs-video-underflow"
      });
      this.tech_.trigger({
        type: "usage",
        name: "hls-video-underflow"
      });
      return true;
    }
    var nextRange = findNextRange(buffered, currentTime);
    if (nextRange.length > 0) {
      var difference = nextRange.start(0) - currentTime;
      this.logger_("Stopped at " + currentTime + ", setting timer for " + difference + ", seeking " + ("to " + nextRange.start(0)));
      this.cancelTimer_();
      this.timer_ = setTimeout(this.skipTheGap_.bind(this), difference * 1e3, currentTime);
      return true;
    }
    return false;
  };
  _proto.afterSeekableWindow_ = function afterSeekableWindow_(seekable3, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow) {
    if (allowSeeksWithinUnsafeLiveWindow === void 0) {
      allowSeeksWithinUnsafeLiveWindow = false;
    }
    if (!seekable3.length) {
      return false;
    }
    var allowedEnd = seekable3.end(seekable3.length - 1) + SAFE_TIME_DELTA;
    var isLive = !playlist.endList;
    if (isLive && allowSeeksWithinUnsafeLiveWindow) {
      allowedEnd = seekable3.end(seekable3.length - 1) + playlist.targetDuration * 3;
    }
    if (currentTime > allowedEnd) {
      return true;
    }
    return false;
  };
  _proto.beforeSeekableWindow_ = function beforeSeekableWindow_(seekable3, currentTime) {
    if (seekable3.length && // can't fall before 0 and 0 seekable start identifies VOD stream
    seekable3.start(0) > 0 && currentTime < seekable3.start(0) - this.liveRangeSafeTimeDelta) {
      return true;
    }
    return false;
  };
  _proto.videoUnderflow_ = function videoUnderflow_(_ref) {
    var videoBuffered = _ref.videoBuffered, audioBuffered = _ref.audioBuffered, currentTime = _ref.currentTime;
    if (!videoBuffered) {
      return;
    }
    var gap;
    if (videoBuffered.length && audioBuffered.length) {
      var lastVideoRange = findRange(videoBuffered, currentTime - 3);
      var videoRange = findRange(videoBuffered, currentTime);
      var audioRange = findRange(audioBuffered, currentTime);
      if (audioRange.length && !videoRange.length && lastVideoRange.length) {
        gap = {
          start: lastVideoRange.end(0),
          end: audioRange.end(0)
        };
      }
    } else {
      var nextRange = findNextRange(videoBuffered, currentTime);
      if (!nextRange.length) {
        gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
      }
    }
    if (gap) {
      this.logger_("Encountered a gap in video from " + gap.start + " to " + gap.end + ". " + ("Seeking to current time " + currentTime));
      return true;
    }
    return false;
  };
  _proto.skipTheGap_ = function skipTheGap_(scheduledCurrentTime) {
    var buffered = this.tech_.buffered();
    var currentTime = this.tech_.currentTime();
    var nextRange = findNextRange(buffered, currentTime);
    this.cancelTimer_();
    if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
      return;
    }
    this.logger_("skipTheGap_:", "currentTime:", currentTime, "scheduled currentTime:", scheduledCurrentTime, "nextRange start:", nextRange.start(0));
    this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
    this.tech_.trigger({
      type: "usage",
      name: "vhs-gap-skip"
    });
    this.tech_.trigger({
      type: "usage",
      name: "hls-gap-skip"
    });
  };
  _proto.gapFromVideoUnderflow_ = function gapFromVideoUnderflow_(buffered, currentTime) {
    var gaps = findGaps(buffered);
    for (var i = 0; i < gaps.length; i++) {
      var start2 = gaps.start(i);
      var end = gaps.end(i);
      if (currentTime - start2 < 4 && currentTime - start2 > 2) {
        return {
          start: start2,
          end
        };
      }
    }
    return null;
  };
  return PlaybackWatcher2;
}();
var defaultOptions = {
  errorInterval: 30,
  getSource: function getSource(next) {
    var tech = this.tech({
      IWillNotUseThisInPlugins: true
    });
    var sourceObj = tech.currentSource_ || this.currentSource();
    return next(sourceObj);
  }
};
var initPlugin = function initPlugin2(player, options) {
  var lastCalled = 0;
  var seekTo = 0;
  var localOptions = videojs.mergeOptions(defaultOptions, options);
  player.ready(function() {
    player.trigger({
      type: "usage",
      name: "vhs-error-reload-initialized"
    });
    player.trigger({
      type: "usage",
      name: "hls-error-reload-initialized"
    });
  });
  var loadedMetadataHandler = function loadedMetadataHandler2() {
    if (seekTo) {
      player.currentTime(seekTo);
    }
  };
  var setSource2 = function setSource3(sourceObj) {
    if (sourceObj === null || sourceObj === void 0) {
      return;
    }
    seekTo = player.duration() !== Infinity && player.currentTime() || 0;
    player.one("loadedmetadata", loadedMetadataHandler);
    player.src(sourceObj);
    player.trigger({
      type: "usage",
      name: "vhs-error-reload"
    });
    player.trigger({
      type: "usage",
      name: "hls-error-reload"
    });
    player.play();
  };
  var errorHandler = function errorHandler2() {
    if (Date.now() - lastCalled < localOptions.errorInterval * 1e3) {
      player.trigger({
        type: "usage",
        name: "vhs-error-reload-canceled"
      });
      player.trigger({
        type: "usage",
        name: "hls-error-reload-canceled"
      });
      return;
    }
    if (!localOptions.getSource || typeof localOptions.getSource !== "function") {
      videojs.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!");
      return;
    }
    lastCalled = Date.now();
    return localOptions.getSource.call(player, setSource2);
  };
  var cleanupEvents = function cleanupEvents2() {
    player.off("loadedmetadata", loadedMetadataHandler);
    player.off("error", errorHandler);
    player.off("dispose", cleanupEvents2);
  };
  var reinitPlugin = function reinitPlugin2(newOptions) {
    cleanupEvents();
    initPlugin2(player, newOptions);
  };
  player.on("error", errorHandler);
  player.on("dispose", cleanupEvents);
  player.reloadSourceOnError = reinitPlugin;
};
var reloadSourceOnError = function reloadSourceOnError2(options) {
  initPlugin(this, options);
};
var version$4 = "2.14.3";
var version$3 = "6.0.1";
var version$2 = "0.21.1";
var version$1 = "4.7.1";
var version2 = "3.1.3";
var Vhs = {
  PlaylistLoader: PlaylistLoader2,
  Playlist,
  utils,
  STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  lastBandwidthSelector,
  movingAverageBandwidthSelector,
  comparePlaylistBandwidth,
  comparePlaylistResolution,
  xhr: xhrFactory()
};
Object.keys(Config).forEach(function(prop) {
  Object.defineProperty(Vhs, prop, {
    get: function get7() {
      videojs.log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
      return Config[prop];
    },
    set: function set4(value) {
      videojs.log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
      if (typeof value !== "number" || value < 0) {
        videojs.log.warn("value of Vhs." + prop + " must be greater than or equal to 0");
        return;
      }
      Config[prop] = value;
    }
  });
});
var LOCAL_STORAGE_KEY = "videojs-vhs";
var handleVhsMediaChange = function handleVhsMediaChange2(qualityLevels3, playlistLoader) {
  var newPlaylist = playlistLoader.media();
  var selectedIndex = -1;
  for (var i = 0; i < qualityLevels3.length; i++) {
    if (qualityLevels3[i].id === newPlaylist.id) {
      selectedIndex = i;
      break;
    }
  }
  qualityLevels3.selectedIndex_ = selectedIndex;
  qualityLevels3.trigger({
    selectedIndex,
    type: "change"
  });
};
var handleVhsLoadedMetadata = function handleVhsLoadedMetadata2(qualityLevels3, vhs) {
  vhs.representations().forEach(function(rep) {
    qualityLevels3.addQualityLevel(rep);
  });
  handleVhsMediaChange(qualityLevels3, vhs.playlists);
};
Vhs.canPlaySource = function() {
  return videojs.log.warn("HLS is no longer a tech. Please remove it from your player's techOrder.");
};
var emeKeySystems = function emeKeySystems2(keySystemOptions, mainPlaylist, audioPlaylist) {
  if (!keySystemOptions) {
    return keySystemOptions;
  }
  var codecs = {};
  if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
    codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
  }
  if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
    codecs.audio = audioPlaylist.attributes.CODECS;
  }
  var videoContentType = getMimeForCodec(codecs.video);
  var audioContentType = getMimeForCodec(codecs.audio);
  var keySystemContentTypes = {};
  for (var keySystem in keySystemOptions) {
    keySystemContentTypes[keySystem] = {};
    if (audioContentType) {
      keySystemContentTypes[keySystem].audioContentType = audioContentType;
    }
    if (videoContentType) {
      keySystemContentTypes[keySystem].videoContentType = videoContentType;
    }
    if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
      keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
    }
    if (typeof keySystemOptions[keySystem] === "string") {
      keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
    }
  }
  return videojs.mergeOptions(keySystemOptions, keySystemContentTypes);
};
var getAllPsshKeySystemsOptions = function getAllPsshKeySystemsOptions2(playlists, keySystems) {
  return playlists.reduce(function(keySystemsArr, playlist) {
    if (!playlist.contentProtection) {
      return keySystemsArr;
    }
    var keySystemsOptions = keySystems.reduce(function(keySystemsObj, keySystem) {
      var keySystemOptions = playlist.contentProtection[keySystem];
      if (keySystemOptions && keySystemOptions.pssh) {
        keySystemsObj[keySystem] = {
          pssh: keySystemOptions.pssh
        };
      }
      return keySystemsObj;
    }, {});
    if (Object.keys(keySystemsOptions).length) {
      keySystemsArr.push(keySystemsOptions);
    }
    return keySystemsArr;
  }, []);
};
var waitForKeySessionCreation = function waitForKeySessionCreation2(_ref) {
  var player = _ref.player, sourceKeySystems = _ref.sourceKeySystems, audioMedia = _ref.audioMedia, mainPlaylists = _ref.mainPlaylists;
  if (!player.eme.initializeMediaKeys) {
    return Promise.resolve();
  }
  var playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  var keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  var initializationFinishedPromises = [];
  var keySessionCreatedPromises = [];
  keySystemsOptionsArr.forEach(function(keySystemsOptions) {
    keySessionCreatedPromises.push(new Promise(function(resolve, reject) {
      player.tech_.one("keysessioncreated", resolve);
    }));
    initializationFinishedPromises.push(new Promise(function(resolve, reject) {
      player.eme.initializeMediaKeys({
        keySystems: keySystemsOptions
      }, function(err) {
        if (err) {
          reject(err);
          return;
        }
        resolve();
      });
    }));
  });
  return Promise.race([
    // If a session was previously created, these will all finish resolving without
    // creating a new session, otherwise it will take until the end of all license
    // requests, which is why the key session check is used (to make setup much faster).
    Promise.all(initializationFinishedPromises),
    // Once a single session is created, the browser knows DRM will be used.
    Promise.race(keySessionCreatedPromises)
  ]);
};
var setupEmeOptions = function setupEmeOptions2(_ref2) {
  var player = _ref2.player, sourceKeySystems = _ref2.sourceKeySystems, media = _ref2.media, audioMedia = _ref2.audioMedia;
  var sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  if (!sourceOptions) {
    return false;
  }
  player.currentSource().keySystems = sourceOptions;
  if (sourceOptions && !player.eme) {
    videojs.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin");
    return false;
  }
  return true;
};
var getVhsLocalStorage = function getVhsLocalStorage2() {
  if (!import_window6.default.localStorage) {
    return null;
  }
  var storedObject = import_window6.default.localStorage.getItem(LOCAL_STORAGE_KEY);
  if (!storedObject) {
    return null;
  }
  try {
    return JSON.parse(storedObject);
  } catch (e) {
    return null;
  }
};
var updateVhsLocalStorage = function updateVhsLocalStorage2(options) {
  if (!import_window6.default.localStorage) {
    return false;
  }
  var objectToStore = getVhsLocalStorage();
  objectToStore = objectToStore ? videojs.mergeOptions(objectToStore, options) : options;
  try {
    import_window6.default.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  } catch (e) {
    return false;
  }
  return objectToStore;
};
var expandDataUri = function expandDataUri2(dataUri) {
  if (dataUri.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,") === 0) {
    return JSON.parse(dataUri.substring(dataUri.indexOf(",") + 1));
  }
  return dataUri;
};
Vhs.supportsNativeHls = function() {
  if (!import_document.default || !import_document.default.createElement) {
    return false;
  }
  var video = import_document.default.createElement("video");
  if (!videojs.getTech("Html5").isSupported()) {
    return false;
  }
  var canPlay = [
    // Apple santioned
    "application/vnd.apple.mpegurl",
    // Apple sanctioned for backwards compatibility
    "audio/mpegurl",
    // Very common
    "audio/x-mpegurl",
    // Very common
    "application/x-mpegurl",
    // Included for completeness
    "video/x-mpegurl",
    "video/mpegurl",
    "application/mpegurl"
  ];
  return canPlay.some(function(canItPlay) {
    return /maybe|probably/i.test(video.canPlayType(canItPlay));
  });
}();
Vhs.supportsNativeDash = function() {
  if (!import_document.default || !import_document.default.createElement || !videojs.getTech("Html5").isSupported()) {
    return false;
  }
  return /maybe|probably/i.test(import_document.default.createElement("video").canPlayType("application/dash+xml"));
}();
Vhs.supportsTypeNatively = function(type2) {
  if (type2 === "hls") {
    return Vhs.supportsNativeHls;
  }
  if (type2 === "dash") {
    return Vhs.supportsNativeDash;
  }
  return false;
};
Vhs.isSupported = function() {
  return videojs.log.warn("HLS is no longer a tech. Please remove it from your player's techOrder.");
};
var Component2 = videojs.getComponent("Component");
var VhsHandler = /* @__PURE__ */ function(_Component) {
  _inheritsLoose(VhsHandler2, _Component);
  function VhsHandler2(source, tech, options) {
    var _this;
    _this = _Component.call(this, tech, videojs.mergeOptions(options.hls, options.vhs)) || this;
    if (options.hls && Object.keys(options.hls).length) {
      videojs.log.warn("Using hls options is deprecated. Please rename `hls` to `vhs` in your options object.");
    }
    if (typeof options.initialBandwidth === "number") {
      _this.options_.bandwidth = options.initialBandwidth;
    }
    _this.logger_ = logger2("VhsHandler");
    if (tech.options_ && tech.options_.playerId) {
      var _player = videojs(tech.options_.playerId);
      if (!_player.hasOwnProperty("hls")) {
        Object.defineProperty(_player, "hls", {
          get: function get7() {
            videojs.log.warn("player.hls is deprecated. Use player.tech().vhs instead.");
            tech.trigger({
              type: "usage",
              name: "hls-player-access"
            });
            return _assertThisInitialized(_this);
          },
          configurable: true
        });
      }
      if (!_player.hasOwnProperty("vhs")) {
        Object.defineProperty(_player, "vhs", {
          get: function get7() {
            videojs.log.warn("player.vhs is deprecated. Use player.tech().vhs instead.");
            tech.trigger({
              type: "usage",
              name: "vhs-player-access"
            });
            return _assertThisInitialized(_this);
          },
          configurable: true
        });
      }
      if (!_player.hasOwnProperty("dash")) {
        Object.defineProperty(_player, "dash", {
          get: function get7() {
            videojs.log.warn("player.dash is deprecated. Use player.tech().vhs instead.");
            return _assertThisInitialized(_this);
          },
          configurable: true
        });
      }
      _this.player_ = _player;
    }
    _this.tech_ = tech;
    _this.source_ = source;
    _this.stats = {};
    _this.ignoreNextSeekingEvent_ = false;
    _this.setOptions_();
    if (_this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
      tech.overrideNativeAudioTracks(true);
      tech.overrideNativeVideoTracks(true);
    } else if (_this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
      throw new Error("Overriding native HLS requires emulated tracks. See https://git.io/vMpjB");
    }
    _this.on(import_document.default, ["fullscreenchange", "webkitfullscreenchange", "mozfullscreenchange", "MSFullscreenChange"], function(event) {
      var fullscreenElement = import_document.default.fullscreenElement || import_document.default.webkitFullscreenElement || import_document.default.mozFullScreenElement || import_document.default.msFullscreenElement;
      if (fullscreenElement && fullscreenElement.contains(_this.tech_.el())) {
        _this.masterPlaylistController_.fastQualityChange_();
      } else {
        _this.masterPlaylistController_.checkABR_();
      }
    });
    _this.on(_this.tech_, "seeking", function() {
      if (this.ignoreNextSeekingEvent_) {
        this.ignoreNextSeekingEvent_ = false;
        return;
      }
      this.setCurrentTime(this.tech_.currentTime());
    });
    _this.on(_this.tech_, "error", function() {
      if (this.tech_.error() && this.masterPlaylistController_) {
        this.masterPlaylistController_.pauseLoading();
      }
    });
    _this.on(_this.tech_, "play", _this.play);
    return _this;
  }
  var _proto = VhsHandler2.prototype;
  _proto.setOptions_ = function setOptions_() {
    var _this2 = this;
    this.options_.withCredentials = this.options_.withCredentials || false;
    this.options_.handleManifestRedirects = this.options_.handleManifestRedirects === false ? false : true;
    this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
    this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
    this.options_.smoothQualityChange = this.options_.smoothQualityChange || false;
    this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== "undefined" ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
    this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
    this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
    this.options_.customTagParsers = this.options_.customTagParsers || [];
    this.options_.customTagMappers = this.options_.customTagMappers || [];
    this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
    if (typeof this.options_.blacklistDuration !== "number") {
      this.options_.blacklistDuration = 5 * 60;
    }
    if (typeof this.options_.bandwidth !== "number") {
      if (this.options_.useBandwidthFromLocalStorage) {
        var storedObject = getVhsLocalStorage();
        if (storedObject && storedObject.bandwidth) {
          this.options_.bandwidth = storedObject.bandwidth;
          this.tech_.trigger({
            type: "usage",
            name: "vhs-bandwidth-from-local-storage"
          });
          this.tech_.trigger({
            type: "usage",
            name: "hls-bandwidth-from-local-storage"
          });
        }
        if (storedObject && storedObject.throughput) {
          this.options_.throughput = storedObject.throughput;
          this.tech_.trigger({
            type: "usage",
            name: "vhs-throughput-from-local-storage"
          });
          this.tech_.trigger({
            type: "usage",
            name: "hls-throughput-from-local-storage"
          });
        }
      }
    }
    if (typeof this.options_.bandwidth !== "number") {
      this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
    }
    this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH;
    ["withCredentials", "useDevicePixelRatio", "limitRenditionByPlayerDimensions", "bandwidth", "smoothQualityChange", "customTagParsers", "customTagMappers", "handleManifestRedirects", "cacheEncryptionKeys", "playlistSelector", "initialPlaylistSelector", "experimentalBufferBasedABR", "liveRangeSafeTimeDelta", "experimentalLLHLS", "useNetworkInformationApi", "useDtsForTimestampOffset", "experimentalExactManifestTimings", "experimentalLeastPixelDiffSelector"].forEach(function(option) {
      if (typeof _this2.source_[option] !== "undefined") {
        _this2.options_[option] = _this2.source_[option];
      }
    });
    this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
    this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  };
  _proto.src = function src(_src, type2) {
    var _this3 = this;
    if (!_src) {
      return;
    }
    this.setOptions_();
    this.options_.src = expandDataUri(this.source_.src);
    this.options_.tech = this.tech_;
    this.options_.externVhs = Vhs;
    this.options_.sourceType = simpleTypeFromSourceType(type2);
    this.options_.seekTo = function(time) {
      _this3.tech_.setCurrentTime(time);
    };
    if (this.options_.smoothQualityChange) {
      videojs.log.warn("smoothQualityChange is deprecated and will be removed in the next major version");
    }
    this.masterPlaylistController_ = new MasterPlaylistController(this.options_);
    var playbackWatcherOptions = videojs.mergeOptions({
      liveRangeSafeTimeDelta: SAFE_TIME_DELTA
    }, this.options_, {
      seekable: function seekable3() {
        return _this3.seekable();
      },
      media: function media() {
        return _this3.masterPlaylistController_.media();
      },
      masterPlaylistController: this.masterPlaylistController_
    });
    this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
    this.masterPlaylistController_.on("error", function() {
      var player = videojs.players[_this3.tech_.options_.playerId];
      var error = _this3.masterPlaylistController_.error;
      if (typeof error === "object" && !error.code) {
        error.code = 3;
      } else if (typeof error === "string") {
        error = {
          message: error,
          code: 3
        };
      }
      player.error(error);
    });
    var defaultSelector = this.options_.experimentalBufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR;
    this.masterPlaylistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
    this.masterPlaylistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this);
    this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
    this.mediaSource = this.masterPlaylistController_.mediaSource;
    Object.defineProperties(this, {
      selectPlaylist: {
        get: function get7() {
          return this.masterPlaylistController_.selectPlaylist;
        },
        set: function set4(selectPlaylist) {
          this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
        }
      },
      throughput: {
        get: function get7() {
          return this.masterPlaylistController_.mainSegmentLoader_.throughput.rate;
        },
        set: function set4(throughput) {
          this.masterPlaylistController_.mainSegmentLoader_.throughput.rate = throughput;
          this.masterPlaylistController_.mainSegmentLoader_.throughput.count = 1;
        }
      },
      bandwidth: {
        get: function get7() {
          var playerBandwidthEst = this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
          var networkInformation = import_window6.default.navigator.connection || import_window6.default.navigator.mozConnection || import_window6.default.navigator.webkitConnection;
          var tenMbpsAsBitsPerSecond = 1e7;
          if (this.options_.useNetworkInformationApi && networkInformation) {
            var networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1e3 * 1e3;
            if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
              playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
            } else {
              playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
            }
          }
          return playerBandwidthEst;
        },
        set: function set4(bandwidth2) {
          this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth2;
          this.masterPlaylistController_.mainSegmentLoader_.throughput = {
            rate: 0,
            count: 0
          };
        }
      },
      /**
       * `systemBandwidth` is a combination of two serial processes bit-rates. The first
       * is the network bitrate provided by `bandwidth` and the second is the bitrate of
       * the entire process after that - decryption, transmuxing, and appending - provided
       * by `throughput`.
       *
       * Since the two process are serial, the overall system bandwidth is given by:
       *   sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
       */
      systemBandwidth: {
        get: function get7() {
          var invBandwidth = 1 / (this.bandwidth || 1);
          var invThroughput;
          if (this.throughput > 0) {
            invThroughput = 1 / this.throughput;
          } else {
            invThroughput = 0;
          }
          var systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
          return systemBitrate;
        },
        set: function set4() {
          videojs.log.error('The "systemBandwidth" property is read-only');
        }
      }
    });
    if (this.options_.bandwidth) {
      this.bandwidth = this.options_.bandwidth;
    }
    if (this.options_.throughput) {
      this.throughput = this.options_.throughput;
    }
    Object.defineProperties(this.stats, {
      bandwidth: {
        get: function get7() {
          return _this3.bandwidth || 0;
        },
        enumerable: true
      },
      mediaRequests: {
        get: function get7() {
          return _this3.masterPlaylistController_.mediaRequests_() || 0;
        },
        enumerable: true
      },
      mediaRequestsAborted: {
        get: function get7() {
          return _this3.masterPlaylistController_.mediaRequestsAborted_() || 0;
        },
        enumerable: true
      },
      mediaRequestsTimedout: {
        get: function get7() {
          return _this3.masterPlaylistController_.mediaRequestsTimedout_() || 0;
        },
        enumerable: true
      },
      mediaRequestsErrored: {
        get: function get7() {
          return _this3.masterPlaylistController_.mediaRequestsErrored_() || 0;
        },
        enumerable: true
      },
      mediaTransferDuration: {
        get: function get7() {
          return _this3.masterPlaylistController_.mediaTransferDuration_() || 0;
        },
        enumerable: true
      },
      mediaBytesTransferred: {
        get: function get7() {
          return _this3.masterPlaylistController_.mediaBytesTransferred_() || 0;
        },
        enumerable: true
      },
      mediaSecondsLoaded: {
        get: function get7() {
          return _this3.masterPlaylistController_.mediaSecondsLoaded_() || 0;
        },
        enumerable: true
      },
      mediaAppends: {
        get: function get7() {
          return _this3.masterPlaylistController_.mediaAppends_() || 0;
        },
        enumerable: true
      },
      mainAppendsToLoadedData: {
        get: function get7() {
          return _this3.masterPlaylistController_.mainAppendsToLoadedData_() || 0;
        },
        enumerable: true
      },
      audioAppendsToLoadedData: {
        get: function get7() {
          return _this3.masterPlaylistController_.audioAppendsToLoadedData_() || 0;
        },
        enumerable: true
      },
      appendsToLoadedData: {
        get: function get7() {
          return _this3.masterPlaylistController_.appendsToLoadedData_() || 0;
        },
        enumerable: true
      },
      timeToLoadedData: {
        get: function get7() {
          return _this3.masterPlaylistController_.timeToLoadedData_() || 0;
        },
        enumerable: true
      },
      buffered: {
        get: function get7() {
          return timeRangesToArray(_this3.tech_.buffered());
        },
        enumerable: true
      },
      currentTime: {
        get: function get7() {
          return _this3.tech_.currentTime();
        },
        enumerable: true
      },
      currentSource: {
        get: function get7() {
          return _this3.tech_.currentSource_;
        },
        enumerable: true
      },
      currentTech: {
        get: function get7() {
          return _this3.tech_.name_;
        },
        enumerable: true
      },
      duration: {
        get: function get7() {
          return _this3.tech_.duration();
        },
        enumerable: true
      },
      master: {
        get: function get7() {
          return _this3.playlists.master;
        },
        enumerable: true
      },
      playerDimensions: {
        get: function get7() {
          return _this3.tech_.currentDimensions();
        },
        enumerable: true
      },
      seekable: {
        get: function get7() {
          return timeRangesToArray(_this3.tech_.seekable());
        },
        enumerable: true
      },
      timestamp: {
        get: function get7() {
          return Date.now();
        },
        enumerable: true
      },
      videoPlaybackQuality: {
        get: function get7() {
          return _this3.tech_.getVideoPlaybackQuality();
        },
        enumerable: true
      }
    });
    this.tech_.one("canplay", this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));
    this.tech_.on("bandwidthupdate", function() {
      if (_this3.options_.useBandwidthFromLocalStorage) {
        updateVhsLocalStorage({
          bandwidth: _this3.bandwidth,
          throughput: Math.round(_this3.throughput)
        });
      }
    });
    this.masterPlaylistController_.on("selectedinitialmedia", function() {
      renditionSelectionMixin(_this3);
    });
    this.masterPlaylistController_.sourceUpdater_.on("createdsourcebuffers", function() {
      _this3.setupEme_();
    });
    this.on(this.masterPlaylistController_, "progress", function() {
      this.tech_.trigger("progress");
    });
    this.on(this.masterPlaylistController_, "firstplay", function() {
      this.ignoreNextSeekingEvent_ = true;
    });
    this.setupQualityLevels_();
    if (!this.tech_.el()) {
      return;
    }
    this.mediaSourceUrl_ = import_window6.default.URL.createObjectURL(this.masterPlaylistController_.mediaSource);
    this.tech_.src(this.mediaSourceUrl_);
  };
  _proto.createKeySessions_ = function createKeySessions_() {
    var _this4 = this;
    var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
    this.logger_("waiting for EME key session creation");
    waitForKeySessionCreation({
      player: this.player_,
      sourceKeySystems: this.source_.keySystems,
      audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
      mainPlaylists: this.playlists.master.playlists
    }).then(function() {
      _this4.logger_("created EME key session");
      _this4.masterPlaylistController_.sourceUpdater_.initializedEme();
    })["catch"](function(err) {
      _this4.logger_("error while creating EME key session", err);
      _this4.player_.error({
        message: "Failed to initialize media keys for EME",
        code: 3
      });
    });
  };
  _proto.handleWaitingForKey_ = function handleWaitingForKey_() {
    this.logger_("waitingforkey fired, attempting to create any new key sessions");
    this.createKeySessions_();
  };
  _proto.setupEme_ = function setupEme_() {
    var _this5 = this;
    var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
    var didSetupEmeOptions = setupEmeOptions({
      player: this.player_,
      sourceKeySystems: this.source_.keySystems,
      media: this.playlists.media(),
      audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
    });
    this.player_.tech_.on("keystatuschange", function(e) {
      if (e.status !== "output-restricted") {
        return;
      }
      var masterPlaylist = _this5.masterPlaylistController_.master();
      if (!masterPlaylist || !masterPlaylist.playlists) {
        return;
      }
      var excludedHDPlaylists = [];
      masterPlaylist.playlists.forEach(function(playlist) {
        if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
          if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
            playlist.excludeUntil = Infinity;
            excludedHDPlaylists.push(playlist);
          }
        }
      });
      if (excludedHDPlaylists.length) {
        var _videojs$log;
        (_videojs$log = videojs.log).warn.apply(_videojs$log, ['DRM keystatus changed to "output-restricted." Removing the following HD playlists that will most likely fail to play and clearing the buffer. This may be due to HDCP restrictions on the stream and the capabilities of the current device.'].concat(excludedHDPlaylists));
        _this5.masterPlaylistController_.fastQualityChange_();
      }
    });
    this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
    this.player_.tech_.on("waitingforkey", this.handleWaitingForKey_);
    if (videojs.browser.IE_VERSION === 11 || !didSetupEmeOptions) {
      this.masterPlaylistController_.sourceUpdater_.initializedEme();
      return;
    }
    this.createKeySessions_();
  };
  _proto.setupQualityLevels_ = function setupQualityLevels_() {
    var _this6 = this;
    var player = videojs.players[this.tech_.options_.playerId];
    if (!player || !player.qualityLevels || this.qualityLevels_) {
      return;
    }
    this.qualityLevels_ = player.qualityLevels();
    this.masterPlaylistController_.on("selectedinitialmedia", function() {
      handleVhsLoadedMetadata(_this6.qualityLevels_, _this6);
    });
    this.playlists.on("mediachange", function() {
      handleVhsMediaChange(_this6.qualityLevels_, _this6.playlists);
    });
  };
  VhsHandler2.version = function version$52() {
    return {
      "@videojs/http-streaming": version$4,
      "mux.js": version$3,
      "mpd-parser": version$2,
      "m3u8-parser": version$1,
      "aes-decrypter": version2
    };
  };
  _proto.version = function version6() {
    return this.constructor.version();
  };
  _proto.canChangeType = function canChangeType() {
    return SourceUpdater.canChangeType();
  };
  _proto.play = function play() {
    this.masterPlaylistController_.play();
  };
  _proto.setCurrentTime = function setCurrentTime(currentTime) {
    this.masterPlaylistController_.setCurrentTime(currentTime);
  };
  _proto.duration = function duration5() {
    return this.masterPlaylistController_.duration();
  };
  _proto.seekable = function seekable3() {
    return this.masterPlaylistController_.seekable();
  };
  _proto.dispose = function dispose() {
    if (this.playbackWatcher_) {
      this.playbackWatcher_.dispose();
    }
    if (this.masterPlaylistController_) {
      this.masterPlaylistController_.dispose();
    }
    if (this.qualityLevels_) {
      this.qualityLevels_.dispose();
    }
    if (this.player_) {
      delete this.player_.vhs;
      delete this.player_.dash;
      delete this.player_.hls;
    }
    if (this.tech_ && this.tech_.vhs) {
      delete this.tech_.vhs;
    }
    if (this.tech_) {
      delete this.tech_.hls;
    }
    if (this.mediaSourceUrl_ && import_window6.default.URL.revokeObjectURL) {
      import_window6.default.URL.revokeObjectURL(this.mediaSourceUrl_);
      this.mediaSourceUrl_ = null;
    }
    if (this.tech_) {
      this.tech_.off("waitingforkey", this.handleWaitingForKey_);
    }
    _Component.prototype.dispose.call(this);
  };
  _proto.convertToProgramTime = function convertToProgramTime(time, callback2) {
    return getProgramTime({
      playlist: this.masterPlaylistController_.media(),
      time,
      callback: callback2
    });
  };
  _proto.seekToProgramTime = function seekToProgramTime$1(programTime, callback2, pauseAfterSeek, retryCount) {
    if (pauseAfterSeek === void 0) {
      pauseAfterSeek = true;
    }
    if (retryCount === void 0) {
      retryCount = 2;
    }
    return seekToProgramTime({
      programTime,
      playlist: this.masterPlaylistController_.media(),
      retryCount,
      pauseAfterSeek,
      seekTo: this.options_.seekTo,
      tech: this.options_.tech,
      callback: callback2
    });
  };
  return VhsHandler2;
}(Component2);
var VhsSourceHandler = {
  name: "videojs-http-streaming",
  VERSION: version$4,
  canHandleSource: function canHandleSource(srcObj, options) {
    if (options === void 0) {
      options = {};
    }
    var localOptions = videojs.mergeOptions(videojs.options, options);
    return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  },
  handleSource: function handleSource(source, tech, options) {
    if (options === void 0) {
      options = {};
    }
    var localOptions = videojs.mergeOptions(videojs.options, options);
    tech.vhs = new VhsHandler(source, tech, localOptions);
    if (!videojs.hasOwnProperty("hls")) {
      Object.defineProperty(tech, "hls", {
        get: function get7() {
          videojs.log.warn("player.tech().hls is deprecated. Use player.tech().vhs instead.");
          return tech.vhs;
        },
        configurable: true
      });
    }
    tech.vhs.xhr = xhrFactory();
    tech.vhs.src(source.src, source.type);
    return tech.vhs;
  },
  canPlayType: function canPlayType2(type2, options) {
    if (options === void 0) {
      options = {};
    }
    var _videojs$mergeOptions = videojs.mergeOptions(videojs.options, options), _videojs$mergeOptions2 = _videojs$mergeOptions.vhs;
    _videojs$mergeOptions2 = _videojs$mergeOptions2 === void 0 ? {} : _videojs$mergeOptions2;
    var _videojs$mergeOptions3 = _videojs$mergeOptions2.overrideNative, overrideNative = _videojs$mergeOptions3 === void 0 ? !videojs.browser.IS_ANY_SAFARI : _videojs$mergeOptions3, _videojs$mergeOptions4 = _videojs$mergeOptions.hls;
    _videojs$mergeOptions4 = _videojs$mergeOptions4 === void 0 ? {} : _videojs$mergeOptions4;
    var _videojs$mergeOptions5 = _videojs$mergeOptions4.overrideNative, legacyOverrideNative = _videojs$mergeOptions5 === void 0 ? false : _videojs$mergeOptions5;
    var supportedType = simpleTypeFromSourceType(type2);
    var canUseMsePlayback = supportedType && (!Vhs.supportsTypeNatively(supportedType) || legacyOverrideNative || overrideNative);
    return canUseMsePlayback ? "maybe" : "";
  }
};
var supportsNativeMediaSources = function supportsNativeMediaSources2() {
  return browserSupportsCodec("avc1.4d400d,mp4a.40.2");
};
if (supportsNativeMediaSources()) {
  videojs.getTech("Html5").registerSourceHandler(VhsSourceHandler, 0);
}
videojs.VhsHandler = VhsHandler;
Object.defineProperty(videojs, "HlsHandler", {
  get: function get4() {
    videojs.log.warn("videojs.HlsHandler is deprecated. Use videojs.VhsHandler instead.");
    return VhsHandler;
  },
  configurable: true
});
videojs.VhsSourceHandler = VhsSourceHandler;
Object.defineProperty(videojs, "HlsSourceHandler", {
  get: function get5() {
    videojs.log.warn("videojs.HlsSourceHandler is deprecated. Use videojs.VhsSourceHandler instead.");
    return VhsSourceHandler;
  },
  configurable: true
});
videojs.Vhs = Vhs;
Object.defineProperty(videojs, "Hls", {
  get: function get6() {
    videojs.log.warn("videojs.Hls is deprecated. Use videojs.Vhs instead.");
    return Vhs;
  },
  configurable: true
});
if (!videojs.use) {
  videojs.registerComponent("Hls", Vhs);
  videojs.registerComponent("Vhs", Vhs);
}
videojs.options.vhs = videojs.options.vhs || {};
videojs.options.hls = videojs.options.hls || {};
if (!videojs.getPlugin || !videojs.getPlugin("reloadSourceOnError")) {
  registerPlugin3 = videojs.registerPlugin || videojs.plugin;
  registerPlugin3("reloadSourceOnError", reloadSourceOnError);
}
var registerPlugin3;
var video_es_default = videojs;

// node_modules/.pnpm/@yangkghjh+videojs-aspect-ratio-panel@0.0.1/node_modules/@yangkghjh/videojs-aspect-ratio-panel/dist/videojs-aspect-ratio-panel.es.js
function _inheritsLoose2(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  subClass.__proto__ = superClass;
}
function _assertThisInitialized2(self2) {
  if (self2 === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self2;
}
var version3 = "0.0.1";
var MenuButton2 = video_es_default.getComponent("MenuButton");
var ResizerButton = /* @__PURE__ */ function(_MenuButton) {
  _inheritsLoose2(ResizerButton2, _MenuButton);
  function ResizerButton2(player, options) {
    var _this;
    _this = _MenuButton.call(this, player, {
      name: "ResizerButton"
    }) || this;
    MenuButton2.apply(_assertThisInitialized2(_this), arguments);
    _this.controlText(player.localize("Aspect Ratio"));
    return _this;
  }
  var _proto = ResizerButton2.prototype;
  _proto.createEl = function createEl2() {
    return video_es_default.dom.createEl("div", {
      className: "vjs-menu-button vjs-menu-button-popup vjs-control vjs-button"
    });
  };
  _proto.buildCSSClass = function buildCSSClass() {
    return MenuButton2.prototype.buildCSSClass.call(this) + " vjs-icon-cog";
  };
  _proto.update = function update() {
    return MenuButton2.prototype.update.call(this);
  };
  _proto.handleClick = function handleClick() {
    this.player().getChild("ResizerPanel").toggleClass("vjs-hidden");
  };
  return ResizerButton2;
}(MenuButton2);
var Component3 = video_es_default.getComponent("Component");
var ResizerPanel = /* @__PURE__ */ function(_Component) {
  _inheritsLoose2(ResizerPanel2, _Component);
  function ResizerPanel2(player, options) {
    var _this;
    _this = _Component.call(this, player, options) || this;
    Component3.apply(_assertThisInitialized2(_this), arguments);
    _this.aspectRadio = "origin";
    _this.percent = 100;
    _this.radioWidth = 1;
    _this.radioHeight = 1;
    _this.currentHeight = _this.player().currentHeight();
    _this.currentWidth = _this.player().currentWidth();
    var el = _this.el();
    el.childNodes[1].childNodes[1].onclick = function() {
      _this.toggleClass("vjs-hidden");
    };
    window.addEventListener("resize", function() {
      if (_this.currentHeight != _this.player().currentHeight() || _this.currentWidth != _this.player().currentWidth()) {
        _this.currentHeight = _this.player().currentHeight();
        _this.currentWidth = _this.player().currentWidth();
        _this.resize();
      }
    });
    el.onmouseup = function() {
      el.onmousemove = null;
    };
    var scroll = el.childNodes[1].childNodes[5].childNodes[1].childNodes[3];
    _this.setScrollFunc(el, scroll, function(data) {
      _this.setPercent(data);
    });
    _this.player().on("play", function() {
      _this.resize();
    });
    var radiosDiv = el.childNodes[1].childNodes[5].childNodes[3].childNodes;
    var radios = [radiosDiv[1], radiosDiv[5], radiosDiv[9], radiosDiv[13]];
    var prev = "origin";
    for (var i = 0; i < radios.length; i++) {
      radios[i].onchange = function(event) {
        if (event.target.value !== prev) {
          prev = event.target.value;
          _this.setAspectRadio(event.target.value);
        }
      };
    }
    var resetDiv = el.childNodes[1].childNodes[5].childNodes[5].childNodes[1];
    resetDiv.onclick = function(event) {
      radios[0].checked = true;
      _this.reset();
    };
    return _this;
  }
  var _proto = ResizerPanel2.prototype;
  _proto.setAspectRadio = function setAspectRadio(radio) {
    switch (radio) {
      case "origin":
        this.aspectRadio = "origin";
        break;
      case "fill":
        this.aspectRadio = "fill";
        break;
      case "16:9":
        this.aspectRadio = "16:9";
        this.radioWidth = 16;
        this.radioHeight = 9;
        break;
      case "4:3":
        this.aspectRadio = "4:3";
        this.radioWidth = 4;
        this.radioHeight = 3;
        break;
    }
    this.resize();
  };
  _proto.setPercent = function setPercent(percent) {
    this.percent = percent;
    this.resize();
  };
  _proto.reset = function reset3() {
    this.player().tech_.el().style.objectFit = "contain";
    this.aspectRadio = "origin";
    this.percent = 100;
    var scroll = this.el().childNodes[1].childNodes[5].childNodes[1].childNodes[3];
    scroll.childNodes[1].style.left = "255px";
    scroll.childNodes[3].style.width = "255px";
    this.resize();
  };
  _proto.resize = function resize() {
    if (this.aspectRadio != "origin") {
      this.player().tech_.el().style.objectFit = "fill";
    } else {
      this.player().tech_.el().style.objectFit = "contain";
    }
    if (this.aspectRadio == "origin" || this.aspectRadio == "fill") {
      var _w = this.currentWidth * (100 - this.percent) / 100 / 2;
      var _h = this.currentHeight * (100 - this.percent) / 100 / 2;
      this.setPadding(_w, _h);
      return;
    }
    var playerRadio = this.currentWidth / this.currentHeight;
    var width2 = this.currentWidth;
    var height2 = width2 * this.radioHeight / this.radioWidth;
    if (playerRadio > this.radioWidth / this.radioHeight) {
      height2 = this.currentHeight;
      width2 = height2 * this.radioWidth / this.radioHeight;
    }
    var w = (this.currentWidth - width2 * this.percent / 100) / 2;
    var h = (this.currentHeight - height2 * this.percent / 100) / 2;
    this.setPadding(w, h);
  };
  _proto.setPadding = function setPadding(w, h) {
    if (w < 0) {
      w = 0;
    }
    this.player().tech_.el().style.paddingLeft = w + "px";
    this.player().tech_.el().style.paddingRight = w + "px";
    if (h < 0) {
      h = 0;
    }
    this.player().tech_.el().style.paddingTop = h + "px";
    this.player().tech_.el().style.paddingBottom = h + "px";
  };
  _proto.setScrollFunc = function setScrollFunc(scrollDiv, scrollDom, callback2) {
    var bar = scrollDom.childNodes[1];
    var mask = scrollDom.childNodes[3];
    var barleft = 0;
    bar.onmousedown = function(e) {
      var event = e || window.event;
      var leftVal = event.clientX - this.offsetLeft;
      var that = this;
      scrollDiv.onmousemove = function(e2) {
        var event2 = e2 || window.event;
        barleft = event2.clientX - leftVal;
        if (barleft < 0) barleft = 0;
        else if (barleft > 255) barleft = 255;
        mask.style.width = barleft + "px";
        that.style.left = barleft + "px";
        callback2(parseInt(barleft / 255 * 100));
        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
      };
    };
  };
  _proto.createEl = function createEl2() {
    return video_es_default.dom.createEl("div", {
      className: "vjs-resizer-modal vjs-hidden",
      innerHTML: '\n        <div class="vjs-resizer-modal-content">\n        <span class="vjs-resizer-modal-close">&times;</span>\n          <div class="vjs-resizer-modal-title">Aspect Ratio</div>\n          <div class="vjs-resizer-wrap">\n            <div class="vjs-resizer-size">\n              <span class="size-title">Size</span>\n              <div class="size-scroll" id="size-scroll">\n                <div class="size-scroll-bar"></div>\n                <div class="size-scroll-mask"></div>\n              </div>\n            </div>\n            <div class="radios">\n              Ratio\n              <input type="radio" name="radio" id="origin" value="origin" checked >\n              <label for="origin">Default</label>\n              <input type="radio" name="radio" id="4:3" value="4:3">\n              <label for="4:3">4:3</label>\n              <input type="radio" name="radio" id="16:9" value="16:9">\n              <label for="16:9">16:9</label>\n              <input type="radio" name="radio" id="fill" value="fill">\n              <label for="fill">Full</label>\n            </div>\n            <ul style="clear:both">\n                <li id="vjs-resizer-reset">Reset</li>\n            </ul>\n          </div>\n        </div>\n        '
    });
  };
  return ResizerPanel2;
}(Component3);
var Plugin2 = video_es_default.getPlugin("plugin");
var defaults3 = {};
var AspectRatioPanel = /* @__PURE__ */ function(_Plugin) {
  _inheritsLoose2(AspectRatioPanel2, _Plugin);
  function AspectRatioPanel2(player, options) {
    var _this;
    _this = _Plugin.call(this, player) || this;
    _this.options = video_es_default.mergeOptions(defaults3, options);
    _this.player.ready(function() {
      _this.player.addClass("vjs-aspect-ratio-panel");
      if (player.techName_ != "Html5") {
        return false;
      }
      player.on(["loadedmetadata"], function(e) {
        if (player.aspect_ratio_initialized == "undefined" || player.aspect_ratio_initialized == true) ;
        else {
          player.aspect_ratio_initialized = true;
          var controlBar = player.controlBar;
          var fullscreenToggle = controlBar.getChild("fullscreenToggle").el();
          controlBar.el().insertBefore(controlBar.addChild("ResizerButton").el(), fullscreenToggle);
          player.addChild("ResizerPanel");
        }
      });
    });
    video_es_default.registerComponent("ResizerButton", ResizerButton);
    video_es_default.registerComponent("ResizerPanel", ResizerPanel);
    return _this;
  }
  return AspectRatioPanel2;
}(Plugin2);
AspectRatioPanel.defaultState = {};
AspectRatioPanel.VERSION = version3;
video_es_default.registerPlugin("aspectRatioPanel", AspectRatioPanel);

// node_modules/.pnpm/videojs-contrib-quality-levels@2.2.0_video.js@7.20.3/node_modules/videojs-contrib-quality-levels/dist/videojs-contrib-quality-levels.es.js
function _inheritsLoose3(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  subClass.__proto__ = superClass;
}
function _assertThisInitialized3(self2) {
  if (self2 === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self2;
}
var QualityLevel = (
  /**
   * Creates a QualityLevel
   *
   * @param {Representation|Object} representation The representation of the quality level
   * @param {string}   representation.id        Unique id of the QualityLevel
   * @param {number=}  representation.width     Resolution width of the QualityLevel
   * @param {number=}  representation.height    Resolution height of the QualityLevel
   * @param {number}   representation.bandwidth Bitrate of the QualityLevel
   * @param {number=}  representation.frameRate Frame-rate of the QualityLevel
   * @param {Function} representation.enabled   Callback to enable/disable QualityLevel
   */
  function QualityLevel2(representation) {
    var level = this;
    level.id = representation.id;
    level.label = level.id;
    level.width = representation.width;
    level.height = representation.height;
    level.bitrate = representation.bandwidth;
    level.frameRate = representation.frameRate;
    level.enabled_ = representation.enabled;
    Object.defineProperty(level, "enabled", {
      /**
       * Get whether the QualityLevel is enabled.
       *
       * @return {boolean} True if the QualityLevel is enabled.
       */
      get: function get7() {
        return level.enabled_();
      },
      /**
       * Enable or disable the QualityLevel.
       *
       * @param {boolean} enable true to enable QualityLevel, false to disable.
       */
      set: function set4(enable) {
        level.enabled_(enable);
      }
    });
    return level;
  }
);
var QualityLevelList = /* @__PURE__ */ function(_videojs$EventTarget) {
  _inheritsLoose3(QualityLevelList2, _videojs$EventTarget);
  function QualityLevelList2() {
    var _this;
    _this = _videojs$EventTarget.call(this) || this;
    var list = _assertThisInitialized3(_assertThisInitialized3(_this));
    list.levels_ = [];
    list.selectedIndex_ = -1;
    Object.defineProperty(list, "selectedIndex", {
      get: function get7() {
        return list.selectedIndex_;
      }
    });
    Object.defineProperty(list, "length", {
      get: function get7() {
        return list.levels_.length;
      }
    });
    return list || _assertThisInitialized3(_this);
  }
  var _proto = QualityLevelList2.prototype;
  _proto.addQualityLevel = function addQualityLevel(representation) {
    var qualityLevel = this.getQualityLevelById(representation.id);
    if (qualityLevel) {
      return qualityLevel;
    }
    var index = this.levels_.length;
    qualityLevel = new QualityLevel(representation);
    if (!("" + index in this)) {
      Object.defineProperty(this, index, {
        get: function get7() {
          return this.levels_[index];
        }
      });
    }
    this.levels_.push(qualityLevel);
    this.trigger({
      qualityLevel,
      type: "addqualitylevel"
    });
    return qualityLevel;
  };
  _proto.removeQualityLevel = function removeQualityLevel(qualityLevel) {
    var removed = null;
    for (var i = 0, l = this.length; i < l; i++) {
      if (this[i] === qualityLevel) {
        removed = this.levels_.splice(i, 1)[0];
        if (this.selectedIndex_ === i) {
          this.selectedIndex_ = -1;
        } else if (this.selectedIndex_ > i) {
          this.selectedIndex_--;
        }
        break;
      }
    }
    if (removed) {
      this.trigger({
        qualityLevel,
        type: "removequalitylevel"
      });
    }
    return removed;
  };
  _proto.getQualityLevelById = function getQualityLevelById(id) {
    for (var i = 0, l = this.length; i < l; i++) {
      var level = this[i];
      if (level.id === id) {
        return level;
      }
    }
    return null;
  };
  _proto.dispose = function dispose() {
    this.selectedIndex_ = -1;
    this.levels_.length = 0;
  };
  return QualityLevelList2;
}(video_es_default.EventTarget);
QualityLevelList.prototype.allowedEvents_ = {
  change: "change",
  addqualitylevel: "addqualitylevel",
  removequalitylevel: "removequalitylevel"
};
for (event in QualityLevelList.prototype.allowedEvents_) {
  QualityLevelList.prototype["on" + event] = null;
}
var event;
var version4 = "2.2.0";
var registerPlugin = video_es_default.registerPlugin || video_es_default.plugin;
var initPlugin3 = function initPlugin4(player, options) {
  var originalPluginFn = player.qualityLevels;
  var qualityLevelList = new QualityLevelList();
  var disposeHandler = function disposeHandler2() {
    qualityLevelList.dispose();
    player.qualityLevels = originalPluginFn;
    player.off("dispose", disposeHandler2);
  };
  player.on("dispose", disposeHandler);
  player.qualityLevels = function() {
    return qualityLevelList;
  };
  player.qualityLevels.VERSION = version4;
  return qualityLevelList;
};
var qualityLevels = function qualityLevels2(options) {
  return initPlugin3(this, video_es_default.mergeOptions({}, options));
};
registerPlugin("qualityLevels", qualityLevels);
qualityLevels.VERSION = version4;

// node_modules/.pnpm/videojs-hls-quality-selector@1.1.4/node_modules/videojs-hls-quality-selector/dist/videojs-hls-quality-selector.es.js
var version5 = "1.1.4";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
  return typeof obj;
} : function(obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var asyncGenerator = function() {
  function AwaitValue(value) {
    this.value = value;
  }
  function AsyncGenerator(gen) {
    var front, back;
    function send(key, arg) {
      return new Promise(function(resolve, reject) {
        var request = {
          key,
          arg,
          resolve,
          reject,
          next: null
        };
        if (back) {
          back = back.next = request;
        } else {
          front = back = request;
          resume(key, arg);
        }
      });
    }
    function resume(key, arg) {
      try {
        var result = gen[key](arg);
        var value = result.value;
        if (value instanceof AwaitValue) {
          Promise.resolve(value.value).then(function(arg2) {
            resume("next", arg2);
          }, function(arg2) {
            resume("throw", arg2);
          });
        } else {
          settle(result.done ? "return" : "normal", result.value);
        }
      } catch (err) {
        settle("throw", err);
      }
    }
    function settle(type2, value) {
      switch (type2) {
        case "return":
          front.resolve({
            value,
            done: true
          });
          break;
        case "throw":
          front.reject(value);
          break;
        default:
          front.resolve({
            value,
            done: false
          });
          break;
      }
      front = front.next;
      if (front) {
        resume(front.key, front.arg);
      } else {
        back = null;
      }
    }
    this._invoke = send;
    if (typeof gen.return !== "function") {
      this.return = void 0;
    }
  }
  if (typeof Symbol === "function" && Symbol.asyncIterator) {
    AsyncGenerator.prototype[Symbol.asyncIterator] = function() {
      return this;
    };
  }
  AsyncGenerator.prototype.next = function(arg) {
    return this._invoke("next", arg);
  };
  AsyncGenerator.prototype.throw = function(arg) {
    return this._invoke("throw", arg);
  };
  AsyncGenerator.prototype.return = function(arg) {
    return this._invoke("return", arg);
  };
  return {
    wrap: function(fn) {
      return function() {
        return new AsyncGenerator(fn.apply(this, arguments));
      };
    },
    await: function(value) {
      return new AwaitValue(value);
    }
  };
}();
var classCallCheck = function(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
};
var inherits = function(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function(self2, call) {
  if (!self2) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return call && (typeof call === "object" || typeof call === "function") ? call : self2;
};
var VideoJsButtonClass = video_es_default.getComponent("MenuButton");
var VideoJsMenuClass = video_es_default.getComponent("Menu");
var VideoJsComponent = video_es_default.getComponent("Component");
var Dom2 = video_es_default.dom;
function toTitleCase4(string) {
  if (typeof string !== "string") {
    return string;
  }
  return string.charAt(0).toUpperCase() + string.slice(1);
}
var ConcreteButton = function(_VideoJsButtonClass) {
  inherits(ConcreteButton2, _VideoJsButtonClass);
  function ConcreteButton2(player) {
    classCallCheck(this, ConcreteButton2);
    return possibleConstructorReturn(this, _VideoJsButtonClass.call(this, player, {
      title: player.localize("Quality"),
      name: "QualityButton"
    }));
  }
  ConcreteButton2.prototype.createItems = function createItems() {
    return [];
  };
  ConcreteButton2.prototype.createMenu = function createMenu() {
    var menu = new VideoJsMenuClass(this.player_, {
      menuButton: this
    });
    this.hideThreshold_ = 0;
    if (this.options_.title) {
      var titleEl = Dom2.createEl("li", {
        className: "vjs-menu-title",
        innerHTML: toTitleCase4(this.options_.title),
        tabIndex: -1
      });
      var titleComponent = new VideoJsComponent(this.player_, {
        el: titleEl
      });
      this.hideThreshold_ += 1;
      menu.addItem(titleComponent);
    }
    this.items = this.createItems();
    if (this.items) {
      for (var i = 0; i < this.items.length; i++) {
        menu.addItem(this.items[i]);
      }
    }
    return menu;
  };
  return ConcreteButton2;
}(VideoJsButtonClass);
var VideoJsMenuItemClass = video_es_default.getComponent("MenuItem");
var ConcreteMenuItem = function(_VideoJsMenuItemClass) {
  inherits(ConcreteMenuItem2, _VideoJsMenuItemClass);
  function ConcreteMenuItem2(player, item, qualityButton, plugin) {
    classCallCheck(this, ConcreteMenuItem2);
    var _this = possibleConstructorReturn(this, _VideoJsMenuItemClass.call(this, player, {
      label: item.label,
      selectable: true,
      selected: item.selected || false
    }));
    _this.item = item;
    _this.qualityButton = qualityButton;
    _this.plugin = plugin;
    return _this;
  }
  ConcreteMenuItem2.prototype.handleClick = function handleClick() {
    for (var i = 0; i < this.qualityButton.items.length; ++i) {
      this.qualityButton.items[i].selected(false);
    }
    this.plugin.setQuality(this.item.value);
    this.selected(true);
  };
  return ConcreteMenuItem2;
}(VideoJsMenuItemClass);
var defaults4 = {};
var registerPlugin2 = video_es_default.registerPlugin || video_es_default.plugin;
var HlsQualitySelectorPlugin = function() {
  function HlsQualitySelectorPlugin2(player, options) {
    classCallCheck(this, HlsQualitySelectorPlugin2);
    this.player = player;
    this.config = options;
    if (this.player.qualityLevels && this.getHls()) {
      this.createQualityButton();
      this.bindPlayerEvents();
    }
  }
  HlsQualitySelectorPlugin2.prototype.getHls = function getHls() {
    return this.player.tech({
      IWillNotUseThisInPlugins: true
    }).hls;
  };
  HlsQualitySelectorPlugin2.prototype.bindPlayerEvents = function bindPlayerEvents() {
    this.player.qualityLevels().on("addqualitylevel", this.onAddQualityLevel.bind(this));
  };
  HlsQualitySelectorPlugin2.prototype.createQualityButton = function createQualityButton() {
    var player = this.player;
    this._qualityButton = new ConcreteButton(player);
    var placementIndex = player.controlBar.children().length - 2;
    var concreteButtonInstance = player.controlBar.addChild(this._qualityButton, {
      componentClass: "qualitySelector"
    }, this.config.placementIndex || placementIndex);
    concreteButtonInstance.addClass("vjs-quality-selector");
    if (!this.config.displayCurrentQuality) {
      var icon = " " + (this.config.vjsIconClass || "vjs-icon-hd");
      concreteButtonInstance.menuButton_.$(".vjs-icon-placeholder").className += icon;
    } else {
      this.setButtonInnerText("auto");
    }
    concreteButtonInstance.removeClass("vjs-hidden");
  };
  HlsQualitySelectorPlugin2.prototype.setButtonInnerText = function setButtonInnerText(text) {
    this._qualityButton.menuButton_.$(".vjs-icon-placeholder").innerHTML = text;
  };
  HlsQualitySelectorPlugin2.prototype.getQualityMenuItem = function getQualityMenuItem(item) {
    var player = this.player;
    return new ConcreteMenuItem(player, item, this._qualityButton, this);
  };
  HlsQualitySelectorPlugin2.prototype.onAddQualityLevel = function onAddQualityLevel() {
    var _this = this;
    var player = this.player;
    var qualityList = player.qualityLevels();
    var levels = qualityList.levels_ || [];
    var levelItems = [];
    var _loop = function _loop2(i2) {
      if (!levelItems.filter(function(_existingItem) {
        return _existingItem.item && _existingItem.item.value === levels[i2].height;
      }).length) {
        var levelItem = _this.getQualityMenuItem.call(_this, {
          label: levels[i2].height + "p",
          value: levels[i2].height
        });
        levelItems.push(levelItem);
      }
    };
    for (var i = 0; i < levels.length; ++i) {
      _loop(i);
    }
    levelItems.sort(function(current, next) {
      if ((typeof current === "undefined" ? "undefined" : _typeof(current)) !== "object" || (typeof next === "undefined" ? "undefined" : _typeof(next)) !== "object") {
        return -1;
      }
      if (current.item.value < next.item.value) {
        return -1;
      }
      if (current.item.value > next.item.value) {
        return 1;
      }
      return 0;
    });
    levelItems.push(this.getQualityMenuItem.call(this, {
      label: player.localize("Auto"),
      value: "auto",
      selected: true
    }));
    if (this._qualityButton) {
      this._qualityButton.createItems = function() {
        return levelItems;
      };
      this._qualityButton.update();
    }
  };
  HlsQualitySelectorPlugin2.prototype.setQuality = function setQuality(height2) {
    var qualityList = this.player.qualityLevels();
    this._currentQuality = height2;
    if (this.config.displayCurrentQuality) {
      this.setButtonInnerText(height2 === "auto" ? height2 : height2 + "p");
    }
    for (var i = 0; i < qualityList.length; ++i) {
      var quality = qualityList[i];
      quality.enabled = quality.height === height2 || height2 === "auto";
    }
    this._qualityButton.unpressButton();
  };
  HlsQualitySelectorPlugin2.prototype.getCurrentQuality = function getCurrentQuality() {
    return this._currentQuality || "auto";
  };
  return HlsQualitySelectorPlugin2;
}();
var onPlayerReady = function onPlayerReady2(player, options) {
  player.addClass("vjs-hls-quality-selector");
  player.hlsQualitySelector = new HlsQualitySelectorPlugin(player, options);
};
var hlsQualitySelector = function hlsQualitySelector2(options) {
  var _this2 = this;
  this.ready(function() {
    onPlayerReady(_this2, video_es_default.mergeOptions(defaults4, options));
  });
};
registerPlugin2("hlsQualitySelector", hlsQualitySelector);
hlsQualitySelector.VERSION = version5;

// src/app/player/components/vjs-player/vjs-player.component.ts
var _c03 = ["target"];
var VjsPlayerComponent = class _VjsPlayerComponent {
  constructor() {
    this.volume = 1;
  }
  /**
   * Instantiate Video.js on component init
   */
  ngOnInit() {
    this.player = video_es_default(this.target.nativeElement, __spreadProps(__spreadValues({}, this.options), {
      autoplay: true
    }), () => {
      console.log("Setting VideoJS player initial volume to:", this.volume);
      this.player.volume(this.volume);
      this.player.on("volumechange", () => {
        const currentVolume = this.player.volume();
        localStorage.setItem("volume", currentVolume.toString());
      });
    });
    this.player.hlsQualitySelector({
      displayCurrentQuality: true
    });
    this.player["aspectRatioPanel"]();
  }
  /**
   * Replaces the url source of the player with the changed source url
   * @param changes contains changed channel object
   */
  ngOnChanges(changes) {
    if (changes.options.previousValue) {
      this.player.src(changes.options.currentValue.sources[0]);
    }
    if (changes.volume?.currentValue !== void 0 && this.player) {
      console.log("Setting VideoJS player volume to:", changes.volume.currentValue);
      this.player.volume(changes.volume.currentValue);
    }
  }
  /**
   * Removes the players HTML reference on destroy
   */
  ngOnDestroy() {
    if (this.player) {
      this.player.dispose();
    }
  }
  static {
    this.\u0275fac = function VjsPlayerComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || _VjsPlayerComponent)();
    };
  }
  static {
    this.\u0275cmp = /* @__PURE__ */ \u0275\u0275defineComponent({ type: _VjsPlayerComponent, selectors: [["app-vjs-player"]], viewQuery: function VjsPlayerComponent_Query(rf, ctx) {
      if (rf & 1) {
        \u0275\u0275viewQuery(_c03, 7);
      }
      if (rf & 2) {
        let _t;
        \u0275\u0275queryRefresh(_t = \u0275\u0275loadQuery()) && (ctx.target = _t.first);
      }
    }, inputs: { options: "options", volume: "volume" }, features: [\u0275\u0275NgOnChangesFeature], decls: 3, vars: 0, consts: [["target", ""], ["controls", "", "muted", "", "playsinline", "", "preload", "none", "data-setup", '{"liveui": true, "muted": false}', 1, "video-js"]], template: function VjsPlayerComponent_Template(rf, ctx) {
      if (rf & 1) {
        \u0275\u0275element(0, "video", 1, 0);
        \u0275\u0275text(2, "\n");
      }
    }, styles: ["/* src/app/player/components/vjs-player/vjs-player.component.scss */\n.video-js {\n  position: relative !important;\n  width: 100% !important;\n  height: calc(100vh - 65px);\n}\n.hide-captions .vjs-texttrack-settings,\n.hide-captions .vjs-text-track-display,\n.hide-captions .vjs-subs-caps-button {\n  display: none;\n}\n@media only screen and (max-width: 599px) {\n  .video-js {\n    height: calc(50vh - 65px) !important;\n  }\n}\n"], encapsulation: 2 });
  }
};
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(VjsPlayerComponent, [{
    type: Component,
    args: [{ selector: "app-vjs-player", encapsulation: ViewEncapsulation.None, standalone: true, template: `<video
    #target
    class="video-js"
    controls
    muted
    playsinline
    preload="none"
    data-setup='{"liveui": true, "muted": false}'
></video>
`, styles: ["/* src/app/player/components/vjs-player/vjs-player.component.scss */\n.video-js {\n  position: relative !important;\n  width: 100% !important;\n  height: calc(100vh - 65px);\n}\n.hide-captions .vjs-texttrack-settings,\n.hide-captions .vjs-text-track-display,\n.hide-captions .vjs-subs-caps-button {\n  display: none;\n}\n@media only screen and (max-width: 599px) {\n  .video-js {\n    height: calc(50vh - 65px) !important;\n  }\n}\n"] }]
  }], null, { target: [{
    type: ViewChild,
    args: ["target", { static: true }]
  }], options: [{
    type: Input
  }], volume: [{
    type: Input
  }] });
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && \u0275setClassDebugInfo(VjsPlayerComponent, { className: "VjsPlayerComponent", filePath: "src/app/player/components/vjs-player/vjs-player.component.ts", lineNumber: 27 });
})();

export {
  ArtPlayerComponent,
  DPlayerComponent,
  HtmlVideoPlayerComponent,
  ShakaPlayerComponent,
  VjsPlayerComponent
};
/*! Bundled license information:

artplayer/dist/artplayer.js:
  (*!
   * artplayer.js v5.2.1
   * Github: https://github.com/zhw2590582/ArtPlayer
   * (c) 2017-2024 Harvey Zack
   * Released under the MIT License.
   *)

shaka-player/dist/shaka-player.ui.js:
  (*
   @license
   Shaka Player
   Copyright 2016 Google LLC
   SPDX-License-Identifier: Apache-2.0
  *)
  (*
  @license
  Shaka Player
  Copyright 2016 Google LLC
  SPDX-License-Identifier: Apache-2.0
  *)
  (*
  @license
  Copyright 2008 The Closure Library Authors
  SPDX-License-Identifier: Apache-2.0
  *)
  (*
  @license
  Copyright 2006 The Closure Library Authors
  SPDX-License-Identifier: Apache-2.0
  *)
  (*
  @license
  Shaka Player
  Copyright 2025 Google LLC
  SPDX-License-Identifier: Apache-2.0
  *)
  (*
  @license
  tXml
  Copyright 2015 Tobias Nickel
  SPDX-License-Identifier: MIT
  *)
  (*
  @license
  Shaka Player
  Copyright 2023 Google LLC
  SPDX-License-Identifier: Apache-2.0
  *)
  (*
  @license
  Shaka Player
  Copyright 2022 Google LLC
  SPDX-License-Identifier: Apache-2.0
  *)
  (*
  @license
  Copyright 2013 Ali Al Dallal
  Licensed under the MIT license.
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
  *)
  (*
  @license
  MSS Transmuxer
  Copyright 2015 Dash Industry Forum
  SPDX-License-Identifier: BSD-3-Clause
  *)
  (*
  @license
  glMatrix: https://github.com/toji/gl-matrix/
  Copyright 2015-2021, Brandon Jones, Colin MacKenzie IV
  SPDX-License-Identifier: MIT
  *)

keycode/index.js:
  (*!
   * Programatically add the following
   *)

@videojs/xhr/lib/index.js:
  (**
   * @license
   * slighly modified parse-headers 2.0.2 <https://github.com/kesla/parse-headers/>
   * Copyright (c) 2014 David Björklund
   * Available under the MIT license
   * <https://github.com/kesla/parse-headers/blob/master/LICENCE>
   *)

m3u8-parser/dist/m3u8-parser.es.js:
  (*! @name m3u8-parser @version 4.7.1 @license Apache-2.0 *)

mpd-parser/dist/mpd-parser.es.js:
  (*! @name mpd-parser @version 0.21.1 @license Apache-2.0 *)

video.js/dist/video.es.js:
  (**
   * @license
   * Video.js 7.20.3 <http://videojs.com/>
   * Copyright Brightcove, Inc. <https://www.brightcove.com/>
   * Available under Apache License Version 2.0
   * <https://github.com/videojs/video.js/blob/main/LICENSE>
   *
   * Includes vtt.js <https://github.com/mozilla/vtt.js>
   * Available under Apache License Version 2.0
   * <https://github.com/mozilla/vtt.js/blob/main/LICENSE>
   *)
  (*! @name @videojs/http-streaming @version 2.14.3 @license Apache-2.0 *)
  (*! @name pkcs7 @version 1.0.4 @license Apache-2.0 *)
  (*! @name aes-decrypter @version 3.1.3 @license Apache-2.0 *)

@yangkghjh/videojs-aspect-ratio-panel/dist/videojs-aspect-ratio-panel.es.js:
  (*! @name @yangkghjh/videojs-aspect-ratio-panel @version 0.0.1 @license MIT *)

videojs-contrib-quality-levels/dist/videojs-contrib-quality-levels.es.js:
  (*! @name videojs-contrib-quality-levels @version 2.2.0 @license Apache-2.0 *)
*/
