const k = [];
for (let e = 0; e < 256; ++e)
  k.push((e + 256).toString(16).slice(1));
function ft(e, t = 0) {
  return (k[e[t + 0]] + k[e[t + 1]] + k[e[t + 2]] + k[e[t + 3]] + "-" + k[e[t + 4]] + k[e[t + 5]] + "-" + k[e[t + 6]] + k[e[t + 7]] + "-" + k[e[t + 8]] + k[e[t + 9]] + "-" + k[e[t + 10]] + k[e[t + 11]] + k[e[t + 12]] + k[e[t + 13]] + k[e[t + 14]] + k[e[t + 15]]).toLowerCase();
}
let Ce;
const mt = new Uint8Array(16);
function ct() {
  if (!Ce) {
    if (typeof crypto > "u" || !crypto.getRandomValues)
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    Ce = crypto.getRandomValues.bind(crypto);
  }
  return Ce(mt);
}
const pt = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), je = { randomUUID: pt };
function Xe(e, t, i) {
  if (je.randomUUID && !e)
    return je.randomUUID();
  e = e || {};
  const r = e.random || (e.rng || ct)();
  return r[6] = r[6] & 15 | 64, r[8] = r[8] & 63 | 128, ft(r);
}
class Se {
  constructor(t, i = [], r) {
    this.worker = new Worker(t, { type: "module" }), this.listeners = {}, this.persistentEvents = i, this.worker.onmessage = this.handleWorkerMessage.bind(this), r && (this.port = r, this.worker.postMessage({ cmd: "port", data: r }, { transfer: [r] }));
  }
  setupPort(t) {
    this.port = t, this.worker.postMessage({ cmd: "port", data: t }, { transfer: [t] });
  }
  handleWorkerMessage(t) {
    this.listeners[t.data.request_id] && (this.listeners[t.data.request_id](t.data.res), this.persistentEvents.includes(t.data.request_id) || delete this.listeners[t.data.request_id]);
  }
  addPersistentListener(t, i) {
    this.persistentEvents.includes(t) || this.persistentEvents.push(t), this.listeners[t] = i;
  }
  async sendMessage(t, i = {}, r = [], a = !0) {
    const n = Xe(), o = a ? ke(i) : i;
    return new Promise((l, p) => {
      try {
        const y = {
          cmd: t,
          request_id: n,
          data: o
        };
        this.worker.postMessage(y, r), this.listeners[n] = (_) => {
          l(_);
        };
      } catch (y) {
        p(new Error("Failed to send message to worker: " + y));
      }
    });
  }
  terminate() {
    this.worker.terminate(), this.listeners = {};
  }
}
function ke(e) {
  if (e === null || typeof e != "object")
    return e;
  const t = [
    ArrayBuffer,
    Blob,
    EncodedVideoChunk,
    ImageBitmap,
    EncodedAudioChunk,
    OffscreenCanvas,
    Uint8Array,
    VideoFrame,
    FileSystemFileHandle,
    MessageChannel,
    MessagePort
  ];
  for (const a of t)
    if (e instanceof a)
      return e;
  if (Array.isArray(e))
    return e.map((a) => ke(a));
  const i = e && e.__v_raw ? e.__v_raw : e, r = {};
  for (const a in i) {
    if (a.startsWith("__v_"))
      continue;
    const n = i[a];
    typeof n != "function" && (r[a] = ke(n));
  }
  return r;
}
var xe = (e, t, i) => {
  if (!t.has(e))
    throw TypeError("Cannot " + i);
}, s = (e, t, i) => (xe(e, t, "read from private field"), i ? i.call(e) : t.get(e)), f = (e, t, i) => {
  if (t.has(e))
    throw TypeError("Cannot add the same private member more than once");
  t instanceof WeakSet ? t.add(e) : t.set(e, i);
}, S = (e, t, i, r) => (xe(e, t, "write to private field"), t.set(e, i), i), gt = (e, t, i, r) => ({
  set _(a) {
    S(e, t, a);
  },
  get _() {
    return s(e, t, r);
  }
}), m = (e, t, i) => (xe(e, t, "access private method"), i), c = new Uint8Array(8), O = new DataView(c.buffer), C = (e) => [(e % 256 + 256) % 256], g = (e) => (O.setUint16(0, e, !1), [c[0], c[1]]), wt = (e) => (O.setInt16(0, e, !1), [c[0], c[1]]), Ze = (e) => (O.setUint32(0, e, !1), [c[1], c[2], c[3]]), h = (e) => (O.setUint32(0, e, !1), [c[0], c[1], c[2], c[3]]), yt = (e) => (O.setInt32(0, e, !1), [c[0], c[1], c[2], c[3]]), j = (e) => (O.setUint32(0, Math.floor(e / 2 ** 32), !1), O.setUint32(4, e, !1), [c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]), Oe = (e) => (O.setInt16(0, 2 ** 8 * e, !1), [c[0], c[1]]), I = (e) => (O.setInt32(0, 2 ** 16 * e, !1), [c[0], c[1], c[2], c[3]]), Te = (e) => (O.setInt32(0, 2 ** 30 * e, !1), [c[0], c[1], c[2], c[3]]), M = (e, t = !1) => {
  let i = Array(e.length).fill(null).map((r, a) => e.charCodeAt(a));
  return t && i.push(0), i;
}, me = (e) => e && e[e.length - 1], Be = (e) => {
  let t;
  for (let i of e)
    (!t || i.presentationTimestamp > t.presentationTimestamp) && (t = i);
  return t;
}, x = (e, t, i = !0) => {
  let r = e * t;
  return i ? Math.round(r) : r;
}, Ke = (e) => {
  let t = e * (Math.PI / 180), i = Math.cos(t), r = Math.sin(t);
  return [
    i,
    r,
    0,
    -r,
    i,
    0,
    0,
    0,
    1
  ];
}, Qe = Ke(0), Ye = (e) => [
  I(e[0]),
  I(e[1]),
  Te(e[2]),
  I(e[3]),
  I(e[4]),
  Te(e[5]),
  I(e[6]),
  I(e[7]),
  Te(e[8])
], ee = (e) => !e || typeof e != "object" ? e : Array.isArray(e) ? e.map(ee) : Object.fromEntries(Object.entries(e).map(([t, i]) => [t, ee(i)])), X = (e) => e >= 0 && e < 2 ** 32, v = (e, t, i) => ({
  type: e,
  contents: t && new Uint8Array(t.flat(10)),
  children: i
}), w = (e, t, i, r, a) => v(
  e,
  [C(t), Ze(i), r ?? []],
  a
), vt = (e) => {
  let t = 512;
  return e.fragmented ? v("ftyp", [
    M("iso5"),
    // Major brand
    h(t),
    // Minor version
    // Compatible brands
    M("iso5"),
    M("iso6"),
    M("mp41")
  ]) : v("ftyp", [
    M("isom"),
    // Major brand
    h(t),
    // Minor version
    // Compatible brands
    M("isom"),
    e.holdsAvc ? M("avc1") : [],
    M("mp41")
  ]);
}, be = (e) => ({ type: "mdat", largeSize: e }), Ct = (e) => ({ type: "free", size: e }), he = (e, t, i = !1) => v("moov", null, [
  Tt(t, e),
  ...e.map((r) => St(r, t)),
  i ? Jt(e) : null
]), Tt = (e, t) => {
  let i = x(Math.max(
    0,
    ...t.filter((o) => o.samples.length > 0).map((o) => {
      const l = Be(o.samples);
      return l.presentationTimestamp + l.duration;
    })
  ), ze), r = Math.max(...t.map((o) => o.id)) + 1, a = !X(e) || !X(i), n = a ? j : h;
  return w("mvhd", +a, 0, [
    n(e),
    // Creation time
    n(e),
    // Modification time
    h(ze),
    // Timescale
    n(i),
    // Duration
    I(1),
    // Preferred rate
    Oe(1),
    // Preferred volume
    Array(10).fill(0),
    // Reserved
    Ye(Qe),
    // Matrix
    Array(24).fill(0),
    // Pre-defined
    h(r)
    // Next track ID
  ]);
}, St = (e, t) => v("trak", null, [
  kt(e, t),
  bt(e, t)
]), kt = (e, t) => {
  let i = Be(e.samples), r = x(
    i ? i.presentationTimestamp + i.duration : 0,
    ze
  ), a = !X(t) || !X(r), n = a ? j : h, o;
  return e.info.type === "video" ? o = typeof e.info.rotation == "number" ? Ke(e.info.rotation) : e.info.rotation : o = Qe, w("tkhd", +a, 3, [
    n(t),
    // Creation time
    n(t),
    // Modification time
    h(e.id),
    // Track ID
    h(0),
    // Reserved
    n(r),
    // Duration
    Array(8).fill(0),
    // Reserved
    g(0),
    // Layer
    g(0),
    // Alternate group
    Oe(e.info.type === "audio" ? 1 : 0),
    // Volume
    g(0),
    // Reserved
    Ye(o),
    // Matrix
    I(e.info.type === "video" ? e.info.width : 0),
    // Track width
    I(e.info.type === "video" ? e.info.height : 0)
    // Track height
  ]);
}, bt = (e, t) => v("mdia", null, [
  _t(e, t),
  Et(e.info.type === "video" ? "vide" : "soun"),
  zt(e)
]), _t = (e, t) => {
  let i = Be(e.samples), r = x(
    i ? i.presentationTimestamp + i.duration : 0,
    e.timescale
  ), a = !X(t) || !X(r), n = a ? j : h;
  return w("mdhd", +a, 0, [
    n(t),
    // Creation time
    n(t),
    // Modification time
    h(e.timescale),
    // Timescale
    n(r),
    // Duration
    g(21956),
    // Language ("und", undetermined)
    g(0)
    // Quality
  ]);
}, Et = (e) => w("hdlr", 0, 0, [
  M("mhlr"),
  // Component type
  M(e),
  // Component subtype
  h(0),
  // Component manufacturer
  h(0),
  // Component flags
  h(0),
  // Component flags mask
  M("mp4-muxer-hdlr", !0)
  // Component name
]), zt = (e) => v("minf", null, [
  e.info.type === "video" ? At() : Mt(),
  Pt(),
  xt(e)
]), At = () => w("vmhd", 0, 1, [
  g(0),
  // Graphics mode
  g(0),
  // Opcolor R
  g(0),
  // Opcolor G
  g(0)
  // Opcolor B
]), Mt = () => w("smhd", 0, 0, [
  g(0),
  // Balance
  g(0)
  // Reserved
]), Pt = () => v("dinf", null, [
  Dt()
]), Dt = () => w("dref", 0, 0, [
  h(1)
  // Entry count
], [
  It()
]), It = () => w("url ", 0, 1), xt = (e) => {
  const t = e.compositionTimeOffsetTable.length > 1 || e.compositionTimeOffsetTable.some((i) => i.sampleCompositionTimeOffset !== 0);
  return v("stbl", null, [
    Ot(e),
    Gt(e),
    Xt(e),
    Zt(e),
    Kt(e),
    Qt(e),
    t ? Yt(e) : null
  ]);
}, Ot = (e) => w("stsd", 0, 0, [
  h(1)
  // Entry count
], [
  e.info.type === "video" ? Bt(
    li[e.info.codec],
    e
  ) : jt(
    ui[e.info.codec],
    e
  )
]), Bt = (e, t) => v(e, [
  Array(6).fill(0),
  // Reserved
  g(1),
  // Data reference index
  g(0),
  // Pre-defined
  g(0),
  // Reserved
  Array(12).fill(0),
  // Pre-defined
  g(t.info.width),
  // Width
  g(t.info.height),
  // Height
  h(4718592),
  // Horizontal resolution
  h(4718592),
  // Vertical resolution
  h(0),
  // Reserved
  g(1),
  // Frame count
  Array(32).fill(0),
  // Compressor name
  g(24),
  // Depth
  wt(65535)
  // Pre-defined
], [
  di[t.info.codec](t),
  t.info.decoderConfig.colorSpace ? Nt(t) : null
]), Ft = {
  bt709: 1,
  // ITU-R BT.709
  bt470bg: 5,
  // ITU-R BT.470BG
  smpte170m: 6
  // ITU-R BT.601 525 - SMPTE 170M
}, Ut = {
  bt709: 1,
  // ITU-R BT.709
  smpte170m: 6,
  // SMPTE 170M
  "iec61966-2-1": 13
  // IEC 61966-2-1
}, Wt = {
  rgb: 0,
  // Identity
  bt709: 1,
  // ITU-R BT.709
  bt470bg: 5,
  // ITU-R BT.470BG
  smpte170m: 6
  // SMPTE 170M
}, Nt = (e) => v("colr", [
  M("nclx"),
  // Colour type
  g(Ft[e.info.decoderConfig.colorSpace.primaries]),
  // Colour primaries
  g(Ut[e.info.decoderConfig.colorSpace.transfer]),
  // Transfer characteristics
  g(Wt[e.info.decoderConfig.colorSpace.matrix]),
  // Matrix coefficients
  C((e.info.decoderConfig.colorSpace.fullRange ? 1 : 0) << 7)
  // Full range flag
]), Rt = (e) => e.info.decoderConfig && v("avcC", [
  // For AVC, description is an AVCDecoderConfigurationRecord, so nothing else to do here
  ...new Uint8Array(e.info.decoderConfig.description)
]), Vt = (e) => e.info.decoderConfig && v("hvcC", [
  // For HEVC, description is a HEVCDecoderConfigurationRecord, so nothing else to do here
  ...new Uint8Array(e.info.decoderConfig.description)
]), Lt = (e) => {
  if (!e.info.decoderConfig)
    return null;
  let t = e.info.decoderConfig;
  if (!t.colorSpace)
    throw new Error("'colorSpace' is required in the decoder config for VP9.");
  let i = t.codec.split("."), r = Number(i[1]), a = Number(i[2]), l = (Number(i[3]) << 4) + (0 << 1) + Number(t.colorSpace.fullRange);
  return w("vpcC", 1, 0, [
    C(r),
    // Profile
    C(a),
    // Level
    C(l),
    // Bit depth, chroma subsampling, full range
    C(2),
    // Colour primaries
    C(2),
    // Transfer characteristics
    C(2),
    // Matrix coefficients
    g(0)
    // Codec initialization data size
  ]);
}, $t = () => {
  let i = (1 << 7) + 1;
  return v("av1C", [
    i,
    0,
    0,
    0
  ]);
}, jt = (e, t) => v(e, [
  Array(6).fill(0),
  // Reserved
  g(1),
  // Data reference index
  g(0),
  // Version
  g(0),
  // Revision level
  h(0),
  // Vendor
  g(t.info.numberOfChannels),
  // Number of channels
  g(16),
  // Sample size (bits)
  g(0),
  // Compression ID
  g(0),
  // Packet size
  I(t.info.sampleRate)
  // Sample rate
], [
  fi[t.info.codec](t)
]), qt = (e) => {
  let t = new Uint8Array(e.info.decoderConfig.description);
  return w("esds", 0, 0, [
    // https://stackoverflow.com/a/54803118
    h(58753152),
    // TAG(3) = Object Descriptor ([2])
    C(32 + t.byteLength),
    // length of this OD (which includes the next 2 tags)
    g(1),
    // ES_ID = 1
    C(0),
    // flags etc = 0
    h(75530368),
    // TAG(4) = ES Descriptor ([2]) embedded in above OD
    C(18 + t.byteLength),
    // length of this ESD
    C(64),
    // MPEG-4 Audio
    C(21),
    // stream type(6bits)=5 audio, flags(2bits)=1
    Ze(0),
    // 24bit buffer size
    h(130071),
    // max bitrate
    h(130071),
    // avg bitrate
    h(92307584),
    // TAG(5) = ASC ([2],[3]) embedded in above OD
    C(t.byteLength),
    // length
    ...t,
    h(109084800),
    // TAG(6)
    C(1),
    // length
    C(2)
    // data
  ]);
}, Ht = (e) => {
  var a;
  let t = 3840, i = 0;
  const r = (a = e.info.decoderConfig) == null ? void 0 : a.description;
  if (r) {
    if (r.byteLength < 18)
      throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");
    const n = ArrayBuffer.isView(r) ? new DataView(r.buffer, r.byteOffset, r.byteLength) : new DataView(r);
    t = n.getUint16(10, !0), i = n.getInt16(14, !0);
  }
  return v("dOps", [
    C(0),
    // Version
    C(e.info.numberOfChannels),
    // OutputChannelCount
    g(t),
    h(e.info.sampleRate),
    // InputSampleRate
    Oe(i),
    // OutputGain
    C(0)
    // ChannelMappingFamily
  ]);
}, Gt = (e) => w("stts", 0, 0, [
  h(e.timeToSampleTable.length),
  // Number of entries
  e.timeToSampleTable.map((t) => [
    // Time-to-sample table
    h(t.sampleCount),
    // Sample count
    h(t.sampleDelta)
    // Sample duration
  ])
]), Xt = (e) => {
  if (e.samples.every((i) => i.type === "key"))
    return null;
  let t = [...e.samples.entries()].filter(([, i]) => i.type === "key");
  return w("stss", 0, 0, [
    h(t.length),
    // Number of entries
    t.map(([i]) => h(i + 1))
    // Sync sample table
  ]);
}, Zt = (e) => w("stsc", 0, 0, [
  h(e.compactlyCodedChunkTable.length),
  // Number of entries
  e.compactlyCodedChunkTable.map((t) => [
    // Sample-to-chunk table
    h(t.firstChunk),
    // First chunk
    h(t.samplesPerChunk),
    // Samples per chunk
    h(1)
    // Sample description index
  ])
]), Kt = (e) => w("stsz", 0, 0, [
  h(0),
  // Sample size (0 means non-constant size)
  h(e.samples.length),
  // Number of entries
  e.samples.map((t) => h(t.size))
  // Sample size table
]), Qt = (e) => e.finalizedChunks.length > 0 && me(e.finalizedChunks).offset >= 2 ** 32 ? w("co64", 0, 0, [
  h(e.finalizedChunks.length),
  // Number of entries
  e.finalizedChunks.map((t) => j(t.offset))
  // Chunk offset table
]) : w("stco", 0, 0, [
  h(e.finalizedChunks.length),
  // Number of entries
  e.finalizedChunks.map((t) => h(t.offset))
  // Chunk offset table
]), Yt = (e) => w("ctts", 0, 0, [
  h(e.compositionTimeOffsetTable.length),
  // Number of entries
  e.compositionTimeOffsetTable.map((t) => [
    // Time-to-sample table
    h(t.sampleCount),
    // Sample count
    h(t.sampleCompositionTimeOffset)
    // Sample offset
  ])
]), Jt = (e) => v("mvex", null, e.map(ei)), ei = (e) => w("trex", 0, 0, [
  h(e.id),
  // Track ID
  h(1),
  // Default sample description index
  h(0),
  // Default sample duration
  h(0),
  // Default sample size
  h(0)
  // Default sample flags
]), qe = (e, t) => v("moof", null, [
  ti(e),
  ...t.map(ii)
]), ti = (e) => w("mfhd", 0, 0, [
  h(e)
  // Sequence number
]), Je = (e) => {
  let t = 0, i = 0, r = 0, a = 0, n = e.type === "delta";
  return i |= +n, n ? t |= 1 : t |= 2, t << 24 | i << 16 | r << 8 | a;
}, ii = (e) => v("traf", null, [
  si(e),
  ri(e),
  ai(e)
]), si = (e) => {
  let t = 0;
  t |= 8, t |= 16, t |= 32, t |= 131072;
  let i = e.currentChunk.samples[1] ?? e.currentChunk.samples[0], r = {
    duration: i.timescaleUnitsToNextSample,
    size: i.size,
    flags: Je(i)
  };
  return w("tfhd", 0, t, [
    h(e.id),
    // Track ID
    h(r.duration),
    // Default sample duration
    h(r.size),
    // Default sample size
    h(r.flags)
    // Default sample flags
  ]);
}, ri = (e) => w("tfdt", 1, 0, [
  j(x(e.currentChunk.startTimestamp, e.timescale))
  // Base Media Decode Time
]), ai = (e) => {
  let t = e.currentChunk.samples.map((B) => B.timescaleUnitsToNextSample), i = e.currentChunk.samples.map((B) => B.size), r = e.currentChunk.samples.map(Je), a = e.currentChunk.samples.map((B) => x(B.presentationTimestamp - B.decodeTimestamp, e.timescale)), n = new Set(t), o = new Set(i), l = new Set(r), p = new Set(a), y = l.size === 2 && r[0] !== r[1], _ = n.size > 1, W = o.size > 1, K = !y && l.size > 1, Q = p.size > 1 || [...p].some((B) => B !== 0), P = 0;
  return P |= 1, P |= 4 * +y, P |= 256 * +_, P |= 512 * +W, P |= 1024 * +K, P |= 2048 * +Q, w("trun", 1, P, [
    h(e.currentChunk.samples.length),
    // Sample count
    h(e.currentChunk.offset - e.currentChunk.moofOffset || 0),
    // Data offset
    y ? h(r[0]) : [],
    e.currentChunk.samples.map((B, oe) => [
      _ ? h(t[oe]) : [],
      // Sample duration
      W ? h(i[oe]) : [],
      // Sample size
      K ? h(r[oe]) : [],
      // Sample flags
      // Sample composition time offsets
      Q ? yt(a[oe]) : []
    ])
  ]);
}, ni = (e) => v("mfra", null, [
  ...e.map(oi),
  hi()
]), oi = (e, t) => w("tfra", 1, 0, [
  h(e.id),
  // Track ID
  h(63),
  // This specifies that traf number, trun number and sample number are 32-bit ints
  h(e.finalizedChunks.length),
  // Number of entries
  e.finalizedChunks.map((r) => [
    j(x(r.startTimestamp, e.timescale)),
    // Time
    j(r.moofOffset),
    // moof offset
    h(t + 1),
    // traf number
    h(1),
    // trun number
    h(1)
    // Sample number
  ])
]), hi = () => w("mfro", 0, 0, [
  // This value needs to be overwritten manually from the outside, where the actual size of the enclosing mfra box
  // is known
  h(0)
  // Size
]), li = {
  avc: "avc1",
  hevc: "hvc1",
  vp9: "vp09",
  av1: "av01"
}, di = {
  avc: Rt,
  hevc: Vt,
  vp9: Lt,
  av1: $t
}, ui = {
  aac: "mp4a",
  opus: "Opus"
}, fi = {
  aac: qt,
  opus: Ht
}, ve = class {
}, et = class extends ve {
  constructor() {
    super(...arguments), this.buffer = null;
  }
}, tt = class extends ve {
  constructor(e) {
    if (super(), this.options = e, typeof e != "object")
      throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");
    if (e.onData) {
      if (typeof e.onData != "function")
        throw new TypeError("options.onData, when provided, must be a function.");
      if (e.onData.length < 2)
        throw new TypeError(
          "options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs."
        );
    }
    if (e.chunked !== void 0 && typeof e.chunked != "boolean")
      throw new TypeError("options.chunked, when provided, must be a boolean.");
    if (e.chunkSize !== void 0 && (!Number.isInteger(e.chunkSize) || e.chunkSize < 1024))
      throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");
  }
}, mi = class extends ve {
  constructor(e, t) {
    if (super(), this.stream = e, this.options = t, !(e instanceof FileSystemWritableFileStream))
      throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");
    if (t !== void 0 && typeof t != "object")
      throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");
    if (t && t.chunkSize !== void 0 && (!Number.isInteger(t.chunkSize) || t.chunkSize <= 0))
      throw new TypeError("options.chunkSize, when provided, must be a positive integer");
  }
}, N, q, it = class {
  constructor() {
    this.pos = 0, f(this, N, new Uint8Array(8)), f(this, q, new DataView(s(this, N).buffer)), this.offsets = /* @__PURE__ */ new WeakMap();
  }
  /** Sets the current position for future writes to a new one. */
  seek(e) {
    this.pos = e;
  }
  writeU32(e) {
    s(this, q).setUint32(0, e, !1), this.write(s(this, N).subarray(0, 4));
  }
  writeU64(e) {
    s(this, q).setUint32(0, Math.floor(e / 2 ** 32), !1), s(this, q).setUint32(4, e, !1), this.write(s(this, N).subarray(0, 8));
  }
  writeAscii(e) {
    for (let t = 0; t < e.length; t++)
      s(this, q).setUint8(t % 8, e.charCodeAt(t)), t % 8 === 7 && this.write(s(this, N));
    e.length % 8 !== 0 && this.write(s(this, N).subarray(0, e.length % 8));
  }
  writeBox(e) {
    if (this.offsets.set(e, this.pos), e.contents && !e.children)
      this.writeBoxHeader(e, e.size ?? e.contents.byteLength + 8), this.write(e.contents);
    else {
      let t = this.pos;
      if (this.writeBoxHeader(e, 0), e.contents && this.write(e.contents), e.children)
        for (let a of e.children)
          a && this.writeBox(a);
      let i = this.pos, r = e.size ?? i - t;
      this.seek(t), this.writeBoxHeader(e, r), this.seek(i);
    }
  }
  writeBoxHeader(e, t) {
    this.writeU32(e.largeSize ? 1 : t), this.writeAscii(e.type), e.largeSize && this.writeU64(t);
  }
  measureBoxHeader(e) {
    return 8 + (e.largeSize ? 8 : 0);
  }
  patchBox(e) {
    let t = this.pos;
    this.seek(this.offsets.get(e)), this.writeBox(e), this.seek(t);
  }
  measureBox(e) {
    if (e.contents && !e.children)
      return this.measureBoxHeader(e) + e.contents.byteLength;
    {
      let t = this.measureBoxHeader(e);
      if (e.contents && (t += e.contents.byteLength), e.children)
        for (let i of e.children)
          i && (t += this.measureBox(i));
      return t;
    }
  }
};
N = /* @__PURE__ */ new WeakMap();
q = /* @__PURE__ */ new WeakMap();
var le, $, ae, Y, de, _e, ci = class extends it {
  constructor(e) {
    super(), f(this, de), f(this, le, void 0), f(this, $, new ArrayBuffer(2 ** 16)), f(this, ae, new Uint8Array(s(this, $))), f(this, Y, 0), S(this, le, e);
  }
  write(e) {
    m(this, de, _e).call(this, this.pos + e.byteLength), s(this, ae).set(e, this.pos), this.pos += e.byteLength, S(this, Y, Math.max(s(this, Y), this.pos));
  }
  finalize() {
    m(this, de, _e).call(this, this.pos), s(this, le).buffer = s(this, $).slice(0, Math.max(s(this, Y), this.pos));
  }
};
le = /* @__PURE__ */ new WeakMap();
$ = /* @__PURE__ */ new WeakMap();
ae = /* @__PURE__ */ new WeakMap();
Y = /* @__PURE__ */ new WeakMap();
de = /* @__PURE__ */ new WeakSet();
_e = function(e) {
  let t = s(this, $).byteLength;
  for (; t < e; )
    t *= 2;
  if (t === s(this, $).byteLength)
    return;
  let i = new ArrayBuffer(t), r = new Uint8Array(i);
  r.set(s(this, ae), 0), S(this, $, i), S(this, ae, r);
};
var pi = 2 ** 24, gi = 2, te, R, J, U, A, ce, Ee, Fe, st, Ue, rt, ie, pe, We = class extends it {
  constructor(e) {
    var t, i;
    super(), f(this, ce), f(this, Fe), f(this, Ue), f(this, ie), f(this, te, void 0), f(this, R, []), f(this, J, void 0), f(this, U, void 0), f(this, A, []), S(this, te, e), S(this, J, ((t = e.options) == null ? void 0 : t.chunked) ?? !1), S(this, U, ((i = e.options) == null ? void 0 : i.chunkSize) ?? pi);
  }
  write(e) {
    s(this, R).push({
      data: e.slice(),
      start: this.pos
    }), this.pos += e.byteLength;
  }
  flush() {
    var i, r;
    if (s(this, R).length === 0)
      return;
    let e = [], t = [...s(this, R)].sort((a, n) => a.start - n.start);
    e.push({
      start: t[0].start,
      size: t[0].data.byteLength
    });
    for (let a = 1; a < t.length; a++) {
      let n = e[e.length - 1], o = t[a];
      o.start <= n.start + n.size ? n.size = Math.max(n.size, o.start + o.data.byteLength - n.start) : e.push({
        start: o.start,
        size: o.data.byteLength
      });
    }
    for (let a of e) {
      a.data = new Uint8Array(a.size);
      for (let n of s(this, R))
        a.start <= n.start && n.start < a.start + a.size && a.data.set(n.data, n.start - a.start);
      s(this, J) ? (m(this, ce, Ee).call(this, a.data, a.start), m(this, ie, pe).call(this)) : (r = (i = s(this, te).options).onData) == null || r.call(i, a.data, a.start);
    }
    s(this, R).length = 0;
  }
  finalize() {
    s(this, J) && m(this, ie, pe).call(this, !0);
  }
};
te = /* @__PURE__ */ new WeakMap();
R = /* @__PURE__ */ new WeakMap();
J = /* @__PURE__ */ new WeakMap();
U = /* @__PURE__ */ new WeakMap();
A = /* @__PURE__ */ new WeakMap();
ce = /* @__PURE__ */ new WeakSet();
Ee = function(e, t) {
  let i = s(this, A).findIndex((l) => l.start <= t && t < l.start + s(this, U));
  i === -1 && (i = m(this, Ue, rt).call(this, t));
  let r = s(this, A)[i], a = t - r.start, n = e.subarray(0, Math.min(s(this, U) - a, e.byteLength));
  r.data.set(n, a);
  let o = {
    start: a,
    end: a + n.byteLength
  };
  if (m(this, Fe, st).call(this, r, o), r.written[0].start === 0 && r.written[0].end === s(this, U) && (r.shouldFlush = !0), s(this, A).length > gi) {
    for (let l = 0; l < s(this, A).length - 1; l++)
      s(this, A)[l].shouldFlush = !0;
    m(this, ie, pe).call(this);
  }
  n.byteLength < e.byteLength && m(this, ce, Ee).call(this, e.subarray(n.byteLength), t + n.byteLength);
};
Fe = /* @__PURE__ */ new WeakSet();
st = function(e, t) {
  let i = 0, r = e.written.length - 1, a = -1;
  for (; i <= r; ) {
    let n = Math.floor(i + (r - i + 1) / 2);
    e.written[n].start <= t.start ? (i = n + 1, a = n) : r = n - 1;
  }
  for (e.written.splice(a + 1, 0, t), (a === -1 || e.written[a].end < t.start) && a++; a < e.written.length - 1 && e.written[a].end >= e.written[a + 1].start; )
    e.written[a].end = Math.max(e.written[a].end, e.written[a + 1].end), e.written.splice(a + 1, 1);
};
Ue = /* @__PURE__ */ new WeakSet();
rt = function(e) {
  let i = {
    start: Math.floor(e / s(this, U)) * s(this, U),
    data: new Uint8Array(s(this, U)),
    written: [],
    shouldFlush: !1
  };
  return s(this, A).push(i), s(this, A).sort((r, a) => r.start - a.start), s(this, A).indexOf(i);
};
ie = /* @__PURE__ */ new WeakSet();
pe = function(e = !1) {
  var t, i;
  for (let r = 0; r < s(this, A).length; r++) {
    let a = s(this, A)[r];
    if (!(!a.shouldFlush && !e)) {
      for (let n of a.written)
        (i = (t = s(this, te).options).onData) == null || i.call(
          t,
          a.data.subarray(n.start, n.end),
          a.start + n.start
        );
      s(this, A).splice(r--, 1);
    }
  }
};
var wi = class extends We {
  constructor(e) {
    var t;
    super(new tt({
      onData: (i, r) => e.stream.write({
        type: "write",
        data: i,
        position: r
      }),
      chunked: !0,
      chunkSize: (t = e.options) == null ? void 0 : t.chunkSize
    }));
  }
}, ze = 1e3, yi = ["avc", "hevc", "vp9", "av1"], vi = ["aac", "opus"], Ci = 2082844800, Ti = ["strict", "offset", "cross-track-offset"], d, u, ge, z, b, T, H, G, Ne, V, L, se, Ae, at, Me, nt, Re, ot, Pe, ht, Ve, lt, ue, De, D, F, Le, dt, re, we, ye, $e, Z, ne, fe, Ie, Si = class {
  constructor(e) {
    if (f(this, Ae), f(this, Me), f(this, Re), f(this, Pe), f(this, Ve), f(this, ue), f(this, D), f(this, Le), f(this, re), f(this, ye), f(this, Z), f(this, fe), f(this, d, void 0), f(this, u, void 0), f(this, ge, void 0), f(this, z, void 0), f(this, b, null), f(this, T, null), f(this, H, Math.floor(Date.now() / 1e3) + Ci), f(this, G, []), f(this, Ne, 1), f(this, V, []), f(this, L, []), f(this, se, !1), m(this, Ae, at).call(this, e), e.video = ee(e.video), e.audio = ee(e.audio), e.fastStart = ee(e.fastStart), this.target = e.target, S(this, d, {
      firstTimestampBehavior: "strict",
      ...e
    }), e.target instanceof et)
      S(this, u, new ci(e.target));
    else if (e.target instanceof tt)
      S(this, u, new We(e.target));
    else if (e.target instanceof mi)
      S(this, u, new wi(e.target));
    else
      throw new Error(`Invalid target: ${e.target}`);
    m(this, Pe, ht).call(this), m(this, Me, nt).call(this);
  }
  addVideoChunk(e, t, i, r) {
    if (!(e instanceof EncodedVideoChunk))
      throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");
    if (t && typeof t != "object")
      throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");
    if (i !== void 0 && (!Number.isFinite(i) || i < 0))
      throw new TypeError(
        "addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number."
      );
    if (r !== void 0 && !Number.isFinite(r))
      throw new TypeError(
        "addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number."
      );
    let a = new Uint8Array(e.byteLength);
    e.copyTo(a), this.addVideoChunkRaw(
      a,
      e.type,
      i ?? e.timestamp,
      e.duration,
      t,
      r
    );
  }
  addVideoChunkRaw(e, t, i, r, a, n) {
    if (!(e instanceof Uint8Array))
      throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");
    if (t !== "key" && t !== "delta")
      throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");
    if (!Number.isFinite(i) || i < 0)
      throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");
    if (!Number.isFinite(r) || r < 0)
      throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");
    if (a && typeof a != "object")
      throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");
    if (n !== void 0 && !Number.isFinite(n))
      throw new TypeError(
        "addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number."
      );
    if (m(this, fe, Ie).call(this), !s(this, d).video)
      throw new Error("No video track declared.");
    if (typeof s(this, d).fastStart == "object" && s(this, b).samples.length === s(this, d).fastStart.expectedVideoChunks)
      throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${s(this, d).fastStart.expectedVideoChunks}).`);
    let o = m(this, ue, De).call(this, s(this, b), e, t, i, r, a, n);
    if (s(this, d).fastStart === "fragmented" && s(this, T)) {
      for (; s(this, L).length > 0 && s(this, L)[0].decodeTimestamp <= o.decodeTimestamp; ) {
        let l = s(this, L).shift();
        m(this, D, F).call(this, s(this, T), l);
      }
      o.decodeTimestamp <= s(this, T).lastDecodeTimestamp ? m(this, D, F).call(this, s(this, b), o) : s(this, V).push(o);
    } else
      m(this, D, F).call(this, s(this, b), o);
  }
  addAudioChunk(e, t, i) {
    if (!(e instanceof EncodedAudioChunk))
      throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");
    if (t && typeof t != "object")
      throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");
    if (i !== void 0 && (!Number.isFinite(i) || i < 0))
      throw new TypeError(
        "addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number."
      );
    let r = new Uint8Array(e.byteLength);
    e.copyTo(r), this.addAudioChunkRaw(r, e.type, i ?? e.timestamp, e.duration, t);
  }
  addAudioChunkRaw(e, t, i, r, a) {
    if (!(e instanceof Uint8Array))
      throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");
    if (t !== "key" && t !== "delta")
      throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");
    if (!Number.isFinite(i) || i < 0)
      throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");
    if (!Number.isFinite(r) || r < 0)
      throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");
    if (a && typeof a != "object")
      throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");
    if (m(this, fe, Ie).call(this), !s(this, d).audio)
      throw new Error("No audio track declared.");
    if (typeof s(this, d).fastStart == "object" && s(this, T).samples.length === s(this, d).fastStart.expectedAudioChunks)
      throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${s(this, d).fastStart.expectedAudioChunks}).`);
    let n = m(this, ue, De).call(this, s(this, T), e, t, i, r, a);
    if (s(this, d).fastStart === "fragmented" && s(this, b)) {
      for (; s(this, V).length > 0 && s(this, V)[0].decodeTimestamp <= n.decodeTimestamp; ) {
        let o = s(this, V).shift();
        m(this, D, F).call(this, s(this, b), o);
      }
      n.decodeTimestamp <= s(this, b).lastDecodeTimestamp ? m(this, D, F).call(this, s(this, T), n) : s(this, L).push(n);
    } else
      m(this, D, F).call(this, s(this, T), n);
  }
  /** Finalizes the file, making it ready for use. Must be called after all video and audio chunks have been added. */
  finalize() {
    if (s(this, se))
      throw new Error("Cannot finalize a muxer more than once.");
    if (s(this, d).fastStart === "fragmented") {
      for (let t of s(this, V))
        m(this, D, F).call(this, s(this, b), t);
      for (let t of s(this, L))
        m(this, D, F).call(this, s(this, T), t);
      m(this, ye, $e).call(this, !1);
    } else
      s(this, b) && m(this, re, we).call(this, s(this, b)), s(this, T) && m(this, re, we).call(this, s(this, T));
    let e = [s(this, b), s(this, T)].filter(Boolean);
    if (s(this, d).fastStart === "in-memory") {
      let t;
      for (let r = 0; r < 2; r++) {
        let a = he(e, s(this, H)), n = s(this, u).measureBox(a);
        t = s(this, u).measureBox(s(this, z));
        let o = s(this, u).pos + n + t;
        for (let l of s(this, G)) {
          l.offset = o;
          for (let { data: p } of l.samples)
            o += p.byteLength, t += p.byteLength;
        }
        if (o < 2 ** 32)
          break;
        t >= 2 ** 32 && (s(this, z).largeSize = !0);
      }
      let i = he(e, s(this, H));
      s(this, u).writeBox(i), s(this, z).size = t, s(this, u).writeBox(s(this, z));
      for (let r of s(this, G))
        for (let a of r.samples)
          s(this, u).write(a.data), a.data = null;
    } else if (s(this, d).fastStart === "fragmented") {
      let t = s(this, u).pos, i = ni(e);
      s(this, u).writeBox(i);
      let r = s(this, u).pos - t;
      s(this, u).seek(s(this, u).pos - 4), s(this, u).writeU32(r);
    } else {
      let t = s(this, u).offsets.get(s(this, z)), i = s(this, u).pos - t;
      s(this, z).size = i, s(this, z).largeSize = i >= 2 ** 32, s(this, u).patchBox(s(this, z));
      let r = he(e, s(this, H));
      if (typeof s(this, d).fastStart == "object") {
        s(this, u).seek(s(this, ge)), s(this, u).writeBox(r);
        let a = t - s(this, u).pos;
        s(this, u).writeBox(Ct(a));
      } else
        s(this, u).writeBox(r);
    }
    m(this, Z, ne).call(this), s(this, u).finalize(), S(this, se, !0);
  }
};
d = /* @__PURE__ */ new WeakMap();
u = /* @__PURE__ */ new WeakMap();
ge = /* @__PURE__ */ new WeakMap();
z = /* @__PURE__ */ new WeakMap();
b = /* @__PURE__ */ new WeakMap();
T = /* @__PURE__ */ new WeakMap();
H = /* @__PURE__ */ new WeakMap();
G = /* @__PURE__ */ new WeakMap();
Ne = /* @__PURE__ */ new WeakMap();
V = /* @__PURE__ */ new WeakMap();
L = /* @__PURE__ */ new WeakMap();
se = /* @__PURE__ */ new WeakMap();
Ae = /* @__PURE__ */ new WeakSet();
at = function(e) {
  if (typeof e != "object")
    throw new TypeError("The muxer requires an options object to be passed to its constructor.");
  if (!(e.target instanceof ve))
    throw new TypeError("The target must be provided and an instance of Target.");
  if (e.video) {
    if (!yi.includes(e.video.codec))
      throw new TypeError(`Unsupported video codec: ${e.video.codec}`);
    if (!Number.isInteger(e.video.width) || e.video.width <= 0)
      throw new TypeError(`Invalid video width: ${e.video.width}. Must be a positive integer.`);
    if (!Number.isInteger(e.video.height) || e.video.height <= 0)
      throw new TypeError(`Invalid video height: ${e.video.height}. Must be a positive integer.`);
    const t = e.video.rotation;
    if (typeof t == "number" && ![0, 90, 180, 270].includes(t))
      throw new TypeError(`Invalid video rotation: ${t}. Has to be 0, 90, 180 or 270.`);
    if (Array.isArray(t) && (t.length !== 9 || t.some((i) => typeof i != "number")))
      throw new TypeError(`Invalid video transformation matrix: ${t.join()}`);
    if (e.video.frameRate !== void 0 && (!Number.isInteger(e.video.frameRate) || e.video.frameRate <= 0))
      throw new TypeError(
        `Invalid video frame rate: ${e.video.frameRate}. Must be a positive integer.`
      );
  }
  if (e.audio) {
    if (!vi.includes(e.audio.codec))
      throw new TypeError(`Unsupported audio codec: ${e.audio.codec}`);
    if (!Number.isInteger(e.audio.numberOfChannels) || e.audio.numberOfChannels <= 0)
      throw new TypeError(
        `Invalid number of audio channels: ${e.audio.numberOfChannels}. Must be a positive integer.`
      );
    if (!Number.isInteger(e.audio.sampleRate) || e.audio.sampleRate <= 0)
      throw new TypeError(
        `Invalid audio sample rate: ${e.audio.sampleRate}. Must be a positive integer.`
      );
  }
  if (e.firstTimestampBehavior && !Ti.includes(e.firstTimestampBehavior))
    throw new TypeError(`Invalid first timestamp behavior: ${e.firstTimestampBehavior}`);
  if (typeof e.fastStart == "object") {
    if (e.video) {
      if (e.fastStart.expectedVideoChunks === void 0)
        throw new TypeError("'fastStart' is an object but is missing property 'expectedVideoChunks'.");
      if (!Number.isInteger(e.fastStart.expectedVideoChunks) || e.fastStart.expectedVideoChunks < 0)
        throw new TypeError("'expectedVideoChunks' must be a non-negative integer.");
    }
    if (e.audio) {
      if (e.fastStart.expectedAudioChunks === void 0)
        throw new TypeError("'fastStart' is an object but is missing property 'expectedAudioChunks'.");
      if (!Number.isInteger(e.fastStart.expectedAudioChunks) || e.fastStart.expectedAudioChunks < 0)
        throw new TypeError("'expectedAudioChunks' must be a non-negative integer.");
    }
  } else if (![!1, "in-memory", "fragmented"].includes(e.fastStart))
    throw new TypeError("'fastStart' option must be false, 'in-memory', 'fragmented' or an object.");
  if (e.minFragmentDuration !== void 0 && (!Number.isFinite(e.minFragmentDuration) || e.minFragmentDuration < 0))
    throw new TypeError("'minFragmentDuration' must be a non-negative number.");
};
Me = /* @__PURE__ */ new WeakSet();
nt = function() {
  var e;
  if (s(this, u).writeBox(vt({
    holdsAvc: ((e = s(this, d).video) == null ? void 0 : e.codec) === "avc",
    fragmented: s(this, d).fastStart === "fragmented"
  })), S(this, ge, s(this, u).pos), s(this, d).fastStart === "in-memory")
    S(this, z, be(!1));
  else if (s(this, d).fastStart !== "fragmented") {
    if (typeof s(this, d).fastStart == "object") {
      let t = m(this, Re, ot).call(this);
      s(this, u).seek(s(this, u).pos + t);
    }
    S(this, z, be(!0)), s(this, u).writeBox(s(this, z));
  }
  m(this, Z, ne).call(this);
};
Re = /* @__PURE__ */ new WeakSet();
ot = function() {
  if (typeof s(this, d).fastStart != "object")
    return;
  let e = 0, t = [
    s(this, d).fastStart.expectedVideoChunks,
    s(this, d).fastStart.expectedAudioChunks
  ];
  for (let i of t)
    i && (e += 8 * Math.ceil(2 / 3 * i), e += 4 * i, e += 12 * Math.ceil(2 / 3 * i), e += 4 * i, e += 8 * i);
  return e += 4096, e;
};
Pe = /* @__PURE__ */ new WeakSet();
ht = function() {
  if (s(this, d).video && S(this, b, {
    id: 1,
    info: {
      type: "video",
      codec: s(this, d).video.codec,
      width: s(this, d).video.width,
      height: s(this, d).video.height,
      rotation: s(this, d).video.rotation ?? 0,
      decoderConfig: null
    },
    // The fallback contains many common frame rates as factors
    timescale: s(this, d).video.frameRate ?? 57600,
    samples: [],
    finalizedChunks: [],
    currentChunk: null,
    firstDecodeTimestamp: void 0,
    lastDecodeTimestamp: -1,
    timeToSampleTable: [],
    compositionTimeOffsetTable: [],
    lastTimescaleUnits: null,
    lastSample: null,
    compactlyCodedChunkTable: []
  }), s(this, d).audio && (S(this, T, {
    id: s(this, d).video ? 2 : 1,
    info: {
      type: "audio",
      codec: s(this, d).audio.codec,
      numberOfChannels: s(this, d).audio.numberOfChannels,
      sampleRate: s(this, d).audio.sampleRate,
      decoderConfig: null
    },
    timescale: s(this, d).audio.sampleRate,
    samples: [],
    finalizedChunks: [],
    currentChunk: null,
    firstDecodeTimestamp: void 0,
    lastDecodeTimestamp: -1,
    timeToSampleTable: [],
    compositionTimeOffsetTable: [],
    lastTimescaleUnits: null,
    lastSample: null,
    compactlyCodedChunkTable: []
  }), s(this, d).audio.codec === "aac")) {
    let e = m(this, Ve, lt).call(
      this,
      2,
      // Object type for AAC-LC, since it's the most common
      s(this, d).audio.sampleRate,
      s(this, d).audio.numberOfChannels
    );
    s(this, T).info.decoderConfig = {
      codec: s(this, d).audio.codec,
      description: e,
      numberOfChannels: s(this, d).audio.numberOfChannels,
      sampleRate: s(this, d).audio.sampleRate
    };
  }
};
Ve = /* @__PURE__ */ new WeakSet();
lt = function(e, t, i) {
  let a = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350].indexOf(t), n = i, o = "";
  o += e.toString(2).padStart(5, "0"), o += a.toString(2).padStart(4, "0"), a === 15 && (o += t.toString(2).padStart(24, "0")), o += n.toString(2).padStart(4, "0");
  let l = Math.ceil(o.length / 8) * 8;
  o = o.padEnd(l, "0");
  let p = new Uint8Array(o.length / 8);
  for (let y = 0; y < o.length; y += 8)
    p[y / 8] = parseInt(o.slice(y, y + 8), 2);
  return p;
};
ue = /* @__PURE__ */ new WeakSet();
De = function(e, t, i, r, a, n, o) {
  let l = r / 1e6, p = (r - (o ?? 0)) / 1e6, y = a / 1e6, _ = m(this, Le, dt).call(this, l, p, e);
  return l = _.presentationTimestamp, p = _.decodeTimestamp, n != null && n.decoderConfig && (e.info.decoderConfig === null ? e.info.decoderConfig = n.decoderConfig : Object.assign(e.info.decoderConfig, n.decoderConfig)), {
    presentationTimestamp: l,
    decodeTimestamp: p,
    duration: y,
    data: t,
    size: t.byteLength,
    type: i,
    // Will be refined once the next sample comes in
    timescaleUnitsToNextSample: x(y, e.timescale)
  };
};
D = /* @__PURE__ */ new WeakSet();
F = function(e, t) {
  s(this, d).fastStart !== "fragmented" && e.samples.push(t);
  const i = x(t.presentationTimestamp - t.decodeTimestamp, e.timescale);
  if (e.lastTimescaleUnits !== null) {
    let a = x(t.decodeTimestamp, e.timescale, !1), n = Math.round(a - e.lastTimescaleUnits);
    if (e.lastTimescaleUnits += n, e.lastSample.timescaleUnitsToNextSample = n, s(this, d).fastStart !== "fragmented") {
      let o = me(e.timeToSampleTable);
      o.sampleCount === 1 ? (o.sampleDelta = n, o.sampleCount++) : o.sampleDelta === n ? o.sampleCount++ : (o.sampleCount--, e.timeToSampleTable.push({
        sampleCount: 2,
        sampleDelta: n
      }));
      const l = me(e.compositionTimeOffsetTable);
      l.sampleCompositionTimeOffset === i ? l.sampleCount++ : e.compositionTimeOffsetTable.push({
        sampleCount: 1,
        sampleCompositionTimeOffset: i
      });
    }
  } else
    e.lastTimescaleUnits = 0, s(this, d).fastStart !== "fragmented" && (e.timeToSampleTable.push({
      sampleCount: 1,
      sampleDelta: x(t.duration, e.timescale)
    }), e.compositionTimeOffsetTable.push({
      sampleCount: 1,
      sampleCompositionTimeOffset: i
    }));
  e.lastSample = t;
  let r = !1;
  if (!e.currentChunk)
    r = !0;
  else {
    let a = t.presentationTimestamp - e.currentChunk.startTimestamp;
    if (s(this, d).fastStart === "fragmented") {
      let n = s(this, b) ?? s(this, T);
      const o = s(this, d).minFragmentDuration ?? 1;
      e === n && t.type === "key" && a >= o && (r = !0, m(this, ye, $e).call(this));
    } else
      r = a >= 0.5;
  }
  r && (e.currentChunk && m(this, re, we).call(this, e), e.currentChunk = {
    startTimestamp: t.presentationTimestamp,
    samples: []
  }), e.currentChunk.samples.push(t);
};
Le = /* @__PURE__ */ new WeakSet();
dt = function(e, t, i) {
  var o, l;
  const r = s(this, d).firstTimestampBehavior === "strict", a = i.lastDecodeTimestamp === -1;
  if (r && a && t !== 0)
    throw new Error(
      `The first chunk for your media track must have a timestamp of 0 (received DTS=${t}).Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of thedocument, which is probably what you want.

If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
`
    );
  if (s(this, d).firstTimestampBehavior === "offset" || s(this, d).firstTimestampBehavior === "cross-track-offset") {
    i.firstDecodeTimestamp === void 0 && (i.firstDecodeTimestamp = t);
    let p;
    s(this, d).firstTimestampBehavior === "offset" ? p = i.firstDecodeTimestamp : p = Math.min(
      ((o = s(this, b)) == null ? void 0 : o.firstDecodeTimestamp) ?? 1 / 0,
      ((l = s(this, T)) == null ? void 0 : l.firstDecodeTimestamp) ?? 1 / 0
    ), t -= p, e -= p;
  }
  if (t < i.lastDecodeTimestamp)
    throw new Error(
      `Timestamps must be monotonically increasing (DTS went from ${i.lastDecodeTimestamp * 1e6} to ${t * 1e6}).`
    );
  return i.lastDecodeTimestamp = t, { presentationTimestamp: e, decodeTimestamp: t };
};
re = /* @__PURE__ */ new WeakSet();
we = function(e) {
  if (s(this, d).fastStart === "fragmented")
    throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");
  if (e.currentChunk) {
    if (e.finalizedChunks.push(e.currentChunk), s(this, G).push(e.currentChunk), (e.compactlyCodedChunkTable.length === 0 || me(e.compactlyCodedChunkTable).samplesPerChunk !== e.currentChunk.samples.length) && e.compactlyCodedChunkTable.push({
      firstChunk: e.finalizedChunks.length,
      // 1-indexed
      samplesPerChunk: e.currentChunk.samples.length
    }), s(this, d).fastStart === "in-memory") {
      e.currentChunk.offset = 0;
      return;
    }
    e.currentChunk.offset = s(this, u).pos;
    for (let t of e.currentChunk.samples)
      s(this, u).write(t.data), t.data = null;
    m(this, Z, ne).call(this);
  }
};
ye = /* @__PURE__ */ new WeakSet();
$e = function(e = !0) {
  if (s(this, d).fastStart !== "fragmented")
    throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");
  let t = [s(this, b), s(this, T)].filter((l) => l && l.currentChunk);
  if (t.length === 0)
    return;
  let i = gt(this, Ne)._++;
  if (i === 1) {
    let l = he(t, s(this, H), !0);
    s(this, u).writeBox(l);
  }
  let r = s(this, u).pos, a = qe(i, t);
  s(this, u).writeBox(a);
  {
    let l = be(!1), p = 0;
    for (let _ of t)
      for (let W of _.currentChunk.samples)
        p += W.size;
    let y = s(this, u).measureBox(l) + p;
    y >= 2 ** 32 && (l.largeSize = !0, y = s(this, u).measureBox(l) + p), l.size = y, s(this, u).writeBox(l);
  }
  for (let l of t) {
    l.currentChunk.offset = s(this, u).pos, l.currentChunk.moofOffset = r;
    for (let p of l.currentChunk.samples)
      s(this, u).write(p.data), p.data = null;
  }
  let n = s(this, u).pos;
  s(this, u).seek(s(this, u).offsets.get(a));
  let o = qe(i, t);
  s(this, u).writeBox(o), s(this, u).seek(n);
  for (let l of t)
    l.finalizedChunks.push(l.currentChunk), s(this, G).push(l.currentChunk), l.currentChunk = null;
  e && m(this, Z, ne).call(this);
};
Z = /* @__PURE__ */ new WeakSet();
ne = function() {
  s(this, u) instanceof We && s(this, u).flush();
};
fe = /* @__PURE__ */ new WeakSet();
Ie = function() {
  if (s(this, se))
    throw new Error("Cannot add new video or audio chunks after the file has been finalized.");
};
const E = 30;
class ki {
  constructor(t) {
    this.audioContext = null, this.sourceNode = null, this.isPlaying = !1, this.startTime = 0, this.pauseTime = 0, this.duration = t.duration, this.audioConfig = t.audioConfig, this.encodedChunks = [], this.audioSegments = /* @__PURE__ */ new Map(), this.scheduledNodes = /* @__PURE__ */ new Map(), this.preloadThreshold = 5, this.isPreloading = !1, this.worker = t.worker, this.file = t.file, this.init();
  }
  init() {
    this.audioContext = new AudioContext(), this.seek(0);
  }
  /**
   * Mux EncodedAudioChunks to an ArrayBuffer for Web Audio API decoding
   * @param chunks - Array of EncodedAudioChunks from a segment
   */
  async muxEncodedChunksToBuffer(t, i) {
    const r = new Si({
      target: new et(),
      fastStart: "in-memory",
      firstTimestampBehavior: "offset",
      audio: {
        codec: "aac",
        sampleRate: i.sampleRate,
        numberOfChannels: i.numberOfChannels
      }
    });
    for (const a of t)
      r.addAudioChunk(a);
    return await r.finalize(), r.target.buffer;
  }
  /**
   * Fetch EncodedAudioChunks for a specific time segment from the file worker
   * @param time - Time in seconds
   * @returns Array of EncodedAudioChunks
   */
  async getEncodedChunksForTime(t) {
    const i = Math.floor(t / E), r = await this.worker.sendMessage("get-audio-segment", {
      start: i * E,
      end: i * E + E,
      file: this.file
    });
    return this.encodedChunks = r, r;
  }
  /**
   * Load and decode an audio segment
   * @param time - Time in seconds
   * @returns Decoded AudioBuffer for the segment
   */
  async loadSegment(t) {
    const i = Math.floor(t / E);
    if (this.audioSegments.has(i))
      return this.audioSegments.get(i);
    const r = await this.getEncodedChunksForTime(i * E);
    if (r.length === 0) return null;
    try {
      const a = performance.now(), n = await this.muxEncodedChunksToBuffer(r, this.audioConfig), o = performance.now(), l = await this.audioContext.decodeAudioData(n), p = performance.now();
      return console.log(`Segment ${i}: Muxing took ${o - a}ms, Decoding took ${p - o}ms`), this.audioSegments.set(i, l), l;
    } catch (a) {
      return console.error("Error loading audio segment:", a), null;
    }
  }
  async startPlayback(t = this.pauseTime) {
    this.clearScheduledNodes();
    const i = await this.loadSegment(t);
    if (!i) return;
    const r = t % E, a = E - r;
    this.scheduleSegment(i, t, r), this.preloadNextSegment(t + a);
  }
  clearScheduledNodes() {
    for (const t of this.scheduledNodes.values())
      t.stop(), t.disconnect();
    this.scheduledNodes.clear();
  }
  getCurrentSegmentIndex() {
    return Math.floor(this.getCurrentTime() / E);
  }
  async preloadNextSegment(t) {
    if (this.isPreloading || t >= this.duration) return;
    const i = Math.floor(t / E);
    if (this.audioSegments.has(i)) {
      this.scheduleSegment(this.audioSegments.get(i), t, 0);
      return;
    }
    this.isPreloading = !0;
    try {
      const r = await this.loadSegment(t);
      if (!r || !this.isPlaying) return;
      this.scheduleSegment(r, t, 0);
    } finally {
      this.isPreloading = !1;
    }
  }
  scheduleSegment(t, i, r) {
    const a = this.audioContext.createBufferSource();
    a.buffer = t, a.connect(this.audioContext.destination);
    const n = this.startTime + (i - this.pauseTime);
    a.start(n, r), this.scheduledNodes.set(i, a), a.onended = () => {
      a.disconnect(), this.scheduledNodes.delete(i);
    };
  }
  async play() {
    this.startTime = this.audioContext.currentTime, await this.startPlayback(), this.isPlaying = !0;
  }
  async pause() {
    this.clearScheduledNodes(), this.pauseTime = this.getCurrentTime(), this.isPlaying = !1;
  }
  async seek(t) {
    const i = this.isPlaying;
    i && (this.clearScheduledNodes(), this.isPlaying = !1), this.pauseTime = t, i && (this.startTime = this.audioContext.currentTime, this.isPlaying = !0, await this.startPlayback(t));
  }
  checkForPreLoad() {
    if (!this.isPlaying) return;
    const t = this.getCurrentTime(), i = this.getCurrentSegmentIndex();
    t % E >= E - this.preloadThreshold && !this.isPreloading && !this.audioSegments.has(i + 1) && this.preloadNextSegment((i + 1) * E);
  }
  getCurrentTime() {
    return this.isPlaying ? this.pauseTime + (this.audioContext.currentTime - this.startTime) : this.pauseTime;
  }
}
class ut {
  constructor() {
    this.listeners = {};
  }
  /**
   * Add an event listener and return its unique ID
   */
  on(t, i) {
    this.listeners[t] || (this.listeners[t] = {});
    const r = Xe();
    return this.listeners[t][r] = i, r;
  }
  /**
   * Remove a specific listener by its ID
   */
  off(t, i) {
    this.listeners[t] && delete this.listeners[t][i];
  }
  /**
   * Emit an event to all registered listeners
   */
  emit(t, i) {
    this.listeners[t] && Object.values(this.listeners[t]).forEach((r) => {
      r(i);
    });
  }
  /**
   * Remove all listeners for a specific event
   */
  removeAllListeners(t) {
    this.listeners[t] && (this.listeners[t] = {});
  }
}
const bi = "/assets/video.worker-DrxbiAg9.js";
class He extends ut {
  constructor(t) {
    super(), this.offscreenCanvas = null, this.duration = 0, this.canvas = t.canvas, this.fileWorkerPort = t.fileWorkerPort, this.worker = new Se(bi);
  }
  /**
   * Send a message to the worker and wait for a response
   */
  /**
   * Initialize the video player
   */
  async initialize() {
    this.offscreenCanvas = this.canvas.transferControlToOffscreen();
    const t = await this.worker.sendMessage("init", {
      canvas: this.offscreenCanvas,
      fileWorkerPort: this.fileWorkerPort
    }, [this.offscreenCanvas, this.fileWorkerPort]);
    this.emit("initialized", t);
  }
  /**
   * Seek to a specific time
   */
  async seek(t) {
    await this.worker.sendMessage("seek", { time: t });
  }
  /**
   * Get debug information from the video worker
   */
  async getDebugInfo() {
    return await this.worker.sendMessage("get-debug-info", {});
  }
  async setTrackData(t, i) {
    await this.worker.sendMessage("set-track-data", {
      videoMetadata: t,
      duration: i
    });
  }
  /**
   * Clean up resources
   */
  terminate() {
    this.worker.sendMessage("terminate").catch(console.error), this.worker.terminate(), this.offscreenCanvas = null, this.emit("terminated");
  }
  /**
  
    /**
     * Update the current frame (animation loop)
     */
  render(t) {
    this.worker.sendMessage("render", { time: t });
  }
}
class _i extends ut {
  /**
   * Create a new Clock
   * @param audioPlayer - Audio player with Web Audio timeline
   * @param videoWorker - Video worker for passive rendering
   * @param duration - Total video duration in seconds
   */
  constructor(t, i, r) {
    super(), this.isPlaying = !1, this.animationFrame = null, this.TARGET_FPS = 30, this.lastFrameTime = 0, this.audioPlayer = t, this.videoWorker = i, this.duration = r, this.FRAME_INTERVAL = 1e3 / this.TARGET_FPS;
  }
  /**
   * Start playback
   *
   * Starts the audio player and begins the tick loop.
   * The tick loop queries the audio timeline and drives video rendering.
   */
  async play() {
    this.isPlaying || (this.isPlaying = !0, await this.audioPlayer.play(), this.lastFrameTime = performance.now(), this.tick(), this.emit("play"));
  }
  /**
   * Pause playback
   *
   * Pauses audio and stops the tick loop.
   */
  pause() {
    this.isPlaying && (this.isPlaying = !1, this.audioPlayer.pause(), this.animationFrame && (cancelAnimationFrame(this.animationFrame), this.animationFrame = null), this.emit("pause"));
  }
  /**
   * Seek to a specific time
   *
   * @param time - Time in seconds
   */
  async seek(t) {
    const i = Math.max(0, Math.min(t, this.duration));
    this.videoWorker.seek(i), await this.audioPlayer.seek(i), this.emit("seek", i);
  }
  /**
   * Get the current playback time
   *
   * Queries the audio player's timeline, which is the source of truth.
   *
   * @returns Current time in seconds
   */
  getCurrentTime() {
    return this.audioPlayer.getCurrentTime();
  }
  /**
   * Check if currently playing
   */
  playing() {
    return this.isPlaying;
  }
  /**
   * Main tick loop
   *
   * This runs at TARGET_FPS and:
   * 1. Queries the current time from audio timeline
   * 2. Emits tick event for UI updates
   * 3. Tells video worker to render at this time
   * 4. Checks for end of video
   *
   * The video worker is passive - it just renders whatever time we tell it.
   * The audio timeline is the source of truth for the current time.
   */
  tick() {
    if (!this.isPlaying) return;
    const t = performance.now();
    if (t - this.lastFrameTime < this.FRAME_INTERVAL) {
      this.animationFrame = requestAnimationFrame(() => this.tick());
      return;
    }
    this.lastFrameTime = t;
    const r = this.audioPlayer.getCurrentTime();
    if (r >= this.duration - 0.1) {
      this.pause(), this.emit("ended");
      return;
    }
    this.emit("tick", r), this.videoWorker.render(r), this.audioPlayer.checkForPreLoad(), this.animationFrame = requestAnimationFrame(() => this.tick());
  }
  /**
   * Update duration (if needed after initialization)
   */
  setDuration(t) {
    this.duration = t;
  }
  /**
   * Clean up resources
   */
  destroy() {
    this.animationFrame && (cancelAnimationFrame(this.animationFrame), this.animationFrame = null), this.isPlaying = !1;
  }
}
const Ge = "/assets/file-DCgsDVsh.js";
class Ei {
  constructor(t) {
    this.canvas = null, this.duration = 0, this.renderer = null, this.audioPlayer = null, this.worker = null, this.clock = null, this.trackData = null, this.params = t, this.worker = new Se(Ge), this.file = t.src, this.canvas = t.canvas, this.duration = 0;
  }
  async play() {
    if (!this.clock)
      throw new Error("Player not initialized. Call initialize() first.");
    await this.clock.play();
  }
  async pause() {
    if (!this.clock)
      throw new Error("Player not initialized. Call initialize() first.");
    this.clock.pause();
  }
  async seek(t) {
    if (!this.clock)
      throw new Error("Player not initialized. Call initialize() first.");
    await this.clock.seek(t);
  }
  getCurrentTime() {
    var t;
    return ((t = this.clock) == null ? void 0 : t.getCurrentTime()) || 0;
  }
  async getDebugInfo() {
    var i, r, a, n, o, l, p, y, _, W, K, Q, P;
    const t = this.renderer ? await this.renderer.getDebugInfo() : null;
    return {
      trackData: {
        duration: this.duration,
        audio: this.audioPlayer ? {
          codec: (i = this.audioPlayer.audioConfig) == null ? void 0 : i.codec,
          sampleRate: (r = this.audioPlayer.audioConfig) == null ? void 0 : r.sampleRate,
          numberOfChannels: (a = this.audioPlayer.audioConfig) == null ? void 0 : a.numberOfChannels,
          startTime: this.audioPlayer.startTime,
          pauseTime: this.audioPlayer.pauseTime,
          isPlaying: this.audioPlayer.isPlaying,
          loadedSegments: this.audioPlayer.audioSegments.size,
          scheduledNodeCount: this.audioPlayer.scheduledNodes.size
        } : null,
        video: t ? {
          duration: (n = this.renderer) == null ? void 0 : n.duration,
          codec: (l = (o = this.trackData) == null ? void 0 : o.video) == null ? void 0 : l.codec,
          width: (y = (p = this.trackData) == null ? void 0 : p.video) == null ? void 0 : y.codedWidth,
          height: (W = (_ = this.trackData) == null ? void 0 : _.video) == null ? void 0 : W.codedHeight,
          frameRate: (Q = (K = this.trackData) == null ? void 0 : K.video) == null ? void 0 : Q.frameRate,
          ...t
        } : null
      },
      clock: {
        isPlaying: (P = this.clock) == null ? void 0 : P.playing(),
        currentTime: this.getCurrentTime()
      }
    };
  }
  terminate() {
    this.clock && (this.clock.destroy(), this.clock = null), this.audioPlayer && this.audioPlayer.pause(), this.renderer && (this.renderer instanceof He && this.renderer.terminate(), this.renderer = null);
  }
  async initialize() {
    console.log("Initializing"), this.worker = new Se(Ge);
    const t = new MessageChannel();
    await this.worker.sendMessage("init", {
      file: this.file,
      videoPort: t.port1
    }, [t.port1]);
    const i = await this.worker.sendMessage("get-tracks", {});
    console.log("Track data", i), this.trackData = i, this.duration = i.duration, this.renderer = new He({
      src: this.file,
      canvas: this.canvas,
      fileWorkerPort: t.port2
    }), await this.renderer.initialize(), await this.renderer.setTrackData(i.video, i.duration), this.audioPlayer = new ki({
      worker: this.worker,
      audioConfig: i.audio,
      duration: i.duration,
      file: this.file
    }), this.clock = new _i(this.audioPlayer, this.renderer, this.duration);
  }
  on(t, i) {
    this.clock.on(t, i);
  }
  // Add more methods as needed
}
export {
  Ei as WebCodecsPlayer
};
//# sourceMappingURL=index.js.map
