import L from "../../../../@videojs_vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/resolve-url.js";
import T from "../../../../../../../_virtual/window.js";
import { forEachMediaGroup as Z } from "../../../../@videojs_vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/media-groups.js";
import J from "../../../../@videojs_vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/decode-b64-to-uint8-array.js";
import { l as Q } from "../../../../../../../_virtual/index6.js";
/*! @name mpd-parser @version 1.3.1 @license Apache-2.0 */
const w = (e) => !!e && typeof e == "object", E = (...e) => e.reduce((n, t) => (typeof t != "object" || Object.keys(t).forEach((r) => {
  Array.isArray(n[r]) && Array.isArray(t[r]) ? n[r] = n[r].concat(t[r]) : w(n[r]) && w(t[r]) ? n[r] = E(n[r], t[r]) : n[r] = t[r];
}), n), {}), q = (e) => Object.keys(e).map((n) => e[n]), ee = (e, n) => {
  const t = [];
  for (let r = e; r < n; r++)
    t.push(r);
  return t;
}, P = (e) => e.reduce((n, t) => n.concat(t), []), W = (e) => {
  if (!e.length)
    return [];
  const n = [];
  for (let t = 0; t < e.length; t++)
    n.push(e[t]);
  return n;
}, te = (e, n) => e.reduce((t, r, i) => (r[n] && t.push(i), t), []), ne = (e, n) => q(e.reduce((t, r) => (r.forEach((i) => {
  t[n(i)] = i;
}), t), {}));
var R = {
  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",
  SEGMENT_TIME_UNSPECIFIED: "SEGMENT_TIME_UNSPECIFIED",
  UNSUPPORTED_UTC_TIMING_SCHEME: "UNSUPPORTED_UTC_TIMING_SCHEME"
};
const O = ({
  baseUrl: e = "",
  source: n = "",
  range: t = "",
  indexRange: r = ""
}) => {
  const i = {
    uri: n,
    resolvedUri: L(e || "", n)
  };
  if (t || r) {
    const s = (t || r).split("-");
    let c = T.BigInt ? T.BigInt(s[0]) : parseInt(s[0], 10), a = T.BigInt ? T.BigInt(s[1]) : parseInt(s[1], 10);
    c < Number.MAX_SAFE_INTEGER && typeof c == "bigint" && (c = Number(c)), a < Number.MAX_SAFE_INTEGER && typeof a == "bigint" && (a = Number(a));
    let u;
    typeof a == "bigint" || typeof c == "bigint" ? u = T.BigInt(a) - T.BigInt(c) + T.BigInt(1) : u = a - c + 1, typeof u == "bigint" && u < Number.MAX_SAFE_INTEGER && (u = Number(u)), i.byterange = {
      length: u,
      offset: c
    };
  }
  return i;
}, re = (e) => {
  let n;
  return typeof e.offset == "bigint" || typeof e.length == "bigint" ? n = T.BigInt(e.offset) + T.BigInt(e.length) - T.BigInt(1) : n = e.offset + e.length - 1, `${e.offset}-${n}`;
}, F = (e) => (e && typeof e != "number" && (e = parseInt(e, 10)), isNaN(e) ? null : e), ie = {
  /**
   * 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(e) {
    const {
      duration: n,
      timescale: t = 1,
      sourceDuration: r,
      periodDuration: i
    } = e, o = F(e.endNumber), s = n / t;
    return typeof o == "number" ? {
      start: 0,
      end: o
    } : typeof i == "number" ? {
      start: 0,
      end: i / s
    } : {
      start: 0,
      end: r / s
    };
  },
  /**
   * 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(e) {
    const {
      NOW: n,
      clientOffset: t,
      availabilityStartTime: r,
      timescale: i = 1,
      duration: o,
      periodStart: s = 0,
      minimumUpdatePeriod: c = 0,
      timeShiftBufferDepth: a = 1 / 0
    } = e, u = F(e.endNumber), m = (n + t) / 1e3, d = r + s, h = m + c - d, l = Math.ceil(h * i / o), g = Math.floor((m - d - a) * i / o), I = Math.floor((m - d) * i / o);
    return {
      start: Math.max(0, g),
      end: typeof u == "number" ? u : Math.min(l, I)
    };
  }
}, oe = (e) => (n) => {
  const {
    duration: t,
    timescale: r = 1,
    periodStart: i,
    startNumber: o = 1
  } = e;
  return {
    number: o + n,
    duration: t / r,
    timeline: i,
    time: n * t
  };
}, C = (e) => {
  const {
    type: n,
    duration: t,
    timescale: r = 1,
    periodDuration: i,
    sourceDuration: o
  } = e, {
    start: s,
    end: c
  } = ie[n](e), a = ee(s, c).map(oe(e));
  if (n === "static") {
    const u = a.length - 1, m = typeof i == "number" ? i : o;
    a[u].duration = m - t / r * u;
  }
  return a;
}, Y = (e) => {
  const {
    baseUrl: n,
    initialization: t = {},
    sourceDuration: r,
    indexRange: i = "",
    periodStart: o,
    presentationTime: s,
    number: c = 0,
    duration: a
  } = e;
  if (!n)
    throw new Error(R.NO_BASE_URL);
  const u = O({
    baseUrl: n,
    source: t.sourceURL,
    range: t.range
  }), m = O({
    baseUrl: n,
    source: n,
    indexRange: i
  });
  if (m.map = u, a) {
    const d = C(e);
    d.length && (m.duration = d[0].duration, m.timeline = d[0].timeline);
  } else r && (m.duration = r, m.timeline = o);
  return m.presentationTime = s || o, m.number = c, [m];
}, se = (e, n, t) => {
  const r = e.sidx.map ? e.sidx.map : null, i = e.sidx.duration, o = e.timeline || 0, s = e.sidx.byterange, c = s.offset + s.length, a = n.timescale, u = n.references.filter((I) => I.referenceType !== 1), m = [], d = e.endList ? "static" : "dynamic", p = e.sidx.timeline;
  let h = p, l = e.mediaSequence || 0, g;
  typeof n.firstOffset == "bigint" ? g = T.BigInt(c) + n.firstOffset : g = c + n.firstOffset;
  for (let I = 0; I < u.length; I++) {
    const U = n.references[I], D = U.referencedSize, N = U.subsegmentDuration;
    let b;
    typeof g == "bigint" ? b = g + T.BigInt(D) - T.BigInt(1) : b = g + D - 1;
    const k = `${g}-${b}`, x = Y({
      baseUrl: t,
      timescale: a,
      timeline: o,
      periodStart: p,
      presentationTime: h,
      number: l,
      duration: N,
      sourceDuration: i,
      indexRange: k,
      type: d
    })[0];
    r && (x.map = r), m.push(x), typeof g == "bigint" ? g += T.BigInt(D) : g += D, h += N / a, l++;
  }
  return e.segments = m, e;
}, ae = ["AUDIO", "SUBTITLES"], ce = 1 / 60, X = (e) => ne(e, ({
  timeline: n
}) => n).sort((n, t) => n.timeline > t.timeline ? 1 : -1), ue = (e, n) => {
  for (let t = 0; t < e.length; t++)
    if (e[t].attributes.NAME === n)
      return e[t];
  return null;
}, G = (e) => {
  let n = [];
  return Z(e, ae, (t, r, i, o) => {
    n = n.concat(t.playlists || []);
  }), n;
}, z = ({
  playlist: e,
  mediaSequence: n
}) => {
  e.mediaSequence = n, e.segments.forEach((t, r) => {
    t.number = e.mediaSequence + r;
  });
}, me = ({
  oldPlaylists: e,
  newPlaylists: n,
  timelineStarts: t
}) => {
  n.forEach((r) => {
    r.discontinuitySequence = t.findIndex(function({
      timeline: a
    }) {
      return a === r.timeline;
    });
    const i = ue(e, r.attributes.NAME);
    if (!i || r.sidx)
      return;
    const o = r.segments[0], s = i.segments.findIndex(function(a) {
      return Math.abs(a.presentationTime - o.presentationTime) < ce;
    });
    if (s === -1) {
      z({
        playlist: r,
        mediaSequence: i.mediaSequence + i.segments.length
      }), r.segments[0].discontinuity = !0, r.discontinuityStarts.unshift(0), (!i.segments.length && r.timeline > i.timeline || i.segments.length && r.timeline > i.segments[i.segments.length - 1].timeline) && r.discontinuitySequence--;
      return;
    }
    i.segments[s].discontinuity && !o.discontinuity && (o.discontinuity = !0, r.discontinuityStarts.unshift(0), r.discontinuitySequence--), z({
      playlist: r,
      mediaSequence: i.segments[s].number
    });
  });
}, de = ({
  oldManifest: e,
  newManifest: n
}) => {
  const t = e.playlists.concat(G(e)), r = n.playlists.concat(G(n));
  return n.timelineStarts = X([e.timelineStarts, n.timelineStarts]), me({
    oldPlaylists: t,
    newPlaylists: r,
    timelineStarts: n.timelineStarts
  }), n;
}, le = (e) => e && e.uri + "-" + re(e.byterange), M = (e) => {
  const n = e.reduce(function(r, i) {
    return r[i.attributes.baseUrl] || (r[i.attributes.baseUrl] = []), r[i.attributes.baseUrl].push(i), r;
  }, {});
  let t = [];
  return Object.values(n).forEach((r) => {
    const i = q(r.reduce((o, s) => {
      const c = s.attributes.id + (s.attributes.lang || "");
      return o[c] ? (s.segments && (s.segments[0] && (s.segments[0].discontinuity = !0), o[c].segments.push(...s.segments)), s.attributes.contentProtection && (o[c].attributes.contentProtection = s.attributes.contentProtection)) : (o[c] = s, o[c].attributes.timelineStarts = []), o[c].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: s.attributes.periodStart,
        timeline: s.attributes.periodStart
      }), o;
    }, {}));
    t = t.concat(i);
  }), t.map((r) => (r.discontinuityStarts = te(r.segments || [], "discontinuity"), r));
}, B = (e, n) => {
  const t = le(e.sidx), r = t && n[t] && n[t].sidx;
  return r && se(e, r, e.sidx.resolvedUri), e;
}, fe = (e, n = {}) => {
  if (!Object.keys(n).length)
    return e;
  for (const t in e)
    e[t] = B(e[t], n);
  return e;
}, ge = ({
  attributes: e,
  segments: n,
  sidx: t,
  mediaSequence: r,
  discontinuitySequence: i,
  discontinuityStarts: o
}, s) => {
  const c = {
    attributes: {
      NAME: e.id,
      BANDWIDTH: e.bandwidth,
      CODECS: e.codecs,
      "PROGRAM-ID": 1
    },
    uri: "",
    endList: e.type === "static",
    timeline: e.periodStart,
    resolvedUri: e.baseUrl || "",
    targetDuration: e.duration,
    discontinuitySequence: i,
    discontinuityStarts: o,
    timelineStarts: e.timelineStarts,
    mediaSequence: r,
    segments: n
  };
  return e.contentProtection && (c.contentProtection = e.contentProtection), e.serviceLocation && (c.attributes.serviceLocation = e.serviceLocation), t && (c.sidx = t), s && (c.attributes.AUDIO = "audio", c.attributes.SUBTITLES = "subs"), c;
}, pe = ({
  attributes: e,
  segments: n,
  mediaSequence: t,
  discontinuityStarts: r,
  discontinuitySequence: i
}) => {
  typeof n > "u" && (n = [{
    uri: e.baseUrl,
    timeline: e.periodStart,
    resolvedUri: e.baseUrl || "",
    duration: e.sourceDuration,
    number: 0
  }], e.duration = e.sourceDuration);
  const o = {
    NAME: e.id,
    BANDWIDTH: e.bandwidth,
    "PROGRAM-ID": 1
  };
  e.codecs && (o.CODECS = e.codecs);
  const s = {
    attributes: o,
    uri: "",
    endList: e.type === "static",
    timeline: e.periodStart,
    resolvedUri: e.baseUrl || "",
    targetDuration: e.duration,
    timelineStarts: e.timelineStarts,
    discontinuityStarts: r,
    discontinuitySequence: i,
    mediaSequence: t,
    segments: n
  };
  return e.serviceLocation && (s.attributes.serviceLocation = e.serviceLocation), s;
}, Se = (e, n = {}, t = !1) => {
  let r;
  const i = e.reduce((o, s) => {
    const c = s.attributes.role && s.attributes.role.value || "", a = s.attributes.lang || "";
    let u = s.attributes.label || "main";
    if (a && !s.attributes.label) {
      const d = c ? ` (${c})` : "";
      u = `${s.attributes.lang}${d}`;
    }
    o[u] || (o[u] = {
      language: a,
      autoselect: !0,
      default: c === "main",
      playlists: [],
      uri: ""
    });
    const m = B(ge(s, t), n);
    return o[u].playlists.push(m), typeof r > "u" && c === "main" && (r = s, r.default = !0), o;
  }, {});
  if (!r) {
    const o = Object.keys(i)[0];
    i[o].default = !0;
  }
  return i;
}, he = (e, n = {}) => e.reduce((t, r) => {
  const i = r.attributes.label || r.attributes.lang || "text", o = r.attributes.lang || "und";
  return t[i] || (t[i] = {
    language: o,
    default: !1,
    autoselect: !1,
    playlists: [],
    uri: ""
  }), t[i].playlists.push(B(pe(r), n)), t;
}, {}), Ie = (e) => e.reduce((n, t) => (t && t.forEach((r) => {
  const {
    channel: i,
    language: o
  } = r;
  n[o] = {
    autoselect: !1,
    default: !1,
    instreamId: i,
    language: o
  }, r.hasOwnProperty("aspectRatio") && (n[o].aspectRatio = r.aspectRatio), r.hasOwnProperty("easyReader") && (n[o].easyReader = r.easyReader), r.hasOwnProperty("3D") && (n[o]["3D"] = r["3D"]);
}), n), {}), Ee = ({
  attributes: e,
  segments: n,
  sidx: t,
  discontinuityStarts: r
}) => {
  const i = {
    attributes: {
      NAME: e.id,
      AUDIO: "audio",
      SUBTITLES: "subs",
      RESOLUTION: {
        width: e.width,
        height: e.height
      },
      CODECS: e.codecs,
      BANDWIDTH: e.bandwidth,
      "PROGRAM-ID": 1
    },
    uri: "",
    endList: e.type === "static",
    timeline: e.periodStart,
    resolvedUri: e.baseUrl || "",
    targetDuration: e.duration,
    discontinuityStarts: r,
    timelineStarts: e.timelineStarts,
    segments: n
  };
  return e.frameRate && (i.attributes["FRAME-RATE"] = e.frameRate), e.contentProtection && (i.contentProtection = e.contentProtection), e.serviceLocation && (i.attributes.serviceLocation = e.serviceLocation), t && (i.sidx = t), i;
}, Te = ({
  attributes: e
}) => e.mimeType === "video/mp4" || e.mimeType === "video/webm" || e.contentType === "video", De = ({
  attributes: e
}) => e.mimeType === "audio/mp4" || e.mimeType === "audio/webm" || e.contentType === "audio", Ue = ({
  attributes: e
}) => e.mimeType === "text/vtt" || e.contentType === "text", Ne = (e, n) => {
  e.forEach((t) => {
    t.mediaSequence = 0, t.discontinuitySequence = n.findIndex(function({
      timeline: r
    }) {
      return r === t.timeline;
    }), t.segments && t.segments.forEach((r, i) => {
      r.number = i;
    });
  });
}, $ = (e) => e ? Object.keys(e).reduce((n, t) => {
  const r = e[t];
  return n.concat(r.playlists);
}, []) : [], be = ({
  dashPlaylists: e,
  locations: n,
  contentSteering: t,
  sidxMapping: r = {},
  previousManifest: i,
  eventStream: o
}) => {
  if (!e.length)
    return {};
  const {
    sourceDuration: s,
    type: c,
    suggestedPresentationDelay: a,
    minimumUpdatePeriod: u
  } = e[0].attributes, m = M(e.filter(Te)).map(Ee), d = M(e.filter(De)), p = M(e.filter(Ue)), h = e.map((b) => b.attributes.captionServices).filter(Boolean), l = {
    allowCache: !0,
    discontinuityStarts: [],
    segments: [],
    endList: !0,
    mediaGroups: {
      AUDIO: {},
      VIDEO: {},
      "CLOSED-CAPTIONS": {},
      SUBTITLES: {}
    },
    uri: "",
    duration: s,
    playlists: fe(m, r)
  };
  u >= 0 && (l.minimumUpdatePeriod = u * 1e3), n && (l.locations = n), t && (l.contentSteering = t), c === "dynamic" && (l.suggestedPresentationDelay = a), o && o.length > 0 && (l.eventStream = o);
  const g = l.playlists.length === 0, I = d.length ? Se(d, r, g) : null, U = p.length ? he(p, r) : null, D = m.concat($(I), $(U)), N = D.map(({
    timelineStarts: b
  }) => b);
  return l.timelineStarts = X(N), Ne(D, l.timelineStarts), I && (l.mediaGroups.AUDIO.audio = I), U && (l.mediaGroups.SUBTITLES.subs = U), h.length && (l.mediaGroups["CLOSED-CAPTIONS"].cc = Ie(h)), i ? de({
    oldManifest: i,
    newManifest: l
  }) : l;
}, ye = (e, n, t) => {
  const {
    NOW: r,
    clientOffset: i,
    availabilityStartTime: o,
    timescale: s = 1,
    periodStart: c = 0,
    minimumUpdatePeriod: a = 0
  } = e, u = (r + i) / 1e3, m = o + c, p = u + a - m;
  return Math.ceil((p * s - n) / t);
}, j = (e, n) => {
  const {
    type: t,
    minimumUpdatePeriod: r = 0,
    media: i = "",
    sourceDuration: o,
    timescale: s = 1,
    startNumber: c = 1,
    periodStart: a
  } = e, u = [];
  let m = -1;
  for (let d = 0; d < n.length; d++) {
    const p = n[d], h = p.d, l = p.r || 0, g = p.t || 0;
    m < 0 && (m = g), g && g > m && (m = g);
    let I;
    if (l < 0) {
      const N = d + 1;
      N === n.length ? t === "dynamic" && r > 0 && i.indexOf("$Number$") > 0 ? I = ye(e, m, h) : I = (o * s - m) / h : I = (n[N].t - m) / h;
    } else
      I = l + 1;
    const U = c + u.length + I;
    let D = c + u.length;
    for (; D < U; )
      u.push({
        number: D,
        duration: h / s,
        time: m,
        timeline: a
      }), m += h, D++;
  }
  return u;
}, Pe = /\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g, Re = (e) => (n, t, r, i) => {
  if (n === "$$")
    return "$";
  if (typeof e[t] > "u")
    return n;
  const o = "" + e[t];
  return t === "RepresentationID" || (r ? i = parseInt(i, 10) : i = 1, o.length >= i) ? o : `${new Array(i - o.length + 1).join("0")}${o}`;
}, H = (e, n) => e.replace(Pe, Re(n)), Oe = (e, n) => !e.duration && !n ? [{
  number: e.startNumber || 1,
  duration: e.sourceDuration,
  time: 0,
  timeline: e.periodStart
}] : e.duration ? C(e) : j(e, n), Ae = (e, n) => {
  const t = {
    RepresentationID: e.id,
    Bandwidth: e.bandwidth || 0
  }, {
    initialization: r = {
      sourceURL: "",
      range: ""
    }
  } = e, i = O({
    baseUrl: e.baseUrl,
    source: H(r.sourceURL, t),
    range: r.range
  });
  return Oe(e, n).map((s) => {
    t.Number = s.number, t.Time = s.time;
    const c = H(e.media || "", t), a = e.timescale || 1, u = e.presentationTimeOffset || 0, m = (
      // 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.
      e.periodStart + (s.time - u) / a
    );
    return {
      uri: c,
      timeline: s.timeline,
      duration: s.duration,
      resolvedUri: L(e.baseUrl || "", c),
      map: i,
      number: s.number,
      presentationTime: m
    };
  });
}, _e = (e, n) => {
  const {
    baseUrl: t,
    initialization: r = {}
  } = e, i = O({
    baseUrl: t,
    source: r.sourceURL,
    range: r.range
  }), o = O({
    baseUrl: t,
    source: n.media,
    range: n.mediaRange
  });
  return o.map = i, o;
}, Me = (e, n) => {
  const {
    duration: t,
    segmentUrls: r = [],
    periodStart: i
  } = e;
  if (!t && !n || t && n)
    throw new Error(R.SEGMENT_TIME_UNSPECIFIED);
  const o = r.map((a) => _e(e, a));
  let s;
  return t && (s = C(e)), n && (s = j(e, n)), s.map((a, u) => {
    if (o[u]) {
      const m = o[u], d = e.timescale || 1, p = e.presentationTimeOffset || 0;
      return m.timeline = a.timeline, m.duration = a.duration, m.number = a.number, m.presentationTime = i + (a.time - p) / d, m;
    }
  }).filter((a) => a);
}, Le = ({
  attributes: e,
  segmentInfo: n
}) => {
  let t, r;
  n.template ? (r = Ae, t = E(e, n.template)) : n.base ? (r = Y, t = E(e, n.base)) : n.list && (r = Me, t = E(e, n.list));
  const i = {
    attributes: e
  };
  if (!r)
    return i;
  const o = r(t, n.segmentTimeline);
  if (t.duration) {
    const {
      duration: s,
      timescale: c = 1
    } = t;
    t.duration = s / c;
  } else o.length ? t.duration = o.reduce((s, c) => Math.max(s, Math.ceil(c.duration)), 0) : t.duration = 0;
  return i.attributes = t, i.segments = o, n.base && t.indexRange && (i.sidx = o[0], i.segments = []), i;
}, Ce = (e) => e.map(Le), f = (e, n) => W(e.childNodes).filter(({
  tagName: t
}) => t === n), A = (e) => e.textContent.trim(), Be = (e) => parseFloat(e.split("/").reduce((n, t) => n / t)), y = (e) => {
  const c = /P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(e);
  if (!c)
    return 0;
  const [a, u, m, d, p, h] = c.slice(1);
  return parseFloat(a || 0) * 31536e3 + parseFloat(u || 0) * 2592e3 + parseFloat(m || 0) * 86400 + parseFloat(d || 0) * 3600 + parseFloat(p || 0) * 60 + parseFloat(h || 0);
}, ve = (e) => (/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(e) && (e += "Z"), Date.parse(e)), V = {
  /**
   * 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(e) {
    return y(e);
  },
  /**
   * 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(e) {
    return ve(e) / 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(e) {
    return y(e);
  },
  /**
   * 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(e) {
    return y(e);
  },
  /**
   * 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(e) {
    return e;
  },
  /**
   * 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(e) {
    return y(e);
  },
  /**
   * 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(e) {
    return y(e);
  },
  /**
   * Specifies the width of the visual presentation
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed width
   */
  width(e) {
    return parseInt(e, 10);
  },
  /**
   * Specifies the height of the visual presentation
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed height
   */
  height(e) {
    return parseInt(e, 10);
  },
  /**
   * Specifies the bitrate of the representation
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed bandwidth
   */
  bandwidth(e) {
    return parseInt(e, 10);
  },
  /**
   * Specifies the frame rate of the representation
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed frame rate
   */
  frameRate(e) {
    return Be(e);
  },
  /**
   * 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(e) {
    return parseInt(e, 10);
  },
  /**
   * Specifies the timescale in units per seconds
   *
   * @param {string} value
   *        value of attribute as a string
   * @return {number}
   *         The parsed timescale
   */
  timescale(e) {
    return parseInt(e, 10);
  },
  /**
   * Specifies the presentationTimeOffset.
   *
   * @param {string} value
   *        value of the attribute as a string
   *
   * @return {number}
   *         The parsed presentationTimeOffset
   */
  presentationTimeOffset(e) {
    return parseInt(e, 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(e) {
    const n = parseInt(e, 10);
    return isNaN(n) ? y(e) : n;
  },
  /**
   * 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(e) {
    return parseInt(e, 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(e) {
    return parseInt(e, 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(e) {
    return parseInt(e, 10);
  },
  /**
   * Specifies the presentationTime.
   *
   * @param {string} value
   *        value of the attribute as a string
   *
   * @return {number}
   *         The parsed presentationTime
   */
  presentationTime(e) {
    return parseInt(e, 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(e) {
    return e;
  }
}, S = (e) => e && e.attributes ? W(e.attributes).reduce((n, t) => {
  const r = V[t.name] || V.DEFAULT;
  return n[t.name] = r(t.value), n;
}, {}) : {}, xe = {
  "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",
  // ISO_IEC 23009-1_2022 5.8.5.2.2 The mp4 Protection Scheme
  "urn:mpeg:dash:mp4protection:2011": "mp4protection"
}, _ = (e, n) => n.length ? P(e.map(function(t) {
  return n.map(function(r) {
    const i = A(r), o = L(t.baseUrl, i), s = E(S(r), {
      baseUrl: o
    });
    return o !== i && !s.serviceLocation && t.serviceLocation && (s.serviceLocation = t.serviceLocation), s;
  });
})) : e, v = (e) => {
  const n = f(e, "SegmentTemplate")[0], t = f(e, "SegmentList")[0], r = t && f(t, "SegmentURL").map((d) => E({
    tag: "SegmentURL"
  }, S(d))), i = f(e, "SegmentBase")[0], o = t || n, s = o && f(o, "SegmentTimeline")[0], c = t || i || n, a = c && f(c, "Initialization")[0], u = n && S(n);
  u && a ? u.initialization = a && S(a) : u && u.initialization && (u.initialization = {
    sourceURL: u.initialization
  });
  const m = {
    template: u,
    segmentTimeline: s && f(s, "S").map((d) => S(d)),
    list: t && E(S(t), {
      segmentUrls: r,
      initialization: S(a)
    }),
    base: i && E(S(i), {
      initialization: S(a)
    })
  };
  return Object.keys(m).forEach((d) => {
    m[d] || delete m[d];
  }), m;
}, we = (e, n, t) => (r) => {
  const i = f(r, "BaseURL"), o = _(n, i), s = E(e, S(r)), c = v(r);
  return o.map((a) => ({
    segmentInfo: E(t, c),
    attributes: E(s, a)
  }));
}, Fe = (e) => e.reduce((n, t) => {
  const r = S(t);
  r.schemeIdUri && (r.schemeIdUri = r.schemeIdUri.toLowerCase());
  const i = xe[r.schemeIdUri];
  if (i) {
    n[i] = {
      attributes: r
    };
    const o = f(t, "cenc:pssh")[0];
    if (o) {
      const s = A(o);
      n[i].pssh = s && J(s);
    }
  }
  return n;
}, {}), Ge = (e) => {
  if (e.schemeIdUri === "urn:scte:dash:cc:cea-608:2015")
    return (typeof e.value != "string" ? [] : e.value.split(";")).map((t) => {
      let r, i;
      return i = t, /^CC\d=/.test(t) ? [r, i] = t.split("=") : /^CC\d$/.test(t) && (r = t), {
        channel: r,
        language: i
      };
    });
  if (e.schemeIdUri === "urn:scte:dash:cc:cea-708:2015")
    return (typeof e.value != "string" ? [] : e.value.split(";")).map((t) => {
      const r = {
        // 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(t)) {
        const [i, o = ""] = t.split("=");
        r.channel = i, r.language = t, o.split(",").forEach((s) => {
          const [c, a] = s.split(":");
          c === "lang" ? r.language = a : c === "er" ? r.easyReader = Number(a) : c === "war" ? r.aspectRatio = Number(a) : c === "3D" && (r["3D"] = Number(a));
        });
      } else
        r.language = t;
      return r.channel && (r.channel = "SERVICE" + r.channel), r;
    });
}, ze = (e) => P(f(e.node, "EventStream").map((n) => {
  const t = S(n), r = t.schemeIdUri;
  return f(n, "Event").map((i) => {
    const o = S(i), s = o.presentationTime || 0, c = t.timescale || 1, a = o.duration || 0, u = s / c + e.attributes.start;
    return {
      schemeIdUri: r,
      value: t.value,
      id: o.id,
      start: u,
      end: u + a / c,
      messageData: A(i) || o.messageData,
      contentEncoding: t.contentEncoding,
      presentationTimeOffset: t.presentationTimeOffset || 0
    };
  });
})), $e = (e, n, t) => (r) => {
  const i = S(r), o = _(n, f(r, "BaseURL")), s = f(r, "Role")[0], c = {
    role: S(s)
  };
  let a = E(e, i, c);
  const u = f(r, "Accessibility")[0], m = Ge(S(u));
  m && (a = E(a, {
    captionServices: m
  }));
  const d = f(r, "Label")[0];
  if (d && d.childNodes.length) {
    const I = d.childNodes[0].nodeValue.trim();
    a = E(a, {
      label: I
    });
  }
  const p = Fe(f(r, "ContentProtection"));
  Object.keys(p).length && (a = E(a, {
    contentProtection: p
  }));
  const h = v(r), l = f(r, "Representation"), g = E(t, h);
  return P(l.map(we(a, o, g)));
}, He = (e, n) => (t, r) => {
  const i = _(n, f(t.node, "BaseURL")), o = E(e, {
    periodStart: t.attributes.start
  });
  typeof t.attributes.duration == "number" && (o.periodDuration = t.attributes.duration);
  const s = f(t.node, "AdaptationSet"), c = v(t.node);
  return P(s.map($e(o, i, c)));
}, Ve = (e, n) => {
  if (e.length > 1 && n({
    type: "warn",
    message: "The MPD manifest should contain no more than one ContentSteering tag"
  }), !e.length)
    return null;
  const t = E({
    serverURL: A(e[0])
  }, S(e[0]));
  return t.queryBeforeStart = t.queryBeforeStart === "true", t;
}, qe = ({
  attributes: e,
  priorPeriodAttributes: n,
  mpdType: t
}) => typeof e.start == "number" ? e.start : n && typeof n.start == "number" && typeof n.duration == "number" ? n.start + n.duration : !n && t === "static" ? 0 : null, We = (e, n = {}) => {
  const {
    manifestUri: t = "",
    NOW: r = Date.now(),
    clientOffset: i = 0,
    // TODO: For now, we are expecting an eventHandler callback function
    // to be passed into the mpd parser as an option.
    // In the future, we should enable stream parsing by using the Stream class from vhs-utils.
    // This will support new features including a standardized event handler.
    // See the m3u8 parser for examples of how stream parsing is currently used for HLS parsing.
    // https://github.com/videojs/vhs-utils/blob/88d6e10c631e57a5af02c5a62bc7376cd456b4f5/src/stream.js#L9
    eventHandler: o = function() {
    }
  } = n, s = f(e, "Period");
  if (!s.length)
    throw new Error(R.INVALID_NUMBER_OF_PERIOD);
  const c = f(e, "Location"), a = S(e), u = _([{
    baseUrl: t
  }], f(e, "BaseURL")), m = f(e, "ContentSteering");
  a.type = a.type || "static", a.sourceDuration = a.mediaPresentationDuration || 0, a.NOW = r, a.clientOffset = i, c.length && (a.locations = c.map(A));
  const d = [];
  return s.forEach((p, h) => {
    const l = S(p), g = d[h - 1];
    l.start = qe({
      attributes: l,
      priorPeriodAttributes: g ? g.attributes : null,
      mpdType: a.type
    }), d.push({
      node: p,
      attributes: l
    });
  }), {
    locations: a.locations,
    contentSteeringInfo: Ve(m, o),
    // TODO: There are occurences where this `representationInfo` array contains undesired
    // duplicates. This generally occurs when there are multiple BaseURL nodes that are
    // direct children of the MPD node. When we attempt to resolve URLs from a combination of the
    // parent BaseURL and a child BaseURL, and the value does not resolve,
    // we end up returning the child BaseURL multiple times.
    // We need to determine a way to remove these duplicates in a safe way.
    // See: https://github.com/videojs/mpd-parser/pull/17#discussion_r162750527
    representationInfo: P(d.map(He(a, u))),
    eventStream: P(d.map(ze))
  };
}, K = (e) => {
  if (e === "")
    throw new Error(R.DASH_EMPTY_MANIFEST);
  const n = new Q.DOMParser();
  let t, r;
  try {
    t = n.parseFromString(e, "application/xml"), r = t && t.documentElement.tagName === "MPD" ? t.documentElement : null;
  } catch {
  }
  if (!r || r && r.getElementsByTagName("parsererror").length > 0)
    throw new Error(R.DASH_INVALID_XML);
  return r;
}, Ye = (e) => {
  const n = f(e, "UTCTiming")[0];
  if (!n)
    return null;
  const t = S(n);
  switch (t.schemeIdUri) {
    case "urn:mpeg:dash:utc:http-head:2014":
    case "urn:mpeg:dash:utc:http-head:2012":
      t.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":
      t.method = "GET";
      break;
    case "urn:mpeg:dash:utc:direct:2014":
    case "urn:mpeg:dash:utc:direct:2012":
      t.method = "DIRECT", t.value = Date.parse(t.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(R.UNSUPPORTED_UTC_TIMING_SCHEME);
  }
  return t;
}, Qe = (e, n = {}) => {
  const t = We(K(e), n), r = Ce(t.representationInfo);
  return be({
    dashPlaylists: r,
    locations: t.locations,
    contentSteering: t.contentSteeringInfo,
    sidxMapping: n.sidxMapping,
    previousManifest: n.previousManifest,
    eventStream: t.eventStream
  });
}, et = (e) => Ye(K(e));
export {
  se as addSidxSegmentsToPlaylist,
  le as generateSidxKey,
  We as inheritAttributes,
  Qe as parse,
  et as parseUTCTiming,
  K as stringToMpdXml,
  be as toM3u8,
  Ce as toPlaylists
};
//# sourceMappingURL=mpd-parser.es.js.map
