import { p as x, Q as S, b as g, T as k, L as u, d as M, l as C } from "./wt-vidstack-player-DL-84dHQ.js";
import { a0 as N, d as p, x as R, l as b, m as F, D as l, B as I, Z as P, $, h as _, R as q, b as E, j as H } from "./useVidstackSrc-CNo2sIR4.js";
import { VideoProvider as j } from "./vidstack-video-CAC4Bc1B.js";
import { R as O } from "./vidstack-DqAw8m9J-kmvNQesV.js";
function v(n) {
  try {
    return new Intl.DisplayNames(navigator.languages, { type: "language" }).of(n) ?? null;
  } catch {
    return null;
  }
}
const Q = (n) => `dash-${I(n)}`;
class G {
  #e;
  #i;
  #t = null;
  #a = /* @__PURE__ */ new Set();
  #r = null;
  config = {};
  get instance() {
    return this.#t;
  }
  constructor(t, i) {
    this.#e = t, this.#i = i;
  }
  setup(t) {
    this.#t = t().create();
    const i = this.#g.bind(this);
    for (const s of Object.values(t.events)) this.#t.on(s, i);
    this.#t.on(t.events.ERROR, this.#v.bind(this));
    for (const s of this.#a) s(this.#t);
    this.#i.player.dispatch("dash-instance", {
      detail: this.#t
    }), this.#t.initialize(this.#e, void 0, !1), this.#t.updateSettings({
      streaming: {
        text: {
          // Disabling text rendering by dash.
          defaultEnabled: !1,
          dispatchForManualRendering: !0
        },
        buffer: {
          /// Enables buffer replacement when switching bitrates for faster switching.
          fastSwitchEnabled: !0
        }
      },
      ...this.config
    }), this.#t.on(t.events.FRAGMENT_LOADING_STARTED, this.#w.bind(this)), this.#t.on(
      t.events.FRAGMENT_LOADING_COMPLETED,
      this.#E.bind(this)
    ), this.#t.on(t.events.MANIFEST_LOADED, this.#b.bind(this)), this.#t.on(t.events.QUALITY_CHANGE_RENDERED, this.#S.bind(this)), this.#t.on(t.events.TEXT_TRACKS_ADDED, this.#m.bind(this)), this.#t.on(t.events.TRACK_CHANGE_RENDERED, this.#T.bind(this)), this.#i.qualities[S.enableAuto] = this.#A.bind(this), b(this.#i.qualities, "change", this.#D.bind(this)), b(this.#i.audioTracks, "change", this.#x.bind(this)), this.#r = F(this.#d.bind(this));
  }
  #s(t) {
    return new l(Q(t.type), { detail: t });
  }
  #d() {
    if (!this.#i.$state.live()) return;
    const t = new O(this.#f.bind(this));
    return t.start(), t.stop.bind(t);
  }
  #f() {
    if (!this.#t) return;
    const t = this.#t.duration() - this.#t.time();
    this.#i.$state.liveSyncPosition.set(isNaN(t) ? 1 / 0 : t);
  }
  #g(t) {
    this.#i.player?.dispatch(this.#s(t));
  }
  #n = null;
  #h = {};
  #y(t) {
    const i = this.#n?.[g.native], s = (i?.track).cues;
    if (!i || !s) return;
    const r = this.#n.id, a = this.#h[r] ?? 0, o = this.#s(t);
    for (let c = a; c < s.length; c++) {
      const h = s[c];
      h.positionAlign || (h.positionAlign = "auto"), this.#n.addCue(h, o);
    }
    this.#h[r] = s.length;
  }
  #m(t) {
    if (!this.#t) return;
    const i = t.tracks, s = [...this.#e.textTracks].filter((a) => "manualMode" in a), r = this.#s(t);
    for (let a = 0; a < s.length; a++) {
      const o = i[a], c = s[a], h = `dash-${o.kind}-${a}`, d = new k({
        id: h,
        label: o?.label ?? o.labels.find((y) => y.text)?.text ?? (o?.lang && v(o.lang)) ?? o?.lang ?? void 0,
        language: o.lang ?? void 0,
        kind: o.kind,
        default: o.defaultTrack
      });
      d[g.native] = {
        managed: !0,
        track: c
      }, d[g.readyState] = 2, d[g.onModeChange] = () => {
        this.#t && (d.mode === "showing" ? (this.#t.setTextTrack(a), this.#n = d) : (this.#t.setTextTrack(-1), this.#n = null));
      }, this.#i.textTracks.add(d, r);
    }
  }
  #T(t) {
    const { mediaType: i, newMediaInfo: s } = t;
    if (i === "audio") {
      const r = this.#i.audioTracks.getById(`dash-audio-${s.index}`);
      if (r) {
        const a = this.#s(t);
        this.#i.audioTracks[u.select](r, !0, a);
      }
    }
  }
  #S(t) {
    if (t.mediaType !== "video") return;
    const i = this.#i.qualities[t.newQuality];
    if (i) {
      const s = this.#s(t);
      this.#i.qualities[u.select](i, !0, s);
    }
  }
  #b(t) {
    if (this.#i.$state.canPlay() || !this.#t) return;
    const { type: i, mediaPresentationDuration: s } = t.data, r = this.#s(t);
    this.#i.notify("stream-type-change", i !== "static" ? "live" : "on-demand", r), this.#i.notify("duration-change", s, r), this.#i.qualities[S.setAuto](!0, r);
    const a = this.#t.getVideoElement(), o = this.#t.getTracksForTypeFromManifest(
      "video",
      t.data
    ), c = [...new Set(o.map((e) => e.mimeType))].find(
      (e) => e && P(a, e)
    ), h = o.filter(
      (e) => c === e.mimeType
    )[0];
    let d = this.#t.getTracksForTypeFromManifest(
      "audio",
      t.data
    );
    const y = [...new Set(d.map((e) => e.mimeType))].find(
      (e) => e && $(a, e)
    );
    if (d = d.filter((e) => y === e.mimeType), h.bitrateList.forEach((e, f) => {
      const m = {
        id: e.id?.toString() ?? `dash-bitrate-${f}`,
        width: e.width ?? 0,
        height: e.height ?? 0,
        bitrate: e.bandwidth ?? 0,
        codec: h.codec,
        index: f
      };
      this.#i.qualities[u.add](m, r);
    }), _(h.index)) {
      const e = this.#i.qualities[h.index];
      e && this.#i.qualities[u.select](e, !0, r);
    }
    d.forEach((e, f) => {
      const L = e.labels.find((T) => navigator.languages.some((D) => T.lang && D.toLowerCase().startsWith(T.lang.toLowerCase()))) || e.labels[0], A = {
        id: `dash-audio-${e?.index}`,
        label: L?.text ?? (e.lang && v(e.lang)) ?? e.lang ?? "",
        language: e.lang ?? "",
        kind: "main",
        mimeType: e.mimeType,
        codec: e.codec,
        index: f
      };
      this.#i.audioTracks[u.add](A, r);
    }), a.dispatchEvent(new l("canplay", { trigger: r }));
  }
  #v(t) {
    const { type: i, error: s } = t;
    s.code === 27 ? this.#L(s) : this.#l(s);
  }
  #w() {
    this.#o >= 0 && this.#c();
  }
  #E(t) {
    t.mediaType === "text" && requestAnimationFrame(this.#y.bind(this, t));
  }
  #o = -1;
  #L(t) {
    this.#c(), this.#t?.play(), this.#o = window.setTimeout(() => {
      this.#o = -1, this.#l(t);
    }, 5e3);
  }
  #c() {
    clearTimeout(this.#o), this.#o = -1;
  }
  #l(t) {
    this.#i.notify("error", {
      message: t.message ?? "",
      code: 1,
      error: t
    });
  }
  #A() {
    this.#u("video", !0);
    const { qualities: t } = this.#i;
    this.#t?.setQualityFor("video", t.selectedIndex, !0);
  }
  #u(t, i) {
    this.#t?.updateSettings({
      streaming: { abr: { autoSwitchBitrate: { [t]: i } } }
    });
  }
  #D() {
    const { qualities: t } = this.#i;
    !this.#t || t.auto || !t.selected || (this.#u("video", !1), this.#t.setQualityFor("video", t.selectedIndex, t.switch === "current"), q && (this.#e.currentTime = this.#e.currentTime));
  }
  #x() {
    if (!this.#t) return;
    const { audioTracks: t } = this.#i, i = this.#t.getTracksFor("audio").find(
      (s) => t.selected && t.selected.id === `dash-audio-${s.index}`
    );
    i && this.#t.setCurrentTrack(i);
  }
  #p() {
    this.#c(), this.#n = null, this.#h = {};
  }
  onInstance(t) {
    return this.#a.add(t), () => this.#a.delete(t);
  }
  loadSource(t) {
    this.#p(), p(t.src) && this.#t?.attachSource(t.src);
  }
  destroy() {
    this.#p(), this.#t?.destroy(), this.#t = null, this.#r?.(), this.#r = null;
  }
}
class V {
  #e;
  #i;
  #t;
  constructor(t, i, s) {
    this.#e = t, this.#i = i, this.#t = s, this.#a();
  }
  async #a() {
    const t = {
      onLoadStart: this.#r.bind(this),
      onLoaded: this.#s.bind(this),
      onLoadError: this.#d.bind(this)
    };
    let i = await U(this.#e, t);
    if (E(i) && !p(this.#e) && (i = await B(this.#e, t)), !i) return null;
    if (!window.dashjs.supportsMediaSource()) {
      const s = "[vidstack] `dash.js` is not supported in this environment";
      return this.#i.player.dispatch(new l("dash-unsupported")), this.#i.notify("error", { message: s, code: 4 }), null;
    }
    return i;
  }
  #r() {
    this.#i.player.dispatch(new l("dash-lib-load-start"));
  }
  #s(t) {
    this.#i.player.dispatch(
      new l("dash-lib-loaded", {
        detail: t
      })
    ), this.#t(t);
  }
  #d(t) {
    const i = M(t);
    this.#i.player.dispatch(
      new l("dash-lib-load-error", {
        detail: i
      })
    ), this.#i.notify("error", {
      message: i.message,
      code: 4,
      error: i
    });
  }
}
async function B(n, t = {}) {
  if (!E(n)) {
    if (t.onLoadStart?.(), K(n))
      return t.onLoaded?.(n), n;
    if (w(n)) {
      const i = n.MediaPlayer;
      return t.onLoaded?.(i), i;
    }
    try {
      const i = (await n())?.default;
      if (w(i))
        return t.onLoaded?.(i.MediaPlayer), i.MediaPlayer;
      if (i)
        t.onLoaded?.(i);
      else
        throw Error(
          ""
        );
      return i;
    } catch (i) {
      t.onLoadError?.(i);
    }
  }
}
async function U(n, t = {}) {
  if (p(n)) {
    t.onLoadStart?.();
    try {
      if (await C(n), !H(window.dashjs.MediaPlayer))
        throw Error(
          ""
        );
      const i = window.dashjs.MediaPlayer;
      return t.onLoaded?.(i), i;
    } catch (i) {
      t.onLoadError?.(i);
    }
  }
}
function K(n) {
  return n && n.prototype && n.prototype !== Function;
}
function w(n) {
  return n && "MediaPlayer" in n;
}
const Y = "https://cdn.jsdelivr.net";
class Z extends j {
  $$PROVIDER_TYPE = "DASH";
  #e = null;
  #i = new G(this.video, this.ctx);
  /**
   * The `dash.js` constructor.
   */
  get ctor() {
    return this.#e;
  }
  /**
   * The current `dash.js` instance.
   */
  get instance() {
    return this.#i.instance;
  }
  /**
   * Whether `dash.js` is supported in this environment.
   */
  static supported = N();
  get type() {
    return "dash";
  }
  get canLiveSync() {
    return !0;
  }
  #t = `${Y}/npm/dashjs@4.7.4/dist/dash.all.min.js`;
  /**
   * The `dash.js` configuration object.
   *
   * @see {@link https://cdn.dashjs.org/latest/jsdoc/module-Settings.html}
   */
  get config() {
    return this.#i.config;
  }
  set config(t) {
    this.#i.config = t;
  }
  /**
   * The `dash.js` constructor (supports dynamic imports) or a URL of where it can be found.
   *
   * @defaultValue `https://cdn.jsdelivr.net/npm/dashjs@4.7.4/dist/dash.all.min.js`
   */
  get library() {
    return this.#t;
  }
  set library(t) {
    this.#t = t;
  }
  preconnect() {
    p(this.#t) && x(this.#t);
  }
  setup() {
    super.setup(), new V(this.#t, this.ctx, (t) => {
      this.#e = t, this.#i.setup(t), this.ctx.notify("provider-setup", this);
      const i = R(this.ctx.$state.source);
      i && this.loadSource(i);
    });
  }
  async loadSource(t, i) {
    if (!p(t.src)) {
      this.removeSource();
      return;
    }
    this.media.preload = i || "", this.appendSource(t, "application/x-mpegurl"), this.#i.loadSource(t), this.currentSrc = t;
  }
  /**
   * The given callback is invoked when a new `dash.js` instance is created and right before it's
   * attached to media.
   */
  onInstance(t) {
    const i = this.#i.instance;
    return i && t(i), this.#i.onInstance(t);
  }
  destroy() {
    this.#i.destroy();
  }
}
export {
  Z as DASHProvider
};
