@blockcast/mmt-container 2.2.0-main.c3a95413582c → 2.2.0-main.cb533d6dfc95

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/browser-runtime.js +1354 -183
  2. package/dist/browser-runtime.js.map +3 -3
  3. package/dist/cmaf-block-assembler.js +92 -1
  4. package/dist/cmaf-block-assembler.js.map +2 -2
  5. package/dist/codec-utils.d.ts.map +1 -1
  6. package/dist/codec-utils.js +92 -1
  7. package/dist/codec-utils.js.map +2 -2
  8. package/dist/delivery-catalog.js +17 -12
  9. package/dist/delivery-catalog.js.map +2 -2
  10. package/dist/delta-fallback-config.js.map +1 -1
  11. package/dist/fec-manager.d.ts +83 -15
  12. package/dist/fec-manager.d.ts.map +1 -1
  13. package/dist/fec-manager.js +446 -61
  14. package/dist/fec-manager.js.map +2 -2
  15. package/dist/fec-worker-setup.js.map +1 -1
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js.map +2 -2
  19. package/dist/iso-block-locator.d.ts +48 -13
  20. package/dist/iso-block-locator.d.ts.map +1 -1
  21. package/dist/iso-block-locator.js +97 -25
  22. package/dist/iso-block-locator.js.map +2 -2
  23. package/dist/iso-bmff-timing.d.ts +10 -1
  24. package/dist/iso-bmff-timing.d.ts.map +1 -1
  25. package/dist/iso-bmff-timing.js +36 -2
  26. package/dist/iso-bmff-timing.js.map +2 -2
  27. package/dist/media-router.js.map +1 -1
  28. package/dist/mmtp-container-parser.d.ts +79 -10
  29. package/dist/mmtp-container-parser.d.ts.map +1 -1
  30. package/dist/mmtp-container-parser.js +299 -27
  31. package/dist/mmtp-container-parser.js.map +2 -2
  32. package/dist/mmtp-container-parser.no-modules.js +301 -30
  33. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  34. package/dist/mmtp-decode-pipeline.js +298 -27
  35. package/dist/mmtp-decode-pipeline.js.map +2 -2
  36. package/dist/mmtp-router.d.ts +34 -8
  37. package/dist/mmtp-router.d.ts.map +1 -1
  38. package/dist/mmtp-router.js +638 -76
  39. package/dist/mmtp-router.js.map +3 -3
  40. package/dist/multicast-manager.d.ts +26 -3
  41. package/dist/multicast-manager.d.ts.map +1 -1
  42. package/dist/multicast-manager.js +1174 -156
  43. package/dist/multicast-manager.js.map +3 -3
  44. package/dist/multicast-transport.js +19 -14
  45. package/dist/multicast-transport.js.map +2 -2
  46. package/dist/no-modules.js +298 -27
  47. package/dist/no-modules.js.map +3 -3
  48. package/dist/repair-fetch.d.ts +38 -8
  49. package/dist/repair-fetch.d.ts.map +1 -1
  50. package/dist/repair-fetch.js +286 -27
  51. package/dist/repair-fetch.js.map +3 -3
  52. package/dist/track-session.d.ts.map +1 -1
  53. package/dist/track-session.js +1 -0
  54. package/dist/track-session.js.map +2 -2
  55. package/dist/wasm-mmtp-container-parser.js +298 -27
  56. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  57. package/package.json +5 -5
  58. package/src/codec-utils.ts +121 -1
  59. package/src/fec-manager.ts +487 -35
  60. package/src/index.ts +3 -0
  61. package/src/iso-block-locator.ts +133 -31
  62. package/src/iso-bmff-timing.ts +40 -1
  63. package/src/mmtp-container-parser.ts +306 -29
  64. package/src/mmtp-router.ts +548 -38
  65. package/src/multicast-manager.ts +134 -16
  66. package/src/repair-fetch.ts +366 -50
  67. package/src/track-session.ts +3 -0
@@ -851,6 +851,17 @@ function readRepairFecPayloadIdFields(mmtpPacket, parsedHeader) {
851
851
  dataOffset: off + REPAIR_FEC_PID_SIZE
852
852
  };
853
853
  }
854
+ function extractRepairFecPayloadId(mmtpPacket) {
855
+ const fields = readRepairFecPayloadIdFields(mmtpPacket);
856
+ if (!fields)
857
+ return null;
858
+ return {
859
+ ssStart: fields.ssStart,
860
+ rsbLength: fields.rsbLength,
861
+ rsId: fields.rsId,
862
+ ssbLength: fields.ssbLength
863
+ };
864
+ }
854
865
  function parseMoqRepairFrame(frame) {
855
866
  return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame));
856
867
  }
@@ -6088,9 +6099,10 @@ function isH264IntraSlice(nal) {
6088
6099
  const sliceType = readH264SliceType(nal);
6089
6100
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
6090
6101
  }
6102
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
6091
6103
  function readH264SliceType(nal) {
6092
6104
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6093
- const rbsp = removeEmulationPrevention(nal.subarray(1));
6105
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
6094
6106
  const state = { bitOffset: 0 };
6095
6107
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6096
6108
  return readUnsignedExpGolomb(rbsp, state);
@@ -6459,6 +6471,96 @@ if (void 0) {
6459
6471
  ]))).toBe(false);
6460
6472
  });
6461
6473
  });
6474
+ describe("readH264SliceType", () => {
6475
+ const wholeNalSliceType = (nal) => {
6476
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6477
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
6478
+ const state = { bitOffset: 0 };
6479
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6480
+ return readUnsignedExpGolomb(rbsp, state);
6481
+ };
6482
+ const hex3 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
6483
+ const ue = (value) => {
6484
+ const code = (value + 1).toString(2);
6485
+ return "0".repeat(code.length - 1) + code;
6486
+ };
6487
+ const sliceNal = (bits) => {
6488
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
6489
+ const nal = [1];
6490
+ let zeros = 0;
6491
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
6492
+ if (zeros >= 2 && byte <= 3) {
6493
+ nal.push(3);
6494
+ zeros = 0;
6495
+ }
6496
+ nal.push(byte);
6497
+ zeros = byte === 0 ? zeros + 1 : 0;
6498
+ }
6499
+ return Uint8Array.from(nal);
6500
+ };
6501
+ const x264Slices = [
6502
+ ["64x48 P", hex3("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
6503
+ ["64x48 B", hex3("419e414212fffeeade283707cb70f7"), 6, false],
6504
+ ["64x48 non-IDR I", hex3(
6505
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
6506
+ ), 7, true],
6507
+ ["1280x720 B, escape at byte 10", hex3(
6508
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
6509
+ ), 6, false],
6510
+ ["1280x720 P, escape at byte 15", hex3(
6511
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
6512
+ ), 5, false],
6513
+ ["1280x720 B, escape at byte 22", hex3("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
6514
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex3(
6515
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
6516
+ ), null, true],
6517
+ ["7680x4320 P, first_mb_in_slice 32640", hex3(
6518
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
6519
+ ), 5, false],
6520
+ ["7680x4320 P, first_mb_in_slice 97440", hex3(
6521
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
6522
+ ), 5, false]
6523
+ ];
6524
+ const syntheticSlices = [
6525
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
6526
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
6527
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
6528
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
6529
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
6530
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
6531
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
6532
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
6533
+ ];
6534
+ test("reads the slice_type of real and synthetic slices", () => {
6535
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
6536
+ expect(readH264SliceType(nal), name).toBe(sliceType);
6537
+ }
6538
+ });
6539
+ test("matches the whole-NAL unescape at every truncation", () => {
6540
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
6541
+ for (let end = 0; end <= nal.length; end++) {
6542
+ const cut = nal.subarray(0, end);
6543
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
6544
+ }
6545
+ }
6546
+ });
6547
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
6548
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
6549
+ let seed = 1;
6550
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
6551
+ for (let i = 0; i < 5e3; i++) {
6552
+ const nal = new Uint8Array(2 + next() % 63);
6553
+ nal[0] = 65;
6554
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
6555
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
6556
+ }
6557
+ });
6558
+ test("classifies the x264 slices as keyframes or not", () => {
6559
+ for (const [name, nal, , keyframe] of x264Slices) {
6560
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
6561
+ }
6562
+ });
6563
+ });
6462
6564
  describe("avccToAnnexB", () => {
6463
6565
  test("converts with SPS/PPS on keyframe", () => {
6464
6566
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -8625,9 +8727,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
8625
8727
  } catch (error) {
8626
8728
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
8627
8729
  }
8628
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
8730
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
8629
8731
  await rx.close();
8630
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8732
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8631
8733
  }
8632
8734
  const events = new EventTarget();
8633
8735
  let state = "connected";
@@ -8746,6 +8848,7 @@ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
8746
8848
  });
8747
8849
 
8748
8850
  // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
8851
+ var MAX_PENDING_PACKETS = 256;
8749
8852
  var AMTGatewayManager = class {
8750
8853
  subscriptions = /* @__PURE__ */ new Map();
8751
8854
  messageHandler;
@@ -8754,7 +8857,6 @@ var AMTGatewayManager = class {
8754
8857
  constructor() {
8755
8858
  this.messageHandler = (event) => {
8756
8859
  const data = event.data;
8757
- console.log(`[AMT] SW message received:`, data.type);
8758
8860
  if (data.type === "UDP_PACKET") {
8759
8861
  this.handlePacket(data);
8760
8862
  } else if (data.type === "SOCKET_ERROR") {
@@ -8772,6 +8874,14 @@ var AMTGatewayManager = class {
8772
8874
  this.messageListenerRegistered = true;
8773
8875
  console.log("[AMT] Registered service worker message handler");
8774
8876
  }
8877
+ removeMessageListener() {
8878
+ if (!this.messageListenerRegistered)
8879
+ return;
8880
+ if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
8881
+ navigator.serviceWorker.removeEventListener("message", this.messageHandler);
8882
+ }
8883
+ this.messageListenerRegistered = false;
8884
+ }
8775
8885
  /**
8776
8886
  * Subscribe via AMT tunnel
8777
8887
  */
@@ -8816,6 +8926,8 @@ var AMTGatewayManager = class {
8816
8926
  this.subscriptions.delete(keyStr);
8817
8927
  this.pendingPackets.delete(subscription.subscriptionId);
8818
8928
  }
8929
+ if (this.subscriptions.size === 0)
8930
+ this.removeMessageListener();
8819
8931
  throw new Error(`Failed to subscribe via AMT: ${error instanceof Error ? error.message : String(error)}`);
8820
8932
  }
8821
8933
  }
@@ -8837,6 +8949,8 @@ var AMTGatewayManager = class {
8837
8949
  } finally {
8838
8950
  this.subscriptions.delete(handle);
8839
8951
  this.pendingPackets.delete(subscription.subscriptionId);
8952
+ if (this.subscriptions.size === 0)
8953
+ this.removeMessageListener();
8840
8954
  }
8841
8955
  }
8842
8956
  /**
@@ -8853,14 +8967,12 @@ var AMTGatewayManager = class {
8853
8967
  if (!subscriptionId)
8854
8968
  return;
8855
8969
  const subscription = this.subscriptions.get(subscriptionId);
8856
- if (!subscription) {
8857
- console.warn(`[AMT] Received packet for unknown subscription: ${subscriptionId}`);
8970
+ if (!subscription)
8858
8971
  return;
8859
- }
8860
8972
  if (!subscription.handshakeComplete) {
8861
8973
  const queue = this.pendingPackets.get(subscriptionId);
8862
8974
  const packetData2 = data;
8863
- if (queue) {
8975
+ if (queue && queue.length < MAX_PENDING_PACKETS) {
8864
8976
  queue.push({
8865
8977
  data: packetData2.data,
8866
8978
  remoteAddress: packetData2.remoteAddress,
@@ -8886,20 +8998,15 @@ var AMTGatewayManager = class {
8886
8998
  if (!subscriptionId)
8887
8999
  return;
8888
9000
  const subscription = this.subscriptions.get(subscriptionId);
8889
- if (!subscription) {
8890
- console.warn(`[AMT] Received error for unknown subscription: ${subscriptionId}`);
9001
+ if (!subscription)
8891
9002
  return;
8892
- }
8893
9003
  subscription.config.onError(new Error(error || "Unknown error"));
8894
9004
  }
8895
9005
  /**
8896
9006
  * Cleanup on destroy
8897
9007
  */
8898
9008
  destroy() {
8899
- if (this.messageListenerRegistered && this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
8900
- navigator.serviceWorker.removeEventListener("message", this.messageHandler);
8901
- this.messageListenerRegistered = false;
8902
- }
9009
+ this.removeMessageListener();
8903
9010
  const handles = Array.from(this.subscriptions.keys());
8904
9011
  for (const handle of handles) {
8905
9012
  this.unsubscribe(handle).catch((err) => {
@@ -12430,6 +12537,7 @@ var TrackSession = class {
12430
12537
  this.#state = "idle";
12431
12538
  this.#subscription = null;
12432
12539
  this.#disarmFec();
12540
+ this.#unsuppress();
12433
12541
  }
12434
12542
  // -----------------------------------------------------------------------
12435
12543
  // Internal
@@ -12923,6 +13031,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
12923
13031
  this.#heldEvicted = 0;
12924
13032
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
12925
13033
  this.#holes = [];
13034
+ /** Holes the horizon passed while pending: sources held until closed. */
13035
+ this.#expired = [];
13036
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
13037
+ this.#newlyExpired = [];
13038
+ /**
13039
+ * Spans closed from expired holes: behind the horizon, so kept only for
13040
+ * `locate` while their sources are fed, until the next retirement.
13041
+ */
13042
+ this.#closedBehind = [];
12926
13043
  /**
12927
13044
  * Keep a gap that is missing a source as a pending hole rather than a span,
12928
13045
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -12944,7 +13061,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
12944
13061
  #retentionBlocks;
12945
13062
  #heldEvicted;
12946
13063
  #newest;
13064
+ #newestSource;
12947
13065
  #holes;
13066
+ #expired;
13067
+ #newlyExpired;
13068
+ #closedBehind;
12948
13069
  static #checkedRetention(retentionBlocks) {
12949
13070
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
12950
13071
  throw new Error(
@@ -12981,6 +13102,21 @@ var IsoBlockLocator = class _IsoBlockLocator {
12981
13102
  observe(position) {
12982
13103
  if (this.#newest === void 0 || serial32Precedes(this.#newest, position)) this.#newest = position;
12983
13104
  }
13105
+ /**
13106
+ * The newest source SS_ID noted with `noteSource` (RFC 1982 order). Unlike
13107
+ * `newest`, a repair never moves it: a repair can run ahead of its sources,
13108
+ * a source cannot run ahead of the sources sent before it except by
13109
+ * reordering.
13110
+ */
13111
+ get newestSource() {
13112
+ return this.#newestSource;
13113
+ }
13114
+ /** Note a received source's SS_ID; true when it is the newest one yet. */
13115
+ noteSource(ssId) {
13116
+ if (this.#newestSource !== void 0 && !serial32Precedes(this.#newestSource, ssId)) return false;
13117
+ this.#newestSource = ssId;
13118
+ return true;
13119
+ }
12984
13120
  /** Held sources evicted by `heldCapacity` (never by the horizon itself). */
12985
13121
  get heldEvicted() {
12986
13122
  return this.#heldEvicted;
@@ -12999,17 +13135,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
12999
13135
  }
13000
13136
  /** The known block or span containing `ssId`, with its ESI. */
13001
13137
  locate(ssId) {
13002
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
13003
- const block = this.#blocks[i];
13004
- if (isoBlockContains(block.start, block.length, ssId)) {
13005
- return { block, esi: serial32Distance(block.start, ssId) };
13138
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
13139
+ for (let i = blocks.length - 1; i >= 0; i--) {
13140
+ const block = blocks[i];
13141
+ if (isoBlockContains(block.start, block.length, ssId)) {
13142
+ return { block, esi: serial32Distance(block.start, ssId) };
13143
+ }
13006
13144
  }
13007
13145
  }
13008
13146
  return null;
13009
13147
  }
13010
- /** Number of pending holes. */
13148
+ /** Number of holes not closed yet, pending or past the horizon. */
13011
13149
  get holeCount() {
13012
- return this.#holes.length;
13150
+ return this.#holes.length + this.#expired.length;
13151
+ }
13152
+ /**
13153
+ * The pending holes the horizon has passed since the last call, in the
13154
+ * order it passed them. Each is no longer pending: no repair states a block
13155
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
13156
+ * release gate does not wait for it. Its owner must close it
13157
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
13158
+ */
13159
+ takeExpiredHoles() {
13160
+ return this.#newlyExpired.splice(0);
13013
13161
  }
13014
13162
  /** The stated block (never a span) ending exactly at `end`. */
13015
13163
  blockEndingAt(end) {
@@ -13065,9 +13213,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
13065
13213
  /**
13066
13214
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
13067
13215
  * block states its range and places every held source in it; later repair
13068
- * symbols of the same block change nothing. A range that contradicts a
13069
- * known block (a different length, or an overlap with another block or a
13070
- * span) fails closed: the repair symbol is dropped and no block changes.
13216
+ * symbols of the same block change nothing. A repair whose range is exactly
13217
+ * a repair-less span states that span's one block. A range that contradicts
13218
+ * a known block (a different length, or an overlap with another block or
13219
+ * with part of a span) fails closed: the repair symbol is dropped and no
13220
+ * block changes.
13071
13221
  * A newly stated block retires behind its SS_Start (see the class note).
13072
13222
  * A block so far past `newest` that stating it would retire the position
13073
13223
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -13086,7 +13236,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
13086
13236
  const known = this.blockAt(start);
13087
13237
  if (known !== void 0) {
13088
13238
  if (known.span) {
13089
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
13239
+ if (known.length === length) {
13240
+ const block2 = { start, length, span: false };
13241
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
13242
+ return { status: "placed", block: block2, placed: [] };
13243
+ }
13244
+ return length < known.length ? {
13245
+ status: "overlap",
13246
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
13247
+ ofSpan: known
13248
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
13090
13249
  }
13091
13250
  if (known.length !== length) {
13092
13251
  return {
@@ -13154,18 +13313,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
13154
13313
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
13155
13314
  }
13156
13315
  /**
13157
- * Turn every pending hole inside `[start, start + length)` into a
13158
- * repair-less span, claiming its held sources: its range FETCH ended, so
13159
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
13316
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
13317
+ * claiming its held sources: its range FETCH ended, so nothing more will
13318
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
13319
+ * span that is not kept among the blocks, as the horizon would retire it at
13320
+ * once; only `locate` finds it, until the next retirement, so its sources
13321
+ * can be fed. Returns the spans, in SS_ID order.
13160
13322
  */
13161
13323
  closeHolesWithin(start, length) {
13162
13324
  const closed = [];
13163
- for (const hole of [...this.#holes]) {
13164
- if (!isoBlockContains(start, length, hole.start)) continue;
13165
- this.#holes.splice(this.#holes.indexOf(hole), 1);
13166
- const spanBlock = { start: hole.start, length: hole.length, span: true };
13167
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13168
- this.#blocks.push(spanBlock);
13325
+ for (const holes of [this.#holes, this.#expired]) {
13326
+ for (const hole of [...holes]) {
13327
+ if (!isoBlockContains(start, length, hole.start)) continue;
13328
+ holes.splice(holes.indexOf(hole), 1);
13329
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
13330
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13331
+ if (holes === this.#holes) {
13332
+ this.#blocks.push(spanBlock);
13333
+ } else {
13334
+ this.#closedBehind.push(spanBlock);
13335
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
13336
+ }
13337
+ }
13169
13338
  }
13170
13339
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
13171
13340
  }
@@ -13179,15 +13348,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
13179
13348
  return void 0;
13180
13349
  }
13181
13350
  /**
13182
- * Retire every block and span whose last SS_ID, and every held source,
13183
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
13184
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
13185
- * horizon uses. Returns the retired block starts.
13351
+ * Retire every block and span whose last SS_ID, and every held source
13352
+ * outside a hole, lies more than `retentionBlocks` blocks behind
13353
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
13354
+ * every ISO interleave horizon uses; a pending hole so far behind expires
13355
+ * (`takeExpiredHoles`). Returns the retired block starts.
13186
13356
  */
13187
13357
  retireBehind(position) {
13188
13358
  this.observe(position);
13189
13359
  const horizon = this.#retentionBlocks;
13190
13360
  const retired = [];
13361
+ this.#closedBehind.length = 0;
13191
13362
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
13192
13363
  const block = this.#blocks[i];
13193
13364
  const last = serial32Add(block.start, block.length - 1);
@@ -13199,10 +13370,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
13199
13370
  for (let i = this.#holes.length - 1; i >= 0; i--) {
13200
13371
  const hole = this.#holes[i];
13201
13372
  const last = serial32Add(hole.start, hole.length - 1);
13202
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
13373
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
13374
+ this.#holes.splice(i, 1);
13375
+ this.#expired.push(hole);
13376
+ this.#newlyExpired.push(hole);
13203
13377
  }
13204
13378
  for (const ssId of [...this.#held.keys()]) {
13205
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
13379
+ if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon && !this.#holes.some((hole) => isoBlockContains(hole.start, hole.length, ssId)) && !this.#expired.some((hole) => isoBlockContains(hole.start, hole.length, ssId))) {
13380
+ this.#held.delete(ssId);
13381
+ }
13206
13382
  }
13207
13383
  return retired;
13208
13384
  }
@@ -13210,9 +13386,13 @@ var IsoBlockLocator = class _IsoBlockLocator {
13210
13386
  reset() {
13211
13387
  this.#blocks.length = 0;
13212
13388
  this.#holes.length = 0;
13389
+ this.#expired.length = 0;
13390
+ this.#newlyExpired.length = 0;
13391
+ this.#closedBehind.length = 0;
13213
13392
  this.#held.clear();
13214
13393
  this.#coverageEnd = void 0;
13215
13394
  this.#newest = void 0;
13395
+ this.#newestSource = void 0;
13216
13396
  }
13217
13397
  #claim(block) {
13218
13398
  const placed = [];
@@ -13832,6 +14012,7 @@ var WORKER_ERROR_LOG_CAP = 5;
13832
14012
  var WORKER_ERROR_KIND_CAP = 32;
13833
14013
  var WORKER_ERROR_OVERFLOW_KIND = "other";
13834
14014
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
14015
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
13835
14016
  function isMulticastSymbolDelivery(value) {
13836
14017
  return value === "datagram" || value === "ordered-relay";
13837
14018
  }
@@ -13925,10 +14106,18 @@ var FECManager = class _FECManager {
13925
14106
  // 'pending' forever, which would park every later frame of its stream in
13926
14107
  // the in-order release gate. Each entry owns its handle; the callback
13927
14108
  // checks it still owns the key, so a settled or reset key is never touched.
14109
+ /**
14110
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
14111
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
14112
+ */
13928
14113
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
13929
14114
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
13930
14115
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
13931
14116
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
14117
+ // Source ESIs per block that another FEC instance rebuilt and fed in
14118
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
14119
+ // not network arrivals and never make a block clean.
14120
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
13932
14121
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
13933
14122
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
13934
14123
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -13937,10 +14126,14 @@ var FECManager = class _FECManager {
13937
14126
  // SSB_length source arrivals and recoverable from SSB_length received
13938
14127
  // symbols; waiting for K fails every one of them.
13939
14128
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
14129
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
14130
+ // a repair states the block there or the span resolves.
14131
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
13940
14132
  this.#ssbLengthConflictCount = 0;
13941
14133
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
13942
14134
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
13943
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
14135
+ // symbols its repair group carries; 0 for a repair-less span no repair can
14136
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
13944
14137
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
13945
14138
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
13946
14139
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -14057,6 +14250,10 @@ var FECManager = class _FECManager {
14057
14250
  // ── Keyframe-protected repair policy (block-policy.ts) ──
14058
14251
  // One classifier per physical stream, built from that stream's geometry.
14059
14252
  this.#classifiers = /* @__PURE__ */ new Map();
14253
+ // A stream without catalog timing has no classifier, so the last RAP it
14254
+ // released stands in for one: "an MPU boundary bounds its RAPs" holds until
14255
+ // a second RAP is released inside one MPU (BLO-52085).
14256
+ this.#noSpanRaps = /* @__PURE__ */ new Map();
14060
14257
  // Geometry a stream-scoped configuration gave one stream (streamKey). ABR
14061
14258
  // rungs can share a packetId with a different framerate or GOP, so the
14062
14259
  // packet-level geometry is only the geometry of a packet whose streams
@@ -14130,7 +14327,10 @@ var FECManager = class _FECManager {
14130
14327
  // arrives via onBlockRecovered callback.
14131
14328
  this.onBlockStarted = null;
14132
14329
  this.onBlockComplete = null;
14133
- /** A block reached its fail bound. `blockClass` is its class at failure. */
14330
+ /**
14331
+ * A block reached its fail bound. `blockClass` is its class at failure.
14332
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
14333
+ */
14134
14334
  this.onBlockFailed = null;
14135
14335
  /**
14136
14336
  * Fired once per stream when its Worker decoder stops being routable.
@@ -14172,12 +14372,22 @@ var FECManager = class _FECManager {
14172
14372
  * for it, which it must be.
14173
14373
  */
14174
14374
  this.#onUndelimitedLoss = null;
14375
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
14376
+ this.#onIsoHoleExpired = null;
14175
14377
  /** A block every symbol of which vanished was created by SBN evidence. */
14176
14378
  this.onBlockVanished = null;
14177
14379
  /** A block reached a terminal state (completed, recovered, or failed). */
14178
14380
  this.onBlockResolved = null;
14179
14381
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
14180
14382
  this.onSourceDiscontinuity = null;
14383
+ /**
14384
+ * The span and tolerance the catalog states for a keyframe overlay
14385
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
14386
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
14387
+ * undefined while none is installed. A block only a late source can
14388
+ * complete also waits for that overlay's repair (#lateSourceWaitMs).
14389
+ */
14390
+ this.keyframeOverlayTiming = null;
14181
14391
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
14182
14392
  /**
14183
14393
  * A recovered source symbol. Return false when admission refused the
@@ -14214,7 +14424,9 @@ var FECManager = class _FECManager {
14214
14424
  #pendingWorkerCleanupBounds;
14215
14425
  #blockSourceCounts;
14216
14426
  #blockSourceEsis;
14427
+ #blockRebuiltEsis;
14217
14428
  #blockAuthoredLengths;
14429
+ #isoSpanKeys;
14218
14430
  #ssbLengthConflictCount;
14219
14431
  #blockRepairRsIds;
14220
14432
  #blockRsbLengths;
@@ -14256,6 +14468,7 @@ var FECManager = class _FECManager {
14256
14468
  #orderedFrontiers;
14257
14469
  #orderedPendingBlocks;
14258
14470
  #classifiers;
14471
+ #noSpanRaps;
14259
14472
  #streamGeometries;
14260
14473
  #failedBlocks;
14261
14474
  #resolvedBlockClasses;
@@ -14280,6 +14493,7 @@ var FECManager = class _FECManager {
14280
14493
  #decoderUnavailableEvents;
14281
14494
  #repairSymbolSizeMismatchCount;
14282
14495
  #onUndelimitedLoss;
14496
+ #onIsoHoleExpired;
14283
14497
  #encodeTrackName(catalogTrackName) {
14284
14498
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
14285
14499
  if (encoded === void 0) {
@@ -14751,7 +14965,10 @@ var FECManager = class _FECManager {
14751
14965
  timer.handle = null;
14752
14966
  this.#requestRepair(sbn, packetId, catalogTrackName);
14753
14967
  };
14754
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
14968
+ timer.handle = setTimeout(
14969
+ onFire,
14970
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
14971
+ );
14755
14972
  this.#repairDeadlines.set(key, timer);
14756
14973
  }
14757
14974
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -14895,8 +15112,14 @@ var FECManager = class _FECManager {
14895
15112
  * Vanished blocks are not enumerated here: their starts are unknown until a
14896
15113
  * repair states them. The SS_IDs between two stated blocks become one
14897
15114
  * repair-less span when the later block's repair arrives (placeIsoRepair).
15115
+ *
15116
+ * A `held` source arrived before its block was known and is fed only now
15117
+ * that a repair, a span or a closed hole placed it: how far its block start
15118
+ * then lies behind the frontier measures how long the receiver held it, not
15119
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
15120
+ * it (BLO-52085).
14898
15121
  */
14899
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
15122
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
14900
15123
  const streamKey = this.#streamKey(packetId, catalogTrackName);
14901
15124
  const now = performance.now();
14902
15125
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -14917,6 +15140,7 @@ var FECManager = class _FECManager {
14917
15140
  };
14918
15141
  const discontinuity = () => {
14919
15142
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
15143
+ this.#noSpanRaps.delete(streamKey);
14920
15144
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
14921
15145
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
14922
15146
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -14934,7 +15158,7 @@ var FECManager = class _FECManager {
14934
15158
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
14935
15159
  };
14936
15160
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
14937
- if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
15161
+ if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (!held && this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
14938
15162
  discontinuity();
14939
15163
  return;
14940
15164
  }
@@ -15196,17 +15420,21 @@ var FECManager = class _FECManager {
15196
15420
  this.#blockWaitDeadlinesMs.delete(key);
15197
15421
  this.#repairHoldUntilMs.delete(key);
15198
15422
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
15199
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
15423
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
15200
15424
  };
15201
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
15425
+ timer.handle = setTimeout(
15426
+ onFire,
15427
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
15428
+ );
15202
15429
  this.#activeBlocks.set(key, timer);
15203
15430
  this.#indexBlockKey(key, sbn, packetId);
15204
15431
  }
15205
15432
  /**
15206
15433
  * Hand a block whose delivery is over to its decoder for finalization: the
15207
- * datagram deadline fired, or the ordered relay moved past it.
15434
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
15435
+ * is when it was due: its deadline, or now.
15208
15436
  */
15209
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
15437
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
15210
15438
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
15211
15439
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
15212
15440
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -15222,7 +15450,7 @@ var FECManager = class _FECManager {
15222
15450
  if (workerClient) {
15223
15451
  this.#pendingWorkerCleanups.add(key);
15224
15452
  this.#pendingWorkerCleanupClients.set(key, workerClient);
15225
- this.#boundOwedCleanup(key, packetId, workerClient);
15453
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
15226
15454
  workerClient.cleanup(sbn);
15227
15455
  } else {
15228
15456
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -15329,6 +15557,9 @@ var FECManager = class _FECManager {
15329
15557
  }
15330
15558
  if (policyChanged) {
15331
15559
  this.#bumpEpoch(packetId);
15560
+ for (const key of [...this.#noSpanRaps.keys()]) {
15561
+ if (this.#belongsToPacket(key, packetId)) this.#noSpanRaps.delete(key);
15562
+ }
15332
15563
  for (const [key, classifier] of [...this.#classifiers]) {
15333
15564
  if (!this.#belongsToPacket(key, packetId)) continue;
15334
15565
  const stream = this.#parseStreamKey(key);
@@ -15531,7 +15762,9 @@ var FECManager = class _FECManager {
15531
15762
  }
15532
15763
  resetMap(this.#blockSourceCounts);
15533
15764
  resetMap(this.#blockSourceEsis);
15765
+ resetMap(this.#blockRebuiltEsis);
15534
15766
  resetMap(this.#blockAuthoredLengths);
15767
+ resetSet(this.#isoSpanKeys);
15535
15768
  resetMap(this.#blockRepairRsIds);
15536
15769
  resetMap(this.#blockRsbLengths);
15537
15770
  resetMap(this.#heldLayerStates);
@@ -15564,6 +15797,7 @@ var FECManager = class _FECManager {
15564
15797
  resetMap(this.#isoLocators);
15565
15798
  resetMap(this.#sourceAnchors);
15566
15799
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
15800
+ this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
15567
15801
  this.#bumpEpoch(packetId);
15568
15802
  for (const [sbn, keys] of this.#blockKeysBySbn) {
15569
15803
  for (const key of keys.keys()) {
@@ -15654,7 +15888,9 @@ var FECManager = class _FECManager {
15654
15888
  dropMap(this.#pendingWorkerCleanupClients);
15655
15889
  dropMap(this.#blockSourceCounts);
15656
15890
  dropMap(this.#blockSourceEsis);
15891
+ dropMap(this.#blockRebuiltEsis);
15657
15892
  dropMap(this.#blockAuthoredLengths);
15893
+ dropSet(this.#isoSpanKeys);
15658
15894
  dropMap(this.#blockRepairRsIds);
15659
15895
  dropMap(this.#blockRsbLengths);
15660
15896
  dropMap(this.#blockPathCounts);
@@ -15670,6 +15906,7 @@ var FECManager = class _FECManager {
15670
15906
  dropMap(this.#isoLocators);
15671
15907
  dropMap(this.#sourceAnchors);
15672
15908
  dropMap(this.#classifiers);
15909
+ dropMap(this.#noSpanRaps);
15673
15910
  dropMap(this.#streamGeometries);
15674
15911
  dropSet(this.#pendingWorkerCleanups);
15675
15912
  dropSet(this.#completedBlocks);
@@ -15815,6 +16052,9 @@ var FECManager = class _FECManager {
15815
16052
  this.#unindexBlockKey(key);
15816
16053
  }
15817
16054
  }
16055
+ if (isSourceSymbol && source === "multicast") {
16056
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
16057
+ }
15818
16058
  return true;
15819
16059
  }
15820
16060
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -15924,8 +16164,10 @@ var FECManager = class _FECManager {
15924
16164
  }
15925
16165
  /**
15926
16166
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
15927
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
15928
- * Undefined for a block that is not open.
16167
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
16168
+ * repair-less span states its length, and RSB_length 0 when it is longer
16169
+ * than K, since no repair can reach it). Undefined for a block that is not
16170
+ * open.
15929
16171
  */
15930
16172
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
15931
16173
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -15993,8 +16235,9 @@ var FECManager = class _FECManager {
15993
16235
  return true;
15994
16236
  }
15995
16237
  /**
15996
- * Drop a block's repair hold: its FETCH ended without delivering. The block
15997
- * falls back to its multicast wait, which may already have passed.
16238
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
16239
+ * back only a repair that cannot complete it. The block falls back to its
16240
+ * multicast wait, which may already have passed.
15998
16241
  */
15999
16242
  releaseRepairHold(sbn, packetId, catalogTrackName) {
16000
16243
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16132,6 +16375,8 @@ var FECManager = class _FECManager {
16132
16375
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16133
16376
  const evictedBefore = locator.heldEvicted;
16134
16377
  const held = locator.hold(ssId, source);
16378
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16379
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16135
16380
  const evicted = locator.heldEvicted - evictedBefore;
16136
16381
  if (evicted > 0) {
16137
16382
  const before = this.#isoHeldEvictedCount;
@@ -16152,17 +16397,20 @@ var FECManager = class _FECManager {
16152
16397
  * contradicts a known block is refused (counted) and must be dropped.
16153
16398
  */
16154
16399
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
16155
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
16400
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16401
+ const placement = locator.placeRepair(ssStart, ssbLength);
16402
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16156
16403
  if (placement.status !== "placed") {
16157
16404
  this.#isoRepairRefusedCount++;
16158
16405
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
16159
16406
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
16160
16407
  }
16408
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
16161
16409
  return placement;
16162
16410
  }
16411
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
16163
16412
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
16164
16413
  if (placement.hole !== void 0) {
16165
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
16166
16414
  const hole = placement.hole.block;
16167
16415
  const previous = locator.blockEndingAt(hole.start);
16168
16416
  const loss = {
@@ -16183,17 +16431,29 @@ var FECManager = class _FECManager {
16183
16431
  * `handler`, instead of a repair-less span; null restores spans. Set by the
16184
16432
  * range repair scheduler; applies to every stream from its next gap. The
16185
16433
  * handler and the deferral are one setting, so no hole is ever created with
16186
- * nobody to close it.
16434
+ * nobody to close it. `onExpired` is told of each pending hole the stream
16435
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
16436
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
16437
+ * reported; otherwise the hole is discarded with its sources.
16187
16438
  */
16188
- setUndelimitedLossHandler(handler) {
16439
+ setUndelimitedLossHandler(handler, onExpired = null) {
16189
16440
  this.#onUndelimitedLoss = handler;
16441
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
16190
16442
  this.#deferIsoGaps = handler !== null;
16191
16443
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
16192
16444
  }
16445
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
16446
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
16447
+ for (const hole of locator.takeExpiredHoles()) {
16448
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
16449
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
16450
+ }
16451
+ }
16193
16452
  /**
16194
- * The range repair for a hole ended: every hole still pending inside
16195
- * `[start, start + length)` becomes a repair-less span. Returns those spans
16196
- * with the held sources they placed, for the caller to feed (MmtpRouter).
16453
+ * The range repair for a hole ended: every hole inside `[start, start +
16454
+ * length)`, pending or expired, becomes a repair-less span. Returns those
16455
+ * spans with the held sources they placed, for the caller to feed
16456
+ * (MmtpRouter).
16197
16457
  */
16198
16458
  closeIsoHoles(packetId, catalogTrackName, start, length) {
16199
16459
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -16209,10 +16469,22 @@ var FECManager = class _FECManager {
16209
16469
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
16210
16470
  * SS_ID of which vanished resolves through its deadline like any vanished
16211
16471
  * block.
16472
+ *
16473
+ * A span longer than K holds more than one block (SSB_length <= K), and the
16474
+ * locator states no block inside a span, only one exactly its range
16475
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
16476
+ * reach it. Its repair group is empty, so only its own late sources can
16477
+ * complete it, and it waits as a stated block its group cannot complete
16478
+ * does (#lateSourceWaitMs; BLO-52085 D4). A span of K or less may be one
16479
+ * block whose repair is still to come, and keeps the whole wait.
16212
16480
  */
16213
16481
  #openIsoSpan(span, packetId, catalogTrackName) {
16214
16482
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
16215
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
16483
+ if (!this.#blockAuthoredLengths.has(key)) {
16484
+ this.#blockAuthoredLengths.set(key, span.block.length);
16485
+ this.#isoSpanKeys.add(key);
16486
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
16487
+ }
16216
16488
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
16217
16489
  }
16218
16490
  /**
@@ -16300,11 +16572,14 @@ var FECManager = class _FECManager {
16300
16572
  /**
16301
16573
  * Whether an MPU boundary still bounds this stream's RAPs (see
16302
16574
  * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
16303
- * it does not. A stream with no classifier yet has shown nothing against it.
16575
+ * it does not. A stream with no classifier yet has shown nothing against it,
16576
+ * and neither has a stream without catalog timing until it releases two
16577
+ * RAPs inside one MPU.
16304
16578
  */
16305
16579
  mpuBoundsRapsFor(packetId, catalogTrackName) {
16306
- if (!this.#hasCatalogTimingForPacket(packetId)) return false;
16307
- return this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.mpuBoundsRaps ?? true;
16580
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
16581
+ if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
16582
+ return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true;
16308
16583
  }
16309
16584
  /** A block's class now, or frozen at its resolution. */
16310
16585
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -16330,7 +16605,14 @@ var FECManager = class _FECManager {
16330
16605
  * invariant (consecutive MPUs exactly one keyframe interval apart).
16331
16606
  */
16332
16607
  noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
16333
- if (!this.#trackConfigs.has(packetId) || !this.#hasCatalogTimingForPacket(packetId)) return;
16608
+ if (!this.#trackConfigs.has(packetId)) return;
16609
+ if (!this.#hasCatalogTimingForPacket(packetId)) {
16610
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
16611
+ const last = this.#noSpanRaps.get(streamKey);
16612
+ const inside = last?.inside === true || last?.mpu === mpu && last.presentationTime !== presentationTime;
16613
+ this.#noSpanRaps.set(streamKey, { mpu, presentationTime, inside });
16614
+ return;
16615
+ }
16334
16616
  this.#applyClassifierChanges(
16335
16617
  packetId,
16336
16618
  catalogTrackName,
@@ -16543,11 +16825,14 @@ var FECManager = class _FECManager {
16543
16825
  });
16544
16826
  client.onCleanupComplete((sbn) => {
16545
16827
  if (this.#releasedWorkerClients.has(client)) return;
16546
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
16828
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
16829
+ const cleanupKeys = owed.filter((key) => {
16547
16830
  const block = this.#parseBlockKey(key);
16548
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
16831
+ return block.packetId === packetId && block.sbn === sbn;
16549
16832
  });
16550
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
16833
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
16834
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
16835
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
16551
16836
  });
16552
16837
  client.onError((msg, code) => {
16553
16838
  const requestedKind = code ?? msg;
@@ -16617,9 +16902,11 @@ var FECManager = class _FECManager {
16617
16902
  * fail deadline already passed, so failing it is the decision that deadline
16618
16903
  * made. A late ack then finds nothing owed and is a no-op.
16619
16904
  */
16620
- #boundOwedCleanup(key, packetId, client) {
16905
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
16621
16906
  this.#clearOwedCleanupBound(key);
16622
16907
  const bound = {
16908
+ dueAtMs,
16909
+ askedAtMs: performance.now(),
16623
16910
  handle: setTimeout(() => {
16624
16911
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
16625
16912
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -16717,7 +17004,15 @@ var FECManager = class _FECManager {
16717
17004
  this.#isoSourceOversizeCount++;
16718
17005
  return null;
16719
17006
  }
16720
- const sbn = located.block.start;
17007
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
17008
+ }
17009
+ /**
17010
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
17011
+ * answers through onFrame (null here), or its synchronous decoder, whose
17012
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
17013
+ * stated for `ssId`.
17014
+ */
17015
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
16721
17016
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
16722
17017
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
16723
17018
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -16746,6 +17041,74 @@ var FECManager = class _FECManager {
16746
17041
  }
16747
17042
  return recovered;
16748
17043
  }
17044
+ /**
17045
+ * Feed a source symbol of this stream that another FEC instance over the
17046
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
17047
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
17048
+ * BLO-52085). It joins its block's decoder as a received source would, so
17049
+ * it reduces the erasures the block still has to solve, but it is not a
17050
+ * network arrival: no transport accounting, no classification evidence,
17051
+ * no deadline refresh, and it never makes a block clean.
17052
+ *
17053
+ * Only a block a repair stated takes one (a repair-less span has no
17054
+ * decoder block). A block that is terminal, or already holds that source,
17055
+ * does not. The symbol is the exact protected packet, unpadded, as
17056
+ * feedSourceSymbol takes it.
17057
+ *
17058
+ * `recovered` is the block the synchronous decoder completed with it; the
17059
+ * caller routes it and completes the block, as for any recovery. When
17060
+ * every source of the block is then present, received or rebuilt, and no
17061
+ * decoder returned it (a Worker answers asynchronously, and reports such a
17062
+ * block as clean on its own side), the block is completed here as
17063
+ * recovered, with nothing left to route.
17064
+ */
17065
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
17066
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
17067
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
17068
+ if (located === null || located.block.span) return NOT_TAKEN;
17069
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
17070
+ const sbn = located.block.start;
17071
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
17072
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
17073
+ let rebuilt = this.#blockRebuiltEsis.get(key);
17074
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
17075
+ if (rebuilt === void 0) {
17076
+ rebuilt = /* @__PURE__ */ new Set();
17077
+ this.#blockRebuiltEsis.set(key, rebuilt);
17078
+ }
17079
+ const config = this.#trackConfigs.get(packetId);
17080
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
17081
+ rebuilt.add(located.esi);
17082
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
17083
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
17084
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
17085
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
17086
+ }
17087
+ }
17088
+ return { taken: true, recovered };
17089
+ }
17090
+ /**
17091
+ * A block that holds every one of its `length` sources, received or
17092
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
17093
+ * every packet of it was delivered, by its own arrival or by the instance
17094
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
17095
+ */
17096
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
17097
+ const rebuilt = this.#blockRebuiltEsis.get(key);
17098
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
17099
+ let present = rebuilt.size;
17100
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
17101
+ if (present < length) return false;
17102
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
17103
+ this.countRecovery(packetId, sbn, catalogTrackName);
17104
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17105
+ if (catalogTrackName === void 0) {
17106
+ this.onBlockComplete?.(sbn, packetId);
17107
+ } else {
17108
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
17109
+ }
17110
+ return true;
17111
+ }
16749
17112
  /**
16750
17113
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
16751
17114
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -16948,8 +17311,95 @@ var FECManager = class _FECManager {
16948
17311
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
16949
17312
  return null;
16950
17313
  }
17314
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
16951
17315
  return recovered;
16952
17316
  }
17317
+ /**
17318
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
17319
+ * its sources in send order, so one that moves the stream's newest source
17320
+ * position past a block leaves the sources that block still misses
17321
+ * reordered behind it at best: it shortens the wait of every block it
17322
+ * passed that only a late source can complete. MoQ is left out: its streams
17323
+ * can overtake one another, so a MoQ source shows nothing about the sources
17324
+ * sent before it.
17325
+ */
17326
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
17327
+ const previous = locator.newestSource;
17328
+ if (!locator.noteSource(ssId) || previous === void 0) return;
17329
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
17330
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17331
+ this.#shortenUnrecoverableWait(
17332
+ this.#blockKey(block.start, packetId, catalogTrackName),
17333
+ block.start,
17334
+ packetId,
17335
+ catalogTrackName
17336
+ );
17337
+ }
17338
+ }
17339
+ /**
17340
+ * The wait of a block that only a late source can complete (BLO-52085): a
17341
+ * repair stated it, or it is a repair-less span longer than K (whose group
17342
+ * is empty, #openIsoSpan), its received sources plus every symbol its
17343
+ * repair group carries (RSB_length) are short of K' (the repair scheduler's
17344
+ * group-cannot-complete), and a later source of the stream has arrived, so
17345
+ * a source it misses is lost or reordered behind that one. The span, which
17346
+ * covers repair symbols paced after its sources, buys it nothing: it waits
17347
+ * the late-symbol allowance alone, the multicast wait less the span (the
17348
+ * catalog tolerance or the measured delivery gap). Undefined for any other
17349
+ * block.
17350
+ *
17351
+ * An installed keyframe overlay (keyframeOverlayTiming) may still rebuild
17352
+ * a RAP packet the block lost: a second FEC instance over the same packets
17353
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
17354
+ * span, unrelated to the base's. That packet can complete a stated block
17355
+ * (feedRebuiltSourceSymbol), and failing the block first would let the
17356
+ * release gate pass the keyframe, whose rebuild then lands stale. The
17357
+ * overlay repair of a packet the block lost goes out within the overlay's
17358
+ * span of that packet (fec-core-00 9.3), and the later source was sent
17359
+ * after it, so the block waits that span plus the larger of the allowance
17360
+ * and the overlay's own tolerance. An overlay that states no span (its
17361
+ * block may then span keyframes), or one whose wait is not shorter than
17362
+ * the whole multicast wait, leaves the block its whole wait: undefined.
17363
+ */
17364
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
17365
+ const authoredLength = this.#blockAuthoredLengths.get(key);
17366
+ const rsbLength = this.#blockRsbLengths.get(key);
17367
+ if (authoredLength === void 0 || rsbLength === void 0) return void 0;
17368
+ let present = this.#blockSourceCounts.get(key) ?? 0;
17369
+ const received = this.#blockSourceEsis.get(key);
17370
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
17371
+ if (present + rsbLength >= authoredLength) return void 0;
17372
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
17373
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
17374
+ return void 0;
17375
+ }
17376
+ const waitMs = this.#multicastWaitMs(config);
17377
+ const allowanceMs = waitMs - config.interleaveDepthMs;
17378
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
17379
+ if (overlay === void 0) return allowanceMs;
17380
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
17381
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
17382
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
17383
+ }
17384
+ /**
17385
+ * Bring an open block's wait in to its late-source wait, when it has one.
17386
+ * Never later than it is armed: only a source can complete such a block,
17387
+ * so a repair of its group (paced across the span) must not keep it open.
17388
+ */
17389
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
17390
+ if (!this.#activeBlocks.has(key)) return;
17391
+ const config = this.#trackConfigs.get(packetId);
17392
+ if (config === void 0) return;
17393
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
17394
+ if (waitMs === void 0) return;
17395
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
17396
+ this.#armBlockTimeout(
17397
+ sbn,
17398
+ packetId,
17399
+ catalogTrackName,
17400
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
17401
+ );
17402
+ }
16953
17403
  /**
16954
17404
  * Record a block's authored SSB_length from a repair symbol. Returns false,
16955
17405
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -17047,12 +17497,13 @@ var FECManager = class _FECManager {
17047
17497
  * the inactivity deadline on each symbol, records the symbol's in-band
17048
17498
  * classification evidence, and marks the block clean when all of its
17049
17499
  * authored source symbols arrived: the SSB_length a repair symbol declared,
17050
- * otherwise K.
17500
+ * otherwise K. `held` marks a source held unplaced since it arrived and
17501
+ * placed only now (see #noteSbnSeen).
17051
17502
  *
17052
17503
  * Throws for a packetId that was never configured, so a classified block
17053
17504
  * never reads the manager-global K or timeout.
17054
17505
  */
17055
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
17506
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
17056
17507
  const trackConfig = this.#trackConfigs.get(packetId);
17057
17508
  if (trackConfig === void 0) {
17058
17509
  throw new Error(
@@ -17068,7 +17519,8 @@ var FECManager = class _FECManager {
17068
17519
  catalogTrackName,
17069
17520
  "source",
17070
17521
  evidence.packetSequenceNumber,
17071
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
17522
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
17523
+ held
17072
17524
  );
17073
17525
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
17074
17526
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -17104,6 +17556,15 @@ var FECManager = class _FECManager {
17104
17556
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
17105
17557
  return;
17106
17558
  }
17559
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
17560
+ key,
17561
+ sbn,
17562
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
17563
+ packetId,
17564
+ catalogTrackName
17565
+ )) {
17566
+ return;
17567
+ }
17107
17568
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
17108
17569
  }
17109
17570
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -17112,7 +17573,9 @@ var FECManager = class _FECManager {
17112
17573
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17113
17574
  this.#blockSourceCounts.delete(key);
17114
17575
  this.#blockSourceEsis.delete(key);
17576
+ this.#blockRebuiltEsis.delete(key);
17115
17577
  this.#blockAuthoredLengths.delete(key);
17578
+ this.#isoSpanKeys.delete(key);
17116
17579
  this.#blockRepairRsIds.delete(key);
17117
17580
  this.#blockRsbLengths.delete(key);
17118
17581
  this.#markTerminal(key, sbn, packetId, true);
@@ -17143,6 +17606,19 @@ var FECManager = class _FECManager {
17143
17606
  #receiptNow() {
17144
17607
  return this.#receiptAtMs ?? performance.now();
17145
17608
  }
17609
+ /**
17610
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
17611
+ * scope: counted from the receipt time, as the timer of a symbol fed when
17612
+ * it was received was, less the whole ms since. So it fires on the tick
17613
+ * that timer would have, never later than a delay counted from now, and
17614
+ * its handler still re-arms a timer that fires before its deadline.
17615
+ * Counted from now, a deadline set from the receipt time is rounded up
17616
+ * from another fraction of a ms (BLO-52085).
17617
+ */
17618
+ #receiptTimerDelayMs(deadlineMs, minMs) {
17619
+ const receivedAtMs = this.#receiptAtMs;
17620
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
17621
+ }
17146
17622
  /**
17147
17623
  * A held packet admitted late arms from its (earlier) receipt time; that
17148
17624
  * never pulls in a deadline later activity already armed. Outside a
@@ -17178,10 +17654,20 @@ var FECManager = class _FECManager {
17178
17654
  this.#repairDeadlineMs(trackConfig)
17179
17655
  );
17180
17656
  }
17181
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
17657
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
17658
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
17659
+ return;
17660
+ }
17661
+ this.#armBlockTimeout(
17662
+ sbn,
17663
+ packetId,
17664
+ catalogTrackName,
17665
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
17666
+ );
17182
17667
  }
17183
17668
  #failBlock(sbn, packetId, catalogTrackName) {
17184
17669
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
17670
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
17185
17671
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
17186
17672
  this.#clearRepairDeadline(key);
17187
17673
  this.#clearBlockTimer(key);
@@ -17191,6 +17677,7 @@ var FECManager = class _FECManager {
17191
17677
  }
17192
17678
  this.#blockSourceCounts.delete(key);
17193
17679
  this.#blockSourceEsis.delete(key);
17680
+ this.#blockRebuiltEsis.delete(key);
17194
17681
  this.#blockAuthoredLengths.delete(key);
17195
17682
  this.#blockRepairRsIds.delete(key);
17196
17683
  this.#blockRsbLengths.delete(key);
@@ -17200,7 +17687,8 @@ var FECManager = class _FECManager {
17200
17687
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
17201
17688
  this.#fecStats.blocksFailed++;
17202
17689
  this.#statsForPacket(packetId).blocksFailed++;
17203
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17690
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17691
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
17204
17692
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
17205
17693
  }
17206
17694
  /**
@@ -17229,7 +17717,9 @@ var FECManager = class _FECManager {
17229
17717
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
17230
17718
  this.#blockSourceCounts.delete(key);
17231
17719
  this.#blockSourceEsis.delete(key);
17720
+ this.#blockRebuiltEsis.delete(key);
17232
17721
  this.#blockAuthoredLengths.delete(key);
17722
+ this.#isoSpanKeys.delete(key);
17233
17723
  this.#blockRepairRsIds.delete(key);
17234
17724
  this.#blockRsbLengths.delete(key);
17235
17725
  this.#clearBlockTimer(key);
@@ -17320,7 +17810,9 @@ var FECManager = class _FECManager {
17320
17810
  this.#blockKeysBySbn.clear();
17321
17811
  this.#blockSourceCounts.clear();
17322
17812
  this.#blockSourceEsis.clear();
17813
+ this.#blockRebuiltEsis.clear();
17323
17814
  this.#blockAuthoredLengths.clear();
17815
+ this.#isoSpanKeys.clear();
17324
17816
  this.#blockRepairRsIds.clear();
17325
17817
  this.#blockRsbLengths.clear();
17326
17818
  this.#heldLayerStates.clear();
@@ -17345,6 +17837,7 @@ var FECManager = class _FECManager {
17345
17837
  this.#blockAnchorsMs.clear();
17346
17838
  this.#blockCatalogTrackNames.clear();
17347
17839
  this.#classifiers.clear();
17840
+ this.#noSpanRaps.clear();
17348
17841
  this.#streamGeometries.clear();
17349
17842
  this.#failedBlocks.clear();
17350
17843
  this.#resolvedBlockClasses.clear();
@@ -17875,9 +18368,21 @@ var IsoBmffTimingResolver = class {
17875
18368
  }
17876
18369
  #track = null;
17877
18370
  #fragments = /* @__PURE__ */ new Map();
18371
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
18372
+ #firstSamples = /* @__PURE__ */ new Map();
18373
+ /**
18374
+ * First sample and sample count of the newest fragments whose every slot was
18375
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
18376
+ * matches the combiner, since it retires an abandoned sample as well.
18377
+ */
18378
+ #delivered = /* @__PURE__ */ new Map();
17878
18379
  #pendingSamples = 0;
17879
18380
  #evictedSamples = 0;
17880
18381
  #lastMovieFragmentRejection = null;
18382
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
18383
+ get initialized() {
18384
+ return this.#track !== null;
18385
+ }
17881
18386
  get pendingSampleCount() {
17882
18387
  return this.#pendingSamples;
17883
18388
  }
@@ -17901,7 +18406,14 @@ var IsoBmffTimingResolver = class {
17901
18406
  this.#track = timing;
17902
18407
  return true;
17903
18408
  }
17904
- addMovieFragment(mpuSequenceNumber2, data, additionalSampleLimit = this.maxPendingSamples) {
18409
+ /**
18410
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
18411
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
18412
+ * fragment whose samples are all done is a duplicate: admitting it again
18413
+ * would charge stale timing and could displace the live MPU's. A source
18414
+ * copy is still admitted again (a rendition switch re-arms timing that way).
18415
+ */
18416
+ addMovieFragment(mpuSequenceNumber2, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
17905
18417
  this.#lastMovieFragmentRejection = null;
17906
18418
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
17907
18419
  this.#lastMovieFragmentRejection = "invalid";
@@ -17927,6 +18439,8 @@ var IsoBmffTimingResolver = class {
17927
18439
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
17928
18440
  );
17929
18441
  }
18442
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
18443
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
17930
18444
  let freed = 0;
17931
18445
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
17932
18446
  freed += this.#evictOldestFragment();
@@ -17940,6 +18454,7 @@ var IsoBmffTimingResolver = class {
17940
18454
  return false;
17941
18455
  }
17942
18456
  this.#fragments.set(key, [...parsed.samples]);
18457
+ this.#firstSamples.set(key, parsed.samples[0]);
17943
18458
  this.#pendingSamples += parsed.samples.length;
17944
18459
  return true;
17945
18460
  }
@@ -17997,6 +18512,7 @@ var IsoBmffTimingResolver = class {
17997
18512
  let live = 0;
17998
18513
  for (const sample of samples) if (sample !== null) live++;
17999
18514
  this.#fragments.delete(oldest);
18515
+ this.#firstSamples.delete(oldest);
18000
18516
  this.#pendingSamples -= live;
18001
18517
  this.#evictedSamples += live;
18002
18518
  return live;
@@ -18012,12 +18528,23 @@ var IsoBmffTimingResolver = class {
18012
18528
  if (!samples || !samples[index]) return false;
18013
18529
  samples[index] = null;
18014
18530
  this.#pendingSamples--;
18015
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
18531
+ if (samples.every((value) => value === null)) {
18532
+ this.#fragments.delete(key);
18533
+ const first = this.#firstSamples.get(key);
18534
+ this.#firstSamples.delete(key);
18535
+ this.#delivered.delete(key);
18536
+ this.#delivered.set(key, { first, sampleCount: samples.length });
18537
+ if (this.#delivered.size > this.maxPendingSamples) {
18538
+ this.#delivered.delete(this.#delivered.keys().next().value);
18539
+ }
18540
+ }
18016
18541
  return true;
18017
18542
  }
18018
18543
  reset() {
18019
18544
  this.#track = null;
18020
18545
  this.#fragments.clear();
18546
+ this.#firstSamples.clear();
18547
+ this.#delivered.clear();
18021
18548
  this.#pendingSamples = 0;
18022
18549
  }
18023
18550
  };
@@ -18187,6 +18714,9 @@ function authoredGap(before, after) {
18187
18714
  function ssIdAfter(a, b) {
18188
18715
  return (a - b | 0) > 0;
18189
18716
  }
18717
+ function holdsRebuilt(stream) {
18718
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
18719
+ }
18190
18720
  var FecReleaseSequencer = class {
18191
18721
  #streams = /* @__PURE__ */ new Map();
18192
18722
  #gate;
@@ -18249,6 +18779,7 @@ var FecReleaseSequencer = class {
18249
18779
  stream.lastSbn = void 0;
18250
18780
  stream.discontinuity = false;
18251
18781
  stream.rapSsId = void 0;
18782
+ stream.sourced = false;
18252
18783
  }
18253
18784
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
18254
18785
  this.#recordStat("droppedStale");
@@ -18275,6 +18806,7 @@ var FecReleaseSequencer = class {
18275
18806
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
18276
18807
  else hi = mid;
18277
18808
  }
18809
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
18278
18810
  stream.buf.splice(lo, 0, frame);
18279
18811
  this.#drainUnlessDeferred(stream);
18280
18812
  }
@@ -18310,6 +18842,41 @@ var FecReleaseSequencer = class {
18310
18842
  }
18311
18843
  return false;
18312
18844
  }
18845
+ /**
18846
+ * These streams' sink is being replaced by one that has seen no source
18847
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
18848
+ * release to the sink being replaced the frames the unanchored path had
18849
+ * already released to it (#cursorPassed): there they waited in its queue,
18850
+ * which its replacement flushes. A stream that holds none is not drained:
18851
+ * it holds nothing the anchor kept back, and a drain would still force out
18852
+ * a frame held past the hold limit, which before the anchor waited for the
18853
+ * next push. Then treat the streams as unsourced until a source frame is
18854
+ * released.
18855
+ */
18856
+ unsource(packetId, catalogTrackName) {
18857
+ for (const stream of this.#streams.values()) {
18858
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
18859
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
18860
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
18861
+ else this.#drain(stream, true);
18862
+ }
18863
+ stream.sourced = false;
18864
+ }
18865
+ }
18866
+ }
18867
+ /**
18868
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
18869
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
18870
+ * packetId.
18871
+ */
18872
+ holdsRebuilt(packetId, catalogTrackName) {
18873
+ for (const stream of this.#streams.values()) {
18874
+ if (stream.packetId !== packetId) continue;
18875
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
18876
+ if (holdsRebuilt(stream)) return true;
18877
+ }
18878
+ return false;
18879
+ }
18313
18880
  /** Re-evaluate held gaps after FEC state changed. */
18314
18881
  poke(streamKey) {
18315
18882
  if (streamKey !== void 0) {
@@ -18401,16 +18968,32 @@ var FecReleaseSequencer = class {
18401
18968
  last: null,
18402
18969
  lastSbn: void 0,
18403
18970
  discontinuity: false,
18404
- rapSsId: void 0
18971
+ rapSsId: void 0,
18972
+ sourced: false,
18973
+ draining: 0
18405
18974
  };
18406
18975
  this.#streams.set(streamKey, stream);
18407
18976
  }
18408
18977
  return stream;
18409
18978
  }
18410
- #drain(stream) {
18979
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
18980
+ #drain(stream, asUnanchored = false) {
18981
+ stream.draining++;
18982
+ try {
18983
+ this.#drainLoop(stream, asUnanchored);
18984
+ } finally {
18985
+ stream.draining--;
18986
+ }
18987
+ }
18988
+ #drainLoop(stream, asUnanchored) {
18411
18989
  while (stream.buf.length > 0 && stream.last !== null) {
18412
18990
  const head = stream.buf[0];
18413
18991
  const last = stream.last;
18992
+ if (compareFrameOrder(head, last) <= 0) {
18993
+ stream.buf.shift();
18994
+ this.#release(stream, head, void 0);
18995
+ continue;
18996
+ }
18414
18997
  if (stream.discontinuity) {
18415
18998
  stream.discontinuity = false;
18416
18999
  stream.buf.shift();
@@ -18424,9 +19007,10 @@ var FecReleaseSequencer = class {
18424
19007
  }
18425
19008
  const headSbn = head.meta.fecSbn;
18426
19009
  const from = stream.lastSbn ?? headSbn;
18427
- const to = headSbn ?? stream.lastSbn;
19010
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
18428
19011
  let lost = [];
18429
19012
  const unanchored = from === void 0 && to === void 0;
19013
+ let unresolved = false;
18430
19014
  if (from !== void 0 && to !== void 0) {
18431
19015
  const resolved = this.#gate.resolvedLoss(
18432
19016
  stream.packetId,
@@ -18435,7 +19019,8 @@ var FecReleaseSequencer = class {
18435
19019
  Math.max(from, to),
18436
19020
  from
18437
19021
  );
18438
- if (resolved === null) {
19022
+ unresolved = resolved === null;
19023
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored)) {
18439
19024
  const heldMs = performance.now() - head.arrivedAtMs;
18440
19025
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
18441
19026
  this.#recordStat("forcedWindowFlushes");
@@ -18443,22 +19028,56 @@ var FecReleaseSequencer = class {
18443
19028
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
18444
19029
  continue;
18445
19030
  }
18446
- lost = resolved;
19031
+ lost = resolved ?? [];
18447
19032
  }
18448
19033
  stream.buf.shift();
18449
19034
  this.#release(
18450
19035
  stream,
18451
19036
  head,
18452
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
19037
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
18453
19038
  );
18454
19039
  }
18455
19040
  }
19041
+ /**
19042
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
19043
+ * source cursor holds it unanchored, and neither does a later frame behind
19044
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
19045
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
19046
+ * like each frame that arrived in front of it since (stale there). The head
19047
+ * then goes, decided as it would be unanchored, once a frame the base path
19048
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
19049
+ * marked one: the base path has passed that one, so a frame still missing
19050
+ * before it can only come from a repair. It also goes while no source frame
19051
+ * has been released, when the direct path shows a recovered frame at once.
19052
+ * And it goes at once while a staged switch decides on when frames arrive
19053
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
19054
+ * sink being replaced: unanchored, it had already reached the sink.
19055
+ * The scan also writes: the `passed` marks it sets stay on the frames,
19056
+ * and push marks a frame it inserts in front of a marked one from them.
19057
+ */
19058
+ #cursorPassed(stream, asUnanchored) {
19059
+ let at2 = -1;
19060
+ for (let i = 0; i < stream.buf.length; i++) {
19061
+ const frame = stream.buf[i];
19062
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
19063
+ frame.passed = true;
19064
+ if (at2 < 0) at2 = i;
19065
+ } else if (frame.passed !== true) break;
19066
+ }
19067
+ if (at2 < 0) return false;
19068
+ return asUnanchored || !stream.sourced || this.#gate.releaseUnanchored?.(stream.packetId, stream.catalogTrackName) === true || stream.buf.some(({ meta }, i) => i > at2 && meta.fecSbnFirst === void 0 && (meta.recovered !== true || meta.fecSbn !== void 0));
19069
+ }
18456
19070
  #release(stream, frame, decision) {
19071
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
19072
+ if (stale) this.#recordStat("droppedStale");
18457
19073
  if (decision) frame.meta.gapBefore = decision;
18458
19074
  stream.last = frame;
18459
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
19075
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
19076
+ stream.lastSbn = frame.meta.fecSbn;
19077
+ }
19078
+ if (frame.meta.recovered !== true) stream.sourced = true;
18460
19079
  this.#gate.onReleased?.(frame.data, frame.meta);
18461
- this.#emit(frame.data, frame.meta);
19080
+ if (!stale) this.#emit(frame.data, frame.meta);
18462
19081
  }
18463
19082
  };
18464
19083
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -18499,6 +19118,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18499
19118
  this.#reclaimedTimingSamples = 0;
18500
19119
  this.#evictedTimingSamples = 0;
18501
19120
  this.#rejectedMovieFragments = 0;
19121
+ this.#recoveredHeadsAwaitingTiming = {
19122
+ held: 0,
19123
+ expired: 0,
19124
+ discarded: 0,
19125
+ superseded: 0
19126
+ };
18502
19127
  this.#sequencers = /* @__PURE__ */ new Map();
18503
19128
  this.#fecGate = null;
18504
19129
  this.#fecSequencer = null;
@@ -18607,6 +19232,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
18607
19232
  #reclaimedTimingSamples;
18608
19233
  #evictedTimingSamples;
18609
19234
  #rejectedMovieFragments;
19235
+ #recoveredHeadsAwaitingTiming;
18610
19236
  #sequencers;
18611
19237
  #fecGate;
18612
19238
  #fecSequencer;
@@ -18712,11 +19338,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18712
19338
  /**
18713
19339
  * Typed view of the ISO-BMFF timing-sample budget.
18714
19340
  *
18715
- * This is the acceptance signal for the budget ratchet: `pending` walking
18716
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
18717
- * and it is observable here rather than only as media silently stopping.
18718
- * Per repo policy this is a producer-owned counter -- never infer budget
18719
- * state by parsing logs.
19341
+ * Each stream admits timing against its own window of `capacity` slots
19342
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
19343
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
19344
+ * timing a stream declared and never delivered shows up there. `pending`
19345
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
19346
+ * a producer-owned counter -- never infer budget state by parsing logs.
18720
19347
  */
18721
19348
  get timingBudgetStats() {
18722
19349
  return {
@@ -18727,6 +19354,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
18727
19354
  rejectedMovieFragments: this.#rejectedMovieFragments
18728
19355
  };
18729
19356
  }
19357
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
19358
+ get recoveredHeadsAwaitingTiming() {
19359
+ let pending = 0;
19360
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
19361
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
19362
+ }
19363
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
19364
+ }
18730
19365
  get reorderStats() {
18731
19366
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
18732
19367
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -18768,6 +19403,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
18768
19403
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
18769
19404
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
18770
19405
  }
19406
+ /** See FecReleaseSequencer.unsource. */
19407
+ unsourceFecRelease(packetId, catalogTrackName) {
19408
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
19409
+ }
19410
+ /** See FecReleaseSequencer.holdsRebuilt. */
19411
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
19412
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
19413
+ }
18771
19414
  /** Re-evaluate held gaps after FEC block state changed. */
18772
19415
  pokeFecRelease(packetId, catalogTrackName) {
18773
19416
  if (!this.#fecSequencer) return;
@@ -18900,7 +19543,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
18900
19543
  const now = Date.now();
18901
19544
  for (const { awaitingTiming } of this.#timingStreams.values()) {
18902
19545
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
18903
- awaitingTiming.shift();
19546
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
18904
19547
  }
18905
19548
  }
18906
19549
  }
@@ -19018,11 +19661,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
19018
19661
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
19019
19662
  return this.#drop("fragment-unexpected-fragmentation");
19020
19663
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
19021
- if (!resolver2) return this.#drop("fragment-no-resolver");
19664
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
19022
19665
  const pendingBefore = resolver2.pendingSampleCount;
19023
19666
  const evictedBefore = resolver2.evictedSampleCount;
19024
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
19025
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
19667
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
19668
+ const admitted = resolver2.addMovieFragment(
19669
+ mpu.mpuSequenceNumber,
19670
+ data,
19671
+ remaining,
19672
+ options?.recovered === true
19673
+ );
19026
19674
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
19027
19675
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
19028
19676
  if (!admitted) {
@@ -19042,7 +19690,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19042
19690
  };
19043
19691
  }
19044
19692
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
19045
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
19693
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
19046
19694
  if (!resolver) return this.#drop("mfu-no-resolver");
19047
19695
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
19048
19696
  return this.#drop("mfu-empty-payload");
@@ -19063,6 +19711,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19063
19711
  mpuSequenceNumber: mpu.mpuSequenceNumber,
19064
19712
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
19065
19713
  sampleNumber: mfuDuHeader.sampleNumber,
19714
+ sequenceNumber: info.sequenceNumber,
19066
19715
  arrivedAt: Date.now()
19067
19716
  });
19068
19717
  return this.#drop("mfu-sample-timing-missing");
@@ -19088,7 +19737,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19088
19737
  info,
19089
19738
  resolver,
19090
19739
  options?.recovered === true,
19091
- options?.fecSbn
19740
+ options?.fecSbn,
19741
+ options?.fecSbnFirst
19092
19742
  );
19093
19743
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
19094
19744
  }
@@ -19181,7 +19831,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19181
19831
  info,
19182
19832
  resolver,
19183
19833
  options?.recovered === true,
19184
- options?.fecSbn
19834
+ options?.fecSbn,
19835
+ options?.fecSbnFirst
19185
19836
  );
19186
19837
  if (outcome.record !== void 0) return outcome.record;
19187
19838
  return this.#drop(outcome.reason);
@@ -19201,7 +19852,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19201
19852
  * attribution exists to keep readable. Leaving the choice at the call site
19202
19853
  * is what keeps both true.
19203
19854
  */
19204
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
19855
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
19205
19856
  const timing = resolver.sampleTiming(
19206
19857
  combined.mpuSequenceNumber,
19207
19858
  combined.movieFragmentSequenceNumber,
@@ -19218,6 +19869,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19218
19869
  );
19219
19870
  if (!meta) return { reason: "combined-meta-build-failed" };
19220
19871
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
19872
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
19221
19873
  if (!resolver.consumeSample(
19222
19874
  combined.mpuSequenceNumber,
19223
19875
  combined.movieFragmentSequenceNumber,
@@ -19386,6 +20038,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
19386
20038
  }
19387
20039
  this.#emitFrame(data, meta);
19388
20040
  }
20041
+ /** Whether FT=1 metadata already names this sample, without claiming it. */
20042
+ hasAuthoredTimingFor(packetId, mpuSequenceNumber2, movieFragmentSequenceNumber, sampleNumber, catalogTrackName) {
20043
+ return this.#timingResolver(this.#streamKey(packetId, catalogTrackName), packetId, false)?.sampleTiming(mpuSequenceNumber2, movieFragmentSequenceNumber, sampleNumber) != null;
20044
+ }
19389
20045
  /**
19390
20046
  * Claim and return the authored timing for a recovered sample. Recovery does
19391
20047
  * not pass through the ordinary `feed()` completion path, so it must retire
@@ -19447,6 +20103,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
19447
20103
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
19448
20104
  this.#sequencers.clear();
19449
20105
  this.#fecSequencer?.discard();
20106
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
20107
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
20108
+ }
19450
20109
  this.#timingStreams.clear();
19451
20110
  this.#pendingTimingSamples = 0;
19452
20111
  this.#reliableMoqStartupGate.clear();
@@ -19465,10 +20124,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
19465
20124
  return resolver;
19466
20125
  }
19467
20126
  #awaitTiming(streamKey, head) {
19468
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
19469
- if (!awaitingTiming) return;
20127
+ const state = this.#timingStreams.get(streamKey);
20128
+ if (!state) return;
20129
+ if (!head.options?.recovered) {
20130
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
20131
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
20132
+ state.awaitingTiming = kept;
20133
+ }
20134
+ const awaitingTiming = state.awaitingTiming;
19470
20135
  awaitingTiming.push(head);
19471
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
20136
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
20137
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
20138
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
20139
+ }
20140
+ }
20141
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
20142
+ #leaveAwaitingTiming(head, outcome) {
20143
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
19472
20144
  }
19473
20145
  /**
19474
20146
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -19496,6 +20168,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19496
20168
  const state = this.#timingStreams.get(streamKey);
19497
20169
  if (!state) return;
19498
20170
  this.#timingStreams.delete(streamKey);
20171
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
19499
20172
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
19500
20173
  if (this.#pendingTimingSamples < 0) {
19501
20174
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -22702,7 +23375,18 @@ function keyframeOverlaySsId(header) {
22702
23375
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
22703
23376
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
22704
23377
  }
23378
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
23379
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
23380
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
23381
+ }
23382
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
23383
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
23384
+ return headerPsn + offset >>> 0;
23385
+ }
23386
+ var OVERLAY_ROUTED_LIMIT = 1024;
23387
+ var OVERLAY_PENDING_LIMIT = 256;
22705
23388
  var OVERLAY_OFFSET_MPUS = 16;
23389
+ var OVERLAY_REBUILT_LIMIT = 256;
22706
23390
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
22707
23391
  function assertStreamIdentity(role, stream) {
22708
23392
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -22813,6 +23497,7 @@ var MmtpRouter = class {
22813
23497
  #provenance = /* @__PURE__ */ new Map();
22814
23498
  #onFlowProtected = null;
22815
23499
  #unadmittedListedDrops = 0;
23500
+ #admittedSourceDatagrams = 0;
22816
23501
  #unlistedRepairSetAside = 0;
22817
23502
  #assistBlocks = /* @__PURE__ */ new Map();
22818
23503
  #assistFailures = /* @__PURE__ */ new Map();
@@ -22869,6 +23554,26 @@ var MmtpRouter = class {
22869
23554
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
22870
23555
  */
22871
23556
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23557
+ /**
23558
+ * Per stream, the SS_ID offset at which a base recovery last showed the
23559
+ * sender's own packet_sequence_number: a recovered packet's header psn
23560
+ * equal to its SS_ID minus that offset. While it equals the stream's
23561
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
23562
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
23563
+ * an MPU no member of which arrived).
23564
+ */
23565
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23566
+ /**
23567
+ * The same, shown by the overlay alone, before any base recovery did: a
23568
+ * packet it rebuilt whose base copy carries its protected psn
23569
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
23570
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
23571
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
23572
+ * make the base drop a late base copy of a keyframe the overlay never
23573
+ * finished, and lift a block's late-source cut, which nothing before
23574
+ * this offset did.
23575
+ */
23576
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
22872
23577
  /**
22873
23578
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
22874
23579
  * not parsed, typically because its overlap copy was parsed first
@@ -22938,7 +23643,9 @@ var MmtpRouter = class {
22938
23643
  recovered: 0,
22939
23644
  restarts: 0,
22940
23645
  unsequencedDropped: 0,
22941
- protectedDropped: 0
23646
+ protectedDropped: 0,
23647
+ baseFed: 0,
23648
+ baseUndetermined: 0
22942
23649
  };
22943
23650
  /** Callback fired when a delta-track FEC block completes or fails. */
22944
23651
  #onDeltaBlockCompleteCb = null;
@@ -23111,7 +23818,7 @@ var MmtpRouter = class {
23111
23818
  const cb = this.#getFrameCallback(packetId);
23112
23819
  if (isVideo && !assembler) {
23113
23820
  if (frameMeta.recovered) {
23114
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
23821
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
23115
23822
  } else {
23116
23823
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
23117
23824
  }
@@ -23144,13 +23851,18 @@ var MmtpRouter = class {
23144
23851
  this.#onDeltaBlockCompleteCb?.(packetId, false);
23145
23852
  }
23146
23853
  };
23147
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
23854
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
23148
23855
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
23149
23856
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
23150
23857
  this.#onDeltaBlockCompleteCb?.(packetId, true);
23151
23858
  }
23152
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23153
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23859
+ if (span === void 0) {
23860
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23861
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23862
+ } else {
23863
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
23864
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
23865
+ }
23154
23866
  };
23155
23867
  }
23156
23868
  }
@@ -23195,8 +23907,9 @@ var MmtpRouter = class {
23195
23907
  }
23196
23908
  /**
23197
23909
  * FEC-recovered source symbols whose reconstructed header named a
23198
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
23199
- * a hop re-stamped the sequence after the sender protected the packet.
23910
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
23911
+ * or, rebuilt by the overlay, than their base copy carries: a hop
23912
+ * re-stamped the sequence after the sender protected the packet.
23200
23913
  */
23201
23914
  get restampedRecoveredSequenceCount() {
23202
23915
  return this.#restampedRecoveredSeqs;
@@ -23375,6 +24088,7 @@ var MmtpRouter = class {
23375
24088
  enableMseAssembler(packetId, config, catalogTrackName) {
23376
24089
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
23377
24090
  const previous = this.#mseAssemblers.get(assemblerKey);
24091
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
23378
24092
  if (previous) {
23379
24093
  previous.flush();
23380
24094
  previous.dispose();
@@ -23501,6 +24215,10 @@ var MmtpRouter = class {
23501
24215
  get keyframeOverlayStats() {
23502
24216
  return { ...this.#overlayStats };
23503
24217
  }
24218
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
24219
+ get recoveredHeadsAwaitingTiming() {
24220
+ return this.#parser.recoveredHeadsAwaitingTiming;
24221
+ }
23504
24222
  #isOverlayRepair(repairPacketId, repairTrackName) {
23505
24223
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
23506
24224
  }
@@ -23521,7 +24239,8 @@ var MmtpRouter = class {
23521
24239
  fec,
23522
24240
  k,
23523
24241
  offsets: /* @__PURE__ */ new Map(),
23524
- moqBlocks: /* @__PURE__ */ new Set()
24242
+ moqBlocks: /* @__PURE__ */ new Set(),
24243
+ rebuilt: /* @__PURE__ */ new Map()
23525
24244
  };
23526
24245
  this.#overlays.set(repairPacketId, inst);
23527
24246
  return () => {
@@ -23551,12 +24270,18 @@ var MmtpRouter = class {
23551
24270
  */
23552
24271
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
23553
24272
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
24273
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
24274
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
24275
+ stream.overlayToBase.routed.clear();
24276
+ stream.overlayToBase.pending.clear();
24277
+ }
23554
24278
  }
23555
24279
  #resetOverlay(inst) {
23556
24280
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
23557
24281
  inst.last = void 0;
23558
24282
  inst.offsets.clear();
23559
24283
  inst.moqBlocks.clear();
24284
+ inst.rebuilt.clear();
23560
24285
  }
23561
24286
  #overlaysForSource(sourcePacketId, catalogTrackName) {
23562
24287
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -23607,18 +24332,33 @@ var MmtpRouter = class {
23607
24332
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
23608
24333
  * every overlay installed for its source, at that SS_ID, with the bytes the
23609
24334
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
23610
- * included (7.1, 7.4.3).
23611
- */
23612
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
24335
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
24336
+ * FEC reads it.
24337
+ *
24338
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
24339
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
24340
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
24341
+ * the stream unstamped at the SS_ID offset it states, for the release gate
24342
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
24343
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
24344
+ */
24345
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
23613
24346
  if (this.#overlays.size === 0) return;
23614
24347
  const ssId = keyframeOverlaySsId(header);
23615
24348
  if (ssId === void 0) return;
24349
+ let rebuiltPsn;
23616
24350
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
23617
24351
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
24352
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
24353
+ inst.rebuilt.delete(ssId);
23618
24354
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
23619
24355
  if (identity !== null) {
23620
24356
  inst.offsets.delete(identity.mpuSequenceNumber);
23621
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
24357
+ inst.offsets.set(identity.mpuSequenceNumber, {
24358
+ psnOffset: ssId - sequenceNumber >>> 0,
24359
+ overlaySsId: ssId,
24360
+ ...baseSsId === void 0 ? {} : { baseSsId }
24361
+ });
23622
24362
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
23623
24363
  }
23624
24364
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23640,6 +24380,14 @@ var MmtpRouter = class {
23640
24380
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
23641
24381
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
23642
24382
  }
24383
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
24384
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
24385
+ if (rebuiltPsn !== sequenceNumber) {
24386
+ this.#restampedRecoveredSeqs++;
24387
+ } else if (baseSsId !== void 0) {
24388
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24389
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24390
+ }
23643
24391
  }
23644
24392
  #noteOverlayMoqBlock(inst, blockStart) {
23645
24393
  inst.moqBlocks.add(blockStart);
@@ -23673,11 +24421,16 @@ var MmtpRouter = class {
23673
24421
  }
23674
24422
  /**
23675
24423
  * Route an overlay-recovered block's packets as source media of the
23676
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
23677
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
23678
- * base re-stamp, no block advance. Each packet's wire sequence is restored
23679
- * from its keyframe's own offset; without one, a stream the base never
23680
- * re-stamped keeps the header's sequence and any other drops the packet.
24424
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
24425
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
24426
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
24427
+ * base FEC recovered does, so it waits behind base frames still in flight,
24428
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
24429
+ * longer than unanchored; one whose base SS_ID is undetermined has no
24430
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
24431
+ * advance. Each packet's wire sequence is restored from its keyframe's own
24432
+ * offset; without one, a stream the base never re-stamped keeps the
24433
+ * header's sequence and any other drops the packet.
23681
24434
  */
23682
24435
  #routeOverlayRecovered(inst, blockStart, recovered) {
23683
24436
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23697,22 +24450,139 @@ var MmtpRouter = class {
23697
24450
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
23698
24451
  const restamped = this.#restampedStreams.has(streamKey);
23699
24452
  const restored = /* @__PURE__ */ new Set();
24453
+ const baseSsIds = /* @__PURE__ */ new Map();
24454
+ const gateOnly = /* @__PURE__ */ new Set();
23700
24455
  const symbols = result.symbols.flatMap((sym) => {
23701
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
23702
- if (offset !== void 0) {
23703
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
24456
+ const overlaySsId = serial32Add(blockStart, sym.index);
24457
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
24458
+ if (anchor !== void 0) {
24459
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
23704
24460
  restored.add(packetSequenceNumber);
23705
- return [{ ...sym, packetSequenceNumber }];
24461
+ const out = { ...sym, packetSequenceNumber };
24462
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
24463
+ if (baseSsId !== void 0) {
24464
+ baseSsIds.set(sym.index, baseSsId);
24465
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24466
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
24467
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24468
+ }
24469
+ }
24470
+ return [out];
24471
+ }
24472
+ if (!restamped) {
24473
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24474
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24475
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24476
+ if (baseSsId !== void 0) {
24477
+ baseSsIds.set(sym.index, baseSsId);
24478
+ if (fedSsId === void 0) gateOnly.add(sym.index);
24479
+ } else {
24480
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
24481
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
24482
+ }
24483
+ return [sym];
23706
24484
  }
23707
- if (!restamped) return [sym];
23708
24485
  this.#overlayStats.unsequencedDropped++;
23709
24486
  return [];
23710
24487
  });
23711
24488
  this.#overlayStats.recovered++;
24489
+ const mpuFirst = /* @__PURE__ */ new Map();
24490
+ for (const sym of symbols) {
24491
+ const ssId = baseSsIds.get(sym.index);
24492
+ const mpu = sym.fragment.mpuSequenceNumber;
24493
+ const first = mpuFirst.get(mpu);
24494
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
24495
+ }
24496
+ const firstSsIds = /* @__PURE__ */ new Map();
24497
+ for (const sym of symbols) {
24498
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
24499
+ }
23712
24500
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
23713
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
24501
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
24502
+ baseSsIds,
24503
+ firstSsIds
23714
24504
  });
23715
24505
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
24506
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
24507
+ }
24508
+ /**
24509
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
24510
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
24511
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
24512
+ * base recovery showed; `baseSsIds` holds no other),
24513
+ * so it is fed to the base decoder as a rebuilt source
24514
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
24515
+ * fewer to solve, and its repair can recover the block's other packets.
24516
+ * A base block no repair has stated yet takes it when one does
24517
+ * (#feedPendingRebuilt).
24518
+ *
24519
+ * The overlay route already handled each packet fed (delivered it, or
24520
+ * held an untimed head for its FT=1), so a base recovery routes none of
24521
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
24522
+ * held head would wait in the parser for timing its first copy consumed.
24523
+ * Only an overlay block decoded from multicast symbols alone is fed: with
24524
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
24525
+ * that crossed no multicast socket, which the provenance counted from the
24526
+ * block's own arrivals cannot show.
24527
+ */
24528
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
24529
+ const fec = this.#fecManager;
24530
+ const owner = inst.leg.sourcePacketId;
24531
+ const name = inst.leg.sourceCatalogTrackName;
24532
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
24533
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
24534
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
24535
+ const feeds = [];
24536
+ for (const sym of symbols) {
24537
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
24538
+ const ssId = baseSsIds.get(sym.index);
24539
+ if (ssId === void 0) {
24540
+ this.#overlayStats.baseUndetermined++;
24541
+ continue;
24542
+ }
24543
+ routed.delete(ssId);
24544
+ routed.add(ssId);
24545
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
24546
+ feeds.push([ssId, sym.rawSymbol]);
24547
+ }
24548
+ for (const [ssId, symbolData] of feeds) {
24549
+ if (this.#classifyPacketId(owner) === null) return;
24550
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
24551
+ }
24552
+ }
24553
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
24554
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
24555
+ const fec = this.#fecManager;
24556
+ if (!fec?.feedRebuiltSourceSymbol) return;
24557
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
24558
+ if (coords == null) {
24559
+ const pending = this.#stream(owner, name).overlayToBase.pending;
24560
+ pending.delete(ssId);
24561
+ pending.set(ssId, symbolData.slice());
24562
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
24563
+ return;
24564
+ }
24565
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
24566
+ if (!fed.taken) return;
24567
+ this.#overlayStats.baseFed++;
24568
+ if (fed.recovered === null) return;
24569
+ const sbn = coords.sbn;
24570
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
24571
+ fec.cancelBlockTimeout(sbn, owner, name);
24572
+ fec.countRecovery(owner, sbn, name);
24573
+ fec.markBlockCompleted(sbn, owner, name);
24574
+ });
24575
+ }
24576
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
24577
+ #feedPendingRebuilt(owner, name, block) {
24578
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
24579
+ if (pending === void 0 || pending.size === 0) return;
24580
+ for (const [ssId, symbolData] of [...pending]) {
24581
+ if (this.#classifyPacketId(owner) === null) return;
24582
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
24583
+ pending.delete(ssId);
24584
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
24585
+ }
23716
24586
  }
23717
24587
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
23718
24588
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -23852,6 +24722,10 @@ var MmtpRouter = class {
23852
24722
  get unadmittedListedDropCount() {
23853
24723
  return this.#unadmittedListedDrops;
23854
24724
  }
24725
+ /** Source datagrams (multicast or MoQ) a protected flow's bc-provenance v2 receiver released: admitted at once or held, then admitted by a record. Repair symbols and user-agent-admitted datagrams are not counted. Counted at release, before this router's own track checks: a released datagram those drop, which only a track change between hold and release can cause, still counts, so this is not a count of routed media. */
24726
+ get admittedSourceDatagramCount() {
24727
+ return this.#admittedSourceDatagrams;
24728
+ }
23855
24729
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
23856
24730
  get unlistedRepairSetAsideCount() {
23857
24731
  return this.#unlistedRepairSetAside;
@@ -24338,6 +25212,8 @@ var MmtpRouter = class {
24338
25212
  )) return;
24339
25213
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
24340
25214
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
25215
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
25216
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
24341
25217
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
24342
25218
  const recovered = fec.feedRepairSymbol(
24343
25219
  ownerPacketId,
@@ -24388,7 +25264,7 @@ var MmtpRouter = class {
24388
25264
  catalogTrackName
24389
25265
  )) continue;
24390
25266
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
24391
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
25267
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
24392
25268
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
24393
25269
  }
24394
25270
  if (payload.oversized) continue;
@@ -24475,6 +25351,8 @@ var MmtpRouter = class {
24475
25351
  this.#droppedPreSyncVideo.delete(streamKey);
24476
25352
  this.#latestVideoSeqByStream.delete(streamKey);
24477
25353
  this.#ssIdSeqOffsetByStream.delete(streamKey);
25354
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
25355
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
24478
25356
  this.#multicastRapTwinByStream.delete(streamKey);
24479
25357
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
24480
25358
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -24601,6 +25479,12 @@ var MmtpRouter = class {
24601
25479
  * the outgoing stream stops. The hold is bounded by the incoming stream's
24602
25480
  * own RAP cadence, so no timer is involved.
24603
25481
  *
25482
+ * While the switch is staged, the FEC release gate lets a keyframe the
25483
+ * overlay rebuilt reach it, on either side, when the keyframe did before
25484
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
25485
+ * decides on what each side delivered, and the commit discards the gate's
25486
+ * frames of the outgoing stream.
25487
+ *
24604
25488
  * The commit is one synchronous transition inside the frame path: the
24605
25489
  * outgoing stream's already-admitted frames are released (its queued FEC
24606
25490
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -24651,6 +25535,9 @@ var MmtpRouter = class {
24651
25535
  droppedIncomingFrames: 0
24652
25536
  };
24653
25537
  this.#staged = state;
25538
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
25539
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
25540
+ }
24654
25541
  return {
24655
25542
  cancel: () => {
24656
25543
  if (this.#staged !== state) return false;
@@ -24733,7 +25620,17 @@ var MmtpRouter = class {
24733
25620
  */
24734
25621
  #routeParsedFrame(data, meta) {
24735
25622
  if (this.#classifyPacketId(meta.packetId) === null) return;
24736
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
25623
+ if (this.#staged !== null) {
25624
+ let consumed = false;
25625
+ this.#fecPokeDepth++;
25626
+ try {
25627
+ consumed = this.#interceptSwitchFrame(data, meta);
25628
+ } finally {
25629
+ this.#fecPokeDepth--;
25630
+ this.#flushPendingFecPokes();
25631
+ }
25632
+ if (consumed) return;
25633
+ }
24737
25634
  this.#deliverParsedFrame(data, meta);
24738
25635
  }
24739
25636
  #commitStreamSwitch(state, rap, reason) {
@@ -24885,12 +25782,16 @@ var MmtpRouter = class {
24885
25782
  this.#parser.deferFecRelease(work);
24886
25783
  } finally {
24887
25784
  this.#fecPokeDepth--;
24888
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
24889
- const pokes = [...this.#pendingFecPokes.values()];
24890
- this.#pendingFecPokes.clear();
24891
- for (const poke of pokes) {
24892
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
24893
- }
25785
+ this.#flushPendingFecPokes();
25786
+ }
25787
+ }
25788
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
25789
+ #flushPendingFecPokes() {
25790
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
25791
+ const pokes = [...this.#pendingFecPokes.values()];
25792
+ this.#pendingFecPokes.clear();
25793
+ for (const poke of pokes) {
25794
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
24894
25795
  }
24895
25796
  }
24896
25797
  }
@@ -24968,6 +25869,14 @@ var MmtpRouter = class {
24968
25869
  onRap: (packetId, catalogTrackName, ssId) => {
24969
25870
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
24970
25871
  },
25872
+ // A staged switch commits on when each side's frames reach it
25873
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
25874
+ // they did unanchored.
25875
+ releaseUnanchored: (packetId, catalogTrackName) => {
25876
+ const staged = this.#staged;
25877
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
25878
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
25879
+ },
24971
25880
  onReleased: (data, meta) => {
24972
25881
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
24973
25882
  const timing = meta.authoredTiming;
@@ -25109,6 +26018,7 @@ var MmtpRouter = class {
25109
26018
  const parsed = this.#parser.parsePacket(packet);
25110
26019
  if (!parsed) return;
25111
26020
  const info = parsed.info;
26021
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
25112
26022
  if (source === "multicast" && !manifestAdmitted) {
25113
26023
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
25114
26024
  }
@@ -25390,7 +26300,8 @@ var MmtpRouter = class {
25390
26300
  parsed.header,
25391
26301
  info.sequenceNumber,
25392
26302
  info.rapFlag,
25393
- source
26303
+ source,
26304
+ fecPayloadId?.ssId
25394
26305
  );
25395
26306
  }
25396
26307
  }
@@ -25416,7 +26327,8 @@ var MmtpRouter = class {
25416
26327
  source: parserOptions?.source,
25417
26328
  deliveryProvenance: parserOptions?.deliveryProvenance,
25418
26329
  catalogTrackName: parserOptions?.catalogTrackName,
25419
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
26330
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
26331
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
25420
26332
  };
25421
26333
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
25422
26334
  else this.#parser.feed(packet, feedOptions);
@@ -25540,7 +26452,8 @@ var MmtpRouter = class {
25540
26452
  if (stream === void 0) {
25541
26453
  stream = {
25542
26454
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
25543
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
26455
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
26456
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
25544
26457
  };
25545
26458
  byName.set(catalogTrackName, stream);
25546
26459
  }
@@ -25655,8 +26568,16 @@ var MmtpRouter = class {
25655
26568
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
25656
26569
  this.#emitDirectVideo(packetId, data, meta, cb);
25657
26570
  }
25658
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
26571
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
25659
26572
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
26573
+ if (this.#isFecTrack(packetId)) {
26574
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
26575
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
26576
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
26577
+ this.#emitDirectVideo(packetId, data, meta, cb);
26578
+ return;
26579
+ }
26580
+ }
25660
26581
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
25661
26582
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
25662
26583
  this.#drainDirectRecoveredVideo(
@@ -25810,6 +26731,13 @@ var MmtpRouter = class {
25810
26731
  * frames by epoch only if pre-protection input ever matters.
25811
26732
  */
25812
26733
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
26734
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
26735
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
26736
+ result = {
26737
+ ...result,
26738
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
26739
+ };
26740
+ }
25813
26741
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
25814
26742
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
25815
26743
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -25866,7 +26794,12 @@ var MmtpRouter = class {
25866
26794
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
25867
26795
  if (ownerPacketId == null) return;
25868
26796
  if (this.#classifyPacketId(ownerPacketId) === null) return;
25869
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
26797
+ const fecSbnOf = (index) => {
26798
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
26799
+ const fecSbn = overlay.baseSsIds.get(index);
26800
+ const fecSbnFirst = overlay.firstSsIds.get(index);
26801
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
26802
+ };
25870
26803
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
25871
26804
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
25872
26805
  if (ssIdSeqOffset !== void 0) {
@@ -25874,7 +26807,10 @@ var MmtpRouter = class {
25874
26807
  ...result,
25875
26808
  symbols: result.symbols.map((sym) => {
25876
26809
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
25877
- if (wire === sym.packetSequenceNumber) return sym;
26810
+ if (wire === sym.packetSequenceNumber) {
26811
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
26812
+ return sym;
26813
+ }
25878
26814
  this.#restampedRecoveredSeqs++;
25879
26815
  this.#restampedStreams.add(streamKey);
25880
26816
  return { ...sym, packetSequenceNumber: wire };
@@ -25910,6 +26846,29 @@ var MmtpRouter = class {
25910
26846
  }
25911
26847
  );
25912
26848
  }
26849
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
26850
+ ownerPacketId,
26851
+ sym.fragment.mpuSequenceNumber,
26852
+ sym.fragment.movieFragmentSequenceNumber,
26853
+ sym.fragment.sampleNumber,
26854
+ catalogTrackName
26855
+ );
26856
+ for (const sym of result.symbols) {
26857
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
26858
+ this.#feedViaParser(
26859
+ sym.rawSymbol,
26860
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
26861
+ void 0,
26862
+ {
26863
+ skipFecPayloadId: true,
26864
+ recovered: true,
26865
+ deliveryProvenance,
26866
+ ...fecSbnOf(sym.index),
26867
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
26868
+ }
26869
+ );
26870
+ }
26871
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
25913
26872
  const gated = this.#isFecTrack(ownerPacketId);
25914
26873
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
25915
26874
  if (assembler) {
@@ -27636,6 +28595,12 @@ function isNonNegativeSafeInteger(value) {
27636
28595
  function isSymbolCounts(value) {
27637
28596
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
27638
28597
  }
28598
+ function isSpanFailure(value) {
28599
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
28600
+ const length = value["length"];
28601
+ const sources = value["sources"];
28602
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
28603
+ }
27639
28604
  function isNullableNonNegative(value) {
27640
28605
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
27641
28606
  }
@@ -27655,7 +28620,10 @@ function isRepairLifecycleEvent(value) {
27655
28620
  case "recovered":
27656
28621
  return hasExactKeys(value, ["version", "type", "block", "blockClass", "via", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && (value["via"] === "inband" || value["via"] === "quic") && isSymbolCounts(value["symbols"]);
27657
28622
  case "failed":
27658
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
28623
+ return hasExactKeys(
28624
+ value,
28625
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
28626
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
27659
28627
  case "repair-preempted":
27660
28628
  case "repair-deferred":
27661
28629
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -27864,6 +28832,8 @@ var MulticastManager = class {
27864
28832
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
27865
28833
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
27866
28834
  #repairReleases = /* @__PURE__ */ new Map();
28835
+ /** Protected repair flows owned by each live repair-endpoint release. */
28836
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
27867
28837
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
27868
28838
  #overlayBindings = /* @__PURE__ */ new Map();
27869
28839
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -27921,7 +28891,7 @@ var MulticastManager = class {
27921
28891
  onPublisherRestart: (packetId, catalogTrackName) => {
27922
28892
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
27923
28893
  },
27924
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
28894
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
27925
28895
  const pathCount = this.#fec.blockPathCount(
27926
28896
  sbn,
27927
28897
  packetId,
@@ -27939,7 +28909,8 @@ var MulticastManager = class {
27939
28909
  symbols: {
27940
28910
  multicast: pathCount?.multicastSymbols ?? 0,
27941
28911
  moq: pathCount?.moqSymbols ?? 0
27942
- }
28912
+ },
28913
+ ...span === void 0 ? {} : { span }
27943
28914
  });
27944
28915
  },
27945
28916
  onFrameGap: (decision) => {
@@ -28027,6 +28998,11 @@ var MulticastManager = class {
28027
28998
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
28028
28999
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
28029
29000
  };
29001
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
29002
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
29003
+ if (binding === void 0) return void 0;
29004
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
29005
+ };
28030
29006
  this.#fec.onDecoderUnavailable = (event) => {
28031
29007
  this.#emitRepairLifecycle({
28032
29008
  version: 2,
@@ -28529,6 +29505,9 @@ var MulticastManager = class {
28529
29505
  this.#transport.onFailback((reason) => {
28530
29506
  const joined = this.#provenanceJoin;
28531
29507
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
29508
+ for (const flows of this.#repairProvenanceFlows.values()) {
29509
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
29510
+ }
28532
29511
  this.#onFailback?.(reason);
28533
29512
  });
28534
29513
  }
@@ -28563,6 +29542,12 @@ var MulticastManager = class {
28563
29542
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
28564
29543
  );
28565
29544
  }
29545
+ if (provenanceFlow !== void 0) {
29546
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
29547
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29548
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
29549
+ }
29550
+ }
28566
29551
  const staged = this.#renditionSwitch;
28567
29552
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
28568
29553
  this.configureFec(config);
@@ -28570,8 +29555,8 @@ var MulticastManager = class {
28570
29555
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
28571
29556
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
28572
29557
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
28573
- this.#releaseProvenanceJoin();
28574
29558
  const provenance = config.provenance;
29559
+ this.#releaseProvenanceJoin();
28575
29560
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
28576
29561
  const ingress = protectedTracks === void 0 ? void 0 : {
28577
29562
  tracks: Object.freeze(
@@ -28624,8 +29609,13 @@ var MulticastManager = class {
28624
29609
  * feeds the flow's receiver; media datagrams are held until one admits them.
28625
29610
  */
28626
29611
  #joinProvenance(provenance, ingress) {
29612
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
29613
+ this.#hookFailback();
29614
+ this.#provenanceJoin = { flow: ingress.flow };
29615
+ }
29616
+ #provenanceReceiver(provenance) {
28627
29617
  const { flow, auth } = provenance;
28628
- const receiver = new BcProvenanceV2Receiver({
29618
+ return new BcProvenanceV2Receiver({
28629
29619
  ...provenance.receiver,
28630
29620
  // The caller's ctx when it passes one, else the catalog's: an explicit
28631
29621
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -28642,9 +29632,6 @@ var MulticastManager = class {
28642
29632
  maxAuthDelayMs: flow.maxAuthDelayMs,
28643
29633
  manifestTimerMs: flow.manifestTimerMs
28644
29634
  });
28645
- this.#router.registerProvenanceFlow(ingress, receiver);
28646
- this.#hookFailback();
28647
- this.#provenanceJoin = { flow: ingress.flow };
28648
29635
  }
28649
29636
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
28650
29637
  #releaseProvenanceJoin() {
@@ -28675,8 +29662,25 @@ var MulticastManager = class {
28675
29662
  * callback delivers must come from a subscription opened on
28676
29663
  * `options.gateway`. A callback that also merges another source (a MoQ or
28677
29664
  * WebSocket repair feed) must not name a native provider here.
29665
+ *
29666
+ * An endpoint's `provenance` makes its group a protected flow of its own
29667
+ * (multicast-02 7.2.7), registered here and released with the group; its
29668
+ * records ride in band on the group's port. On the user-agent path a
29669
+ * flow-less repair group of a protected track is set aside, never read, so
29670
+ * a player joining a protected catalog's repair groups passes it.
28678
29671
  */
28679
29672
  joinRepairEndpoints(endpoints, provider, options) {
29673
+ for (const { provenance, flow, source, group, port: port2 } of endpoints) {
29674
+ if (provenance === void 0) continue;
29675
+ if (flow !== void 0) {
29676
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
29677
+ }
29678
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port2 !== provenance.flow.port) {
29679
+ throw new RangeError(
29680
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
29681
+ );
29682
+ }
29683
+ }
28680
29684
  const releases = [];
28681
29685
  let released = false;
28682
29686
  const safely = (each) => {
@@ -28686,17 +29690,36 @@ var MulticastManager = class {
28686
29690
  console.warn("[MulticastManager] repair group release failed", error);
28687
29691
  }
28688
29692
  };
29693
+ const usedFlows = /* @__PURE__ */ new Set();
29694
+ const preparedProvenance = endpoints.map((endpoint) => {
29695
+ if (endpoint.provenance === void 0) return void 0;
29696
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
29697
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29698
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
29699
+ }
29700
+ usedFlows.add(flow);
29701
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
29702
+ });
29703
+ const provenanceFlows = [];
28689
29704
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
28690
29705
  ...owner,
28691
29706
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
28692
29707
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
28693
29708
  }));
28694
29709
  this.#applyRepairOwners(repairOwners);
28695
- for (const endpoint of endpoints) {
29710
+ for (const [index, endpoint] of endpoints.entries()) {
29711
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
28696
29712
  const ingress = {
28697
29713
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
28698
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
29714
+ ...flow === void 0 ? {} : { flow }
28699
29715
  };
29716
+ if (endpoint.provenance !== void 0) {
29717
+ const prepared = preparedProvenance[index];
29718
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
29719
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
29720
+ provenanceFlows.push(prepared.flow);
29721
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
29722
+ }
28700
29723
  let sender;
28701
29724
  const feed = (packet, sourceAddress, ingressToFeed) => {
28702
29725
  if (released) return;
@@ -28726,7 +29749,7 @@ var MulticastManager = class {
28726
29749
  packetIds: endpoint.packetIds,
28727
29750
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
28728
29751
  // A protected repair group's records ride in band on its port (7.2.3).
28729
- ...endpoint.flow === void 0 ? {} : { protected: true }
29752
+ ...flow === void 0 ? {} : { protected: true }
28730
29753
  }, ingress).then((joined) => {
28731
29754
  if (!joined && !released) fail(transport.lastJoinOutcome);
28732
29755
  });
@@ -28735,9 +29758,12 @@ var MulticastManager = class {
28735
29758
  if (released) return;
28736
29759
  released = true;
28737
29760
  this.#repairReleases.delete(release);
29761
+ this.#repairProvenanceFlows.delete(release);
28738
29762
  for (const each of releases.splice(0)) safely(each);
28739
29763
  };
28740
29764
  this.#repairReleases.set(release, repairOwners);
29765
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
29766
+ if (provenanceFlows.length) this.#hookFailback();
28741
29767
  return release;
28742
29768
  }
28743
29769
  #applyRepairOwners(owners) {
@@ -29223,7 +30249,8 @@ var MulticastManager = class {
29223
30249
  blockProfile: parseFecBlockProfile(
29224
30250
  geometry2.blockProfile,
29225
30251
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
29226
- )
30252
+ ),
30253
+ geometry: geometry2
29227
30254
  });
29228
30255
  }
29229
30256
  }
@@ -29262,7 +30289,7 @@ var MulticastManager = class {
29262
30289
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
29263
30290
  const before = this.#overlayBindings.get(sourcePacketId);
29264
30291
  const after = overlayBindings.get(sourcePacketId);
29265
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
30292
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
29266
30293
  if (!same) install.dispose();
29267
30294
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
29268
30295
  else install.reattach();
@@ -29319,10 +30346,12 @@ var MulticastManager = class {
29319
30346
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
29320
30347
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
29321
30348
  * pending hole and reported here, and `closeIsoHoles` must be called for it
29322
- * once its range FETCH ends (or none is sent).
30349
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
30350
+ * pending hole the stream runs past the locator's horizon: returning true,
30351
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
29323
30352
  */
29324
- onUndelimitedLoss(cb) {
29325
- this.#fec.setUndelimitedLossHandler(cb);
30353
+ onUndelimitedLoss(cb, onExpired) {
30354
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
29326
30355
  }
29327
30356
  /**
29328
30357
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -29558,7 +30587,8 @@ var MulticastManager = class {
29558
30587
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
29559
30588
  ...event,
29560
30589
  block: Object.freeze({ ...event.block }),
29561
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
30590
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
30591
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
29562
30592
  }
29563
30593
  );
29564
30594
  if (this.#logRepairLifecycle) {
@@ -32230,6 +33260,7 @@ var RepairLayerSubscriptions = class {
32230
33260
 
32231
33261
  // src/repair-fetch.ts
32232
33262
  var MOQT_PRIORITY_MAX = 255;
33263
+ var WALK_LEAD_MS = 3;
32233
33264
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
32234
33265
  function isMoqtPriority(value) {
32235
33266
  return Number.isSafeInteger(value) && value >= 0 && value <= MOQT_PRIORITY_MAX;
@@ -32280,8 +33311,17 @@ function wireRepairFetch(mc, opts) {
32280
33311
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
32281
33312
  };
32282
33313
  const clearEntry = (entry) => {
32283
- if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
32284
- else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33314
+ const { range } = entry;
33315
+ if (range) {
33316
+ atReport(range, () => mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, range.holeLength));
33317
+ } else {
33318
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33319
+ }
33320
+ };
33321
+ const atReport = (range, work) => {
33322
+ const fec = mc.fecManager;
33323
+ if (range.groups !== null || fec.withReceiptTime === void 0) work();
33324
+ else fec.withReceiptTime(range.reportedAt, work);
32285
33325
  };
32286
33326
  const releaseHold = (entry) => {
32287
33327
  if (entry.range) return;
@@ -32293,7 +33333,7 @@ function wireRepairFetch(mc, opts) {
32293
33333
  if (!run) return;
32294
33334
  entry.running = null;
32295
33335
  run.stopped = reason;
32296
- run.controller.abort();
33336
+ run.controller.abort(reason);
32297
33337
  if (reason === "preempted") releaseHold(entry);
32298
33338
  mc.noteRepairStopped?.(reason, entry.sbn, entry.packetId, entry.catalogTrackName);
32299
33339
  };
@@ -32348,21 +33388,42 @@ function wireRepairFetch(mc, opts) {
32348
33388
  const admit = (entry, now) => {
32349
33389
  const budgetMs = entry.deadlineAt - now;
32350
33390
  const rttMs = readRtt();
32351
- const reason = !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < budgetMs ? null : "rtt-exceeds-budget";
33391
+ const reason = refusal(entry, now, rttMs);
32352
33392
  if (reason === null) return rttMs;
32353
33393
  skip(entry, reason, rttMs, budgetMs);
32354
33394
  return null;
32355
33395
  };
33396
+ const refusal = (entry, now, rttMs) => !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < entry.deadlineAt - now ? null : "rtt-exceeds-budget";
32356
33397
  const retire = (entry) => {
32357
33398
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
32358
33399
  if (entry.expiry !== void 0) clearTimeout(entry.expiry);
32359
33400
  };
32360
- const outstandingBelow = (priority) => {
33401
+ const holdsBack = (entry, priority, videoWalks = true) => {
33402
+ if (entry.priority >= priority) return false;
33403
+ const { walk } = entry;
33404
+ if (walk === void 0) return true;
33405
+ if (entry.priority !== 0 || !videoWalks) return false;
33406
+ return entry.running === null || walk.group !== null && !walk.group.controller.signal.aborted;
33407
+ };
33408
+ const outstandingBelow = (priority, videoWalks = true) => {
32361
33409
  for (const entry of entries.values()) {
32362
- if (entry.priority < priority) return true;
33410
+ if (holdsBack(entry, priority, videoWalks)) return true;
32363
33411
  }
32364
33412
  return false;
32365
33413
  };
33414
+ const yieldVideoWalks = (queued) => {
33415
+ const now = performance.now();
33416
+ const rttMs = readRtt();
33417
+ const due = queued.some((entry) => entry.priority !== 0 && entry.walk === void 0 && !outstandingBelow(entry.priority, false) && refusal(entry, now, rttMs) === null);
33418
+ if (!due) return;
33419
+ for (const entry of entries.values()) {
33420
+ const walk = entry.walk;
33421
+ if (entry.priority !== 0 || walk === void 0 || walk.group === null) continue;
33422
+ if (walk.group.controller.signal.aborted) continue;
33423
+ walk.yielded = true;
33424
+ walk.group.controller.abort();
33425
+ }
33426
+ };
32366
33427
  const preemptBestEffort = () => {
32367
33428
  for (const entry of entries.values()) {
32368
33429
  if (entry.priority === 0 || !entry.running) continue;
@@ -32391,7 +33452,8 @@ function wireRepairFetch(mc, opts) {
32391
33452
  }
32392
33453
  const rttMs = admit(entry, now);
32393
33454
  if (rttMs === null) return;
32394
- if (entry.priority === 0) preemptBestEffort();
33455
+ if (entry.priority === 0 && entry.walk === void 0) preemptBestEffort();
33456
+ if (entry.range === void 0) leaveWalkedGroup(entry);
32395
33457
  if (counted) entry.attempts++;
32396
33458
  mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
32397
33459
  rttMs,
@@ -32413,6 +33475,14 @@ function wireRepairFetch(mc, opts) {
32413
33475
  }
32414
33476
  void execute(entry, run);
32415
33477
  };
33478
+ const leaveWalkedGroup = (block) => {
33479
+ for (const entry of entries.values()) {
33480
+ const group = entry.walk?.group;
33481
+ if (group?.sbn === block.sbn && entry.packetId === block.packetId && entry.catalogTrackName === block.catalogTrackName) {
33482
+ group.controller.abort();
33483
+ }
33484
+ }
33485
+ };
32416
33486
  const dispatch = () => {
32417
33487
  if (disposed) return;
32418
33488
  const now = performance.now();
@@ -32437,6 +33507,7 @@ function wireRepairFetch(mc, opts) {
32437
33507
  for (const entry of queued) {
32438
33508
  if (entry.priority === 0) start(entry);
32439
33509
  }
33510
+ yieldVideoWalks(queued);
32440
33511
  if (outstandingBelow(1)) return;
32441
33512
  for (const entry of queued) {
32442
33513
  if (entry.priority === 1) start(entry);
@@ -32463,6 +33534,16 @@ function wireRepairFetch(mc, opts) {
32463
33534
  }
32464
33535
  return counts.sources + counts.repairGroupLength >= counts.authoredLength;
32465
33536
  };
33537
+ const groupServed = (sbn, packetId, catalogTrackName) => {
33538
+ if (mc.fecManager.blockSymbolCounts === void 0) return false;
33539
+ const counts = symbolCounts(sbn, packetId, catalogTrackName);
33540
+ if (counts === void 0 || counts.authoredLength === void 0) return true;
33541
+ return counts.sources + counts.repairs >= counts.authoredLength || !groupCanComplete(sbn, packetId, catalogTrackName);
33542
+ };
33543
+ const statedEnd = (sbn, packetId, catalogTrackName) => {
33544
+ const length = symbolCounts(sbn, packetId, catalogTrackName)?.authoredLength;
33545
+ return length === void 0 ? void 0 : serial32Add(sbn, length);
33546
+ };
32466
33547
  const finish = (entry, run, fed, error) => {
32467
33548
  if (run.stopped !== null || entry.running !== run || entries.get(entry.key) !== entry) {
32468
33549
  return;
@@ -32507,27 +33588,81 @@ function wireRepairFetch(mc, opts) {
32507
33588
  signal: run.controller.signal,
32508
33589
  subscriberPriority: entry.subscriberPriority
32509
33590
  };
33591
+ const { range } = entry;
33592
+ const feed = (packet) => {
33593
+ if (entry.catalogTrackName === void 0) {
33594
+ mc.processRepairFromMoQ(packet, entry.packetId);
33595
+ } else {
33596
+ mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
33597
+ }
33598
+ };
32510
33599
  try {
32511
- const packets = entry.range ? opts.rangeTransport({
33600
+ const packets = range === void 0 ? opts.transport({ ...common, sbn: entry.sbn }) : entry.walk !== void 0 ? walkHole(entry, entry.walk, range, common) : opts.rangeTransport({
32512
33601
  ...common,
32513
- startGroup: entry.range.startGroup,
32514
- endGroup: entry.range.endGroup,
32515
- lostSsId: entry.range.lostSsId
32516
- }) : opts.transport({ ...common, sbn: entry.sbn });
33602
+ startGroup: range.groups.startGroup,
33603
+ endGroup: range.groups.endGroup,
33604
+ lostSsId: range.lostSsId
33605
+ });
32517
33606
  for await (const packet of packets) {
32518
33607
  if (run.stopped !== null || entry.running !== run) break;
32519
33608
  fed++;
32520
- if (entry.catalogTrackName === void 0) {
32521
- mc.processRepairFromMoQ(packet, entry.packetId);
32522
- } else {
32523
- mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
32524
- }
33609
+ if (range === void 0) feed(packet);
33610
+ else atReport(range, () => feed(packet));
32525
33611
  }
32526
33612
  finish(entry, run, fed, void 0);
32527
33613
  } catch (error) {
32528
33614
  finish(entry, run, fed, error ?? new Error("repair transport rejected"));
32529
33615
  }
32530
33616
  };
33617
+ async function* walkHole(entry, walk, hole, common) {
33618
+ const lostAt = serial32Distance(entry.sbn, hole.lostSsId);
33619
+ for (let first = true; !common.signal.aborted; first = false) {
33620
+ if (!first && entry.priority !== 0 && outstandingBelow(1)) {
33621
+ stop(entry, "preempted");
33622
+ note("repair-preempted", entry);
33623
+ return;
33624
+ }
33625
+ if (!first && entry.priority === 0) {
33626
+ dispatch();
33627
+ if (common.signal.aborted) return;
33628
+ }
33629
+ const sbn = walk.next;
33630
+ let next;
33631
+ if (entries.get(requestKey(sbn, entry.packetId, entry.catalogTrackName))?.running == null) {
33632
+ const rsIds = /* @__PURE__ */ new Set();
33633
+ const group = new AbortController();
33634
+ const cancel = () => group.abort(common.signal.reason);
33635
+ common.signal.addEventListener("abort", cancel, { once: true });
33636
+ walk.group = { sbn, controller: group };
33637
+ try {
33638
+ for await (const packet of opts.transport({ ...common, sbn, signal: group.signal })) {
33639
+ yield packet;
33640
+ const id = extractRepairFecPayloadId(packet);
33641
+ if (id === null || id.ssStart !== sbn || id.ssbLength === 0) continue;
33642
+ next ??= serial32Add(sbn, id.ssbLength);
33643
+ rsIds.add(id.rsId);
33644
+ if (rsIds.size >= id.rsbLength || groupServed(sbn, entry.packetId, entry.catalogTrackName)) {
33645
+ group.abort();
33646
+ break;
33647
+ }
33648
+ }
33649
+ } catch (error) {
33650
+ if (!group.signal.aborted || common.signal.aborted) throw error;
33651
+ } finally {
33652
+ common.signal.removeEventListener("abort", cancel);
33653
+ walk.group = null;
33654
+ }
33655
+ if (walk.yielded) {
33656
+ walk.yielded = false;
33657
+ continue;
33658
+ }
33659
+ }
33660
+ next ??= statedEnd(sbn, entry.packetId, entry.catalogTrackName);
33661
+ if (next === void 0) return;
33662
+ if (serial32Distance(entry.sbn, next) > lostAt) return;
33663
+ walk.next = next;
33664
+ }
33665
+ }
32531
33666
  const removeResetObserver = mc.addTrackResetObserver((packetId, catalogTrackName) => {
32532
33667
  for (const entry of [...entries.values()]) {
32533
33668
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
@@ -32723,7 +33858,37 @@ function wireRepairFetch(mc, opts) {
32723
33858
  throw error;
32724
33859
  }
32725
33860
  };
32726
- if (opts.rangeTransport !== void 0) {
33861
+ const trackKind = (packetId) => {
33862
+ try {
33863
+ return mc.fecManager.trackKindFor?.(packetId);
33864
+ } catch {
33865
+ return void 0;
33866
+ }
33867
+ };
33868
+ const walkDeadlineAt = (packetId, now, deadlineAt) => {
33869
+ let repairDeadlineMs;
33870
+ try {
33871
+ repairDeadlineMs = mc.fecManager.repairDeadlineMsForPacket?.(packetId);
33872
+ } catch {
33873
+ repairDeadlineMs = void 0;
33874
+ }
33875
+ if (repairDeadlineMs === void 0 || !Number.isFinite(repairDeadlineMs)) return deadlineAt;
33876
+ return Math.min(deadlineAt, now + repairDeadlineMs - WALK_LEAD_MS);
33877
+ };
33878
+ const onHoleExpired = (hole) => {
33879
+ if (disposed) return false;
33880
+ const entry = [...entries.values()].find((candidate) => candidate.walk !== void 0 && candidate.packetId === hole.packetId && candidate.catalogTrackName === hole.catalogTrackName && serial32Distance(candidate.sbn, hole.holeStart) < candidate.range.holeLength);
33881
+ if (entry === void 0) return false;
33882
+ queueMicrotask(() => {
33883
+ if (entries.get(entry.key) !== entry) return;
33884
+ retire(entry);
33885
+ stop(entry, "expired");
33886
+ clearEntry(entry);
33887
+ dispatch();
33888
+ });
33889
+ return true;
33890
+ };
33891
+ if (mc.onUndelimitedLoss !== void 0 && mc.closeIsoHoles !== void 0) {
32727
33892
  mc.onUndelimitedLoss((loss) => {
32728
33893
  const { packetId, catalogTrackName, holeStart, holeLength } = loss;
32729
33894
  const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
@@ -32731,9 +33896,11 @@ function wireRepairFetch(mc, opts) {
32731
33896
  const blockProfile = blockProfileOf(packetId);
32732
33897
  const target = opts.resolveTarget(packetId, catalogTrackName);
32733
33898
  if (!target) return close();
32734
- const priority = repairPriorityForClass("unknown");
32735
- const range = rangeFor(loss, target.repairTrack);
32736
- if (range === null) {
33899
+ const walked = opts.rangeTransport === void 0;
33900
+ const holeClass = walked && trackKind(packetId) === "audio" ? "audio" : "unknown";
33901
+ const priority = repairPriorityForClass(holeClass);
33902
+ const groups = walked ? null : rangeFor(loss, target.repairTrack);
33903
+ if (!walked && groups === null) {
32737
33904
  close();
32738
33905
  mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
32739
33906
  return;
@@ -32744,8 +33911,10 @@ function wireRepairFetch(mc, opts) {
32744
33911
  packetId,
32745
33912
  ...catalogTrackName === void 0 ? {} : { catalogTrackName }
32746
33913
  };
32747
- const wire = wirePriority(identity, "unknown");
32748
- const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
33914
+ const wire = wirePriority(identity, holeClass);
33915
+ if (wire === null) return close();
33916
+ const now = performance.now();
33917
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, now, holeClass);
32749
33918
  if (deadline === null) {
32750
33919
  close();
32751
33920
  mc.noteRepairSkipped(
@@ -32757,6 +33926,7 @@ function wireRepairFetch(mc, opts) {
32757
33926
  );
32758
33927
  return;
32759
33928
  }
33929
+ const deadlineAt = walked ? walkDeadlineAt(packetId, now, deadline.deadlineAt) : deadline.deadlineAt;
32760
33930
  const entry = {
32761
33931
  key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
32762
33932
  ...identity,
@@ -32764,15 +33934,16 @@ function wireRepairFetch(mc, opts) {
32764
33934
  blockProfile,
32765
33935
  priority,
32766
33936
  subscriberPriority: wire.subscriberPriority,
32767
- deadlineAt: deadline.deadlineAt,
32768
- playoutDeadlineAt: deadline.deadlineAt - deadline.extensionMs,
33937
+ deadlineAt,
33938
+ playoutDeadlineAt: deadlineAt - deadline.extensionMs,
32769
33939
  anchorAt: deadline.anchorAt,
32770
33940
  delayMs: deadline.delayMs,
32771
33941
  bound: deadline.bound,
32772
33942
  order: enqueueOrder++,
32773
33943
  attempts: 0,
32774
33944
  running: null,
32775
- range: { ...range, lostSsId: loss.lostSsId, holeLength }
33945
+ range: { lostSsId: loss.lostSsId, holeLength, groups, reportedAt: now },
33946
+ ...walked ? { walk: { next: holeStart, group: null, yielded: false } } : {}
32776
33947
  };
32777
33948
  const previous = entries.get(entry.key);
32778
33949
  if (previous) {
@@ -32782,7 +33953,7 @@ function wireRepairFetch(mc, opts) {
32782
33953
  entries.set(entry.key, entry);
32783
33954
  entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
32784
33955
  dispatch();
32785
- });
33956
+ }, onHoleExpired);
32786
33957
  }
32787
33958
  const removeRapObserver = mc.addRapCompleteObserver?.((packetId) => {
32788
33959
  queueMicrotask(() => {