@blockcast/mmt-container 2.2.0-main.c4fa878f4ff4 → 2.2.0-main.caa271d80062

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 (111) hide show
  1. package/README.md +34 -19
  2. package/dist/block-policy.d.ts +88 -16
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +164 -56
  5. package/dist/block-policy.js.map +3 -3
  6. package/dist/browser-runtime.js +2064 -388
  7. package/dist/browser-runtime.js.map +3 -3
  8. package/dist/carp-catalog.js.map +2 -2
  9. package/dist/catalog-fec-params.d.ts +18 -2
  10. package/dist/catalog-fec-params.d.ts.map +1 -1
  11. package/dist/catalog-fec-params.js +29 -1
  12. package/dist/catalog-fec-params.js.map +2 -2
  13. package/dist/catalog-network-source.js.map +2 -2
  14. package/dist/cmaf-block-assembler.js +92 -1
  15. package/dist/cmaf-block-assembler.js.map +2 -2
  16. package/dist/cmcd-producer.d.ts +60 -47
  17. package/dist/cmcd-producer.d.ts.map +1 -1
  18. package/dist/cmcd-producer.js +138 -109
  19. package/dist/cmcd-producer.js.map +2 -2
  20. package/dist/codec-utils.d.ts.map +1 -1
  21. package/dist/codec-utils.js +92 -1
  22. package/dist/codec-utils.js.map +2 -2
  23. package/dist/delivery-catalog.js +26 -16
  24. package/dist/delivery-catalog.js.map +2 -2
  25. package/dist/delta-fallback-config.js +5 -1
  26. package/dist/delta-fallback-config.js.map +3 -3
  27. package/dist/fec-manager.d.ts +163 -20
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +863 -110
  30. package/dist/fec-manager.js.map +3 -3
  31. package/dist/fec-state.js +5 -1
  32. package/dist/fec-state.js.map +2 -2
  33. package/dist/fec-worker-setup.d.ts +1 -1
  34. package/dist/fec-worker-setup.js +1 -1
  35. package/dist/fec-worker-setup.js.map +2 -2
  36. package/dist/held-layer-admission.js.map +2 -2
  37. package/dist/index.d.ts +4 -4
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +8 -2
  40. package/dist/index.js.map +2 -2
  41. package/dist/iso-block-locator.d.ts +64 -13
  42. package/dist/iso-block-locator.d.ts.map +1 -1
  43. package/dist/iso-block-locator.js +125 -25
  44. package/dist/iso-block-locator.js.map +2 -2
  45. package/dist/iso-bmff-timing.d.ts +10 -1
  46. package/dist/iso-bmff-timing.d.ts.map +1 -1
  47. package/dist/iso-bmff-timing.js +36 -2
  48. package/dist/iso-bmff-timing.js.map +2 -2
  49. package/dist/media-router.js.map +1 -1
  50. package/dist/mfu-reassembler.js.map +2 -2
  51. package/dist/mmtp-container-parser.d.ts +109 -12
  52. package/dist/mmtp-container-parser.d.ts.map +1 -1
  53. package/dist/mmtp-container-parser.js +312 -27
  54. package/dist/mmtp-container-parser.js.map +2 -2
  55. package/dist/mmtp-container-parser.no-modules.js +333 -32
  56. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  57. package/dist/mmtp-decode-pipeline.js +311 -27
  58. package/dist/mmtp-decode-pipeline.js.map +2 -2
  59. package/dist/mmtp-fec-session.js.map +2 -2
  60. package/dist/mmtp-router.d.ts +51 -12
  61. package/dist/mmtp-router.d.ts.map +1 -1
  62. package/dist/mmtp-router.js +723 -83
  63. package/dist/mmtp-router.js.map +3 -3
  64. package/dist/multicast-auth-catalog.js.map +2 -2
  65. package/dist/multicast-input.js.map +2 -2
  66. package/dist/multicast-manager.d.ts +31 -3
  67. package/dist/multicast-manager.d.ts.map +1 -1
  68. package/dist/multicast-manager.js +1698 -231
  69. package/dist/multicast-manager.js.map +3 -3
  70. package/dist/multicast-transport.js +28 -18
  71. package/dist/multicast-transport.js.map +2 -2
  72. package/dist/multicast-unwrap.js.map +2 -2
  73. package/dist/no-modules.d.ts +1 -0
  74. package/dist/no-modules.d.ts.map +1 -1
  75. package/dist/no-modules.js +333 -31
  76. package/dist/no-modules.js.map +4 -4
  77. package/dist/repair-fetch.d.ts +38 -8
  78. package/dist/repair-fetch.d.ts.map +1 -1
  79. package/dist/repair-fetch.js +286 -27
  80. package/dist/repair-fetch.js.map +3 -3
  81. package/dist/repair-layer-subscriptions.d.ts +6 -2
  82. package/dist/repair-layer-subscriptions.d.ts.map +1 -1
  83. package/dist/repair-layer-subscriptions.js +6 -3
  84. package/dist/repair-layer-subscriptions.js.map +2 -2
  85. package/dist/signaling.js.map +2 -2
  86. package/dist/timestamp-codec.js.map +2 -2
  87. package/dist/track-session.d.ts +1 -1
  88. package/dist/track-session.d.ts.map +1 -1
  89. package/dist/track-session.js +1 -0
  90. package/dist/track-session.js.map +2 -2
  91. package/dist/wasm-mfu-reassembler.js.map +2 -2
  92. package/dist/wasm-mmtp-container-parser.js +311 -27
  93. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  94. package/package.json +8 -5
  95. package/schemas/catalog.schema.json +4 -0
  96. package/src/block-policy.ts +324 -83
  97. package/src/catalog-fec-params.ts +37 -1
  98. package/src/cmcd-producer.ts +189 -179
  99. package/src/codec-utils.ts +121 -1
  100. package/src/fec-manager.ts +818 -42
  101. package/src/fec-worker-setup.ts +2 -2
  102. package/src/index.ts +11 -2
  103. package/src/iso-block-locator.ts +167 -31
  104. package/src/iso-bmff-timing.ts +40 -1
  105. package/src/mmtp-container-parser.ts +355 -32
  106. package/src/mmtp-router.ts +665 -50
  107. package/src/multicast-manager.ts +145 -16
  108. package/src/no-modules.ts +3 -0
  109. package/src/repair-fetch.ts +366 -50
  110. package/src/repair-layer-subscriptions.ts +13 -5
  111. package/src/track-session.ts +4 -1
@@ -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
  }
@@ -1786,13 +1797,25 @@ function fecCatalogTracks(catalog) {
1786
1797
  });
1787
1798
  return { tracks, pointers };
1788
1799
  }
1789
- function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1800
+ function runtimeView(catalog, receiver) {
1790
1801
  const { tracks, pointers } = fecCatalogTracks(catalog);
1791
1802
  const report = validateFecCatalog({ tracks }, receiver);
1792
1803
  const at2 = (path) => {
1793
1804
  const m = /^\/tracks\/(\d+)(.*)$/.exec(path);
1794
1805
  return m ? pointers[Number(m[1])] + m[2] : path;
1795
1806
  };
1807
+ return { tracks, pointers, report, at: at2 };
1808
+ }
1809
+ function runtimeFecCatalogReport(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1810
+ const { report, at: at2 } = runtimeView(catalog, receiver);
1811
+ const issue = (i) => Object.freeze({ code: i.code, path: at2(i.path) });
1812
+ return Object.freeze({
1813
+ instances: Object.freeze(report.instances.map((i) => Object.freeze({ ...i, path: at2(i.path), issues: Object.freeze(i.issues.map(issue)) }))),
1814
+ issues: Object.freeze(report.issues.map(issue))
1815
+ });
1816
+ }
1817
+ function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1818
+ const { tracks, pointers, report, at: at2 } = runtimeView(catalog, receiver);
1796
1819
  const trackAt = (i) => recordOf(tracks[i]) ?? {};
1797
1820
  const nameAt = (i) => i === null ? void 0 : trackAt(i)["name"];
1798
1821
  const why = (i) => Object.freeze({
@@ -6088,9 +6111,10 @@ function isH264IntraSlice(nal) {
6088
6111
  const sliceType = readH264SliceType(nal);
6089
6112
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
6090
6113
  }
6114
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
6091
6115
  function readH264SliceType(nal) {
6092
6116
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6093
- const rbsp = removeEmulationPrevention(nal.subarray(1));
6117
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
6094
6118
  const state = { bitOffset: 0 };
6095
6119
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6096
6120
  return readUnsignedExpGolomb(rbsp, state);
@@ -6459,6 +6483,96 @@ if (void 0) {
6459
6483
  ]))).toBe(false);
6460
6484
  });
6461
6485
  });
6486
+ describe("readH264SliceType", () => {
6487
+ const wholeNalSliceType = (nal) => {
6488
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6489
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
6490
+ const state = { bitOffset: 0 };
6491
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6492
+ return readUnsignedExpGolomb(rbsp, state);
6493
+ };
6494
+ const hex3 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
6495
+ const ue = (value) => {
6496
+ const code = (value + 1).toString(2);
6497
+ return "0".repeat(code.length - 1) + code;
6498
+ };
6499
+ const sliceNal = (bits) => {
6500
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
6501
+ const nal = [1];
6502
+ let zeros = 0;
6503
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
6504
+ if (zeros >= 2 && byte <= 3) {
6505
+ nal.push(3);
6506
+ zeros = 0;
6507
+ }
6508
+ nal.push(byte);
6509
+ zeros = byte === 0 ? zeros + 1 : 0;
6510
+ }
6511
+ return Uint8Array.from(nal);
6512
+ };
6513
+ const x264Slices = [
6514
+ ["64x48 P", hex3("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
6515
+ ["64x48 B", hex3("419e414212fffeeade283707cb70f7"), 6, false],
6516
+ ["64x48 non-IDR I", hex3(
6517
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
6518
+ ), 7, true],
6519
+ ["1280x720 B, escape at byte 10", hex3(
6520
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
6521
+ ), 6, false],
6522
+ ["1280x720 P, escape at byte 15", hex3(
6523
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
6524
+ ), 5, false],
6525
+ ["1280x720 B, escape at byte 22", hex3("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
6526
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex3(
6527
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
6528
+ ), null, true],
6529
+ ["7680x4320 P, first_mb_in_slice 32640", hex3(
6530
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
6531
+ ), 5, false],
6532
+ ["7680x4320 P, first_mb_in_slice 97440", hex3(
6533
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
6534
+ ), 5, false]
6535
+ ];
6536
+ const syntheticSlices = [
6537
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
6538
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
6539
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
6540
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
6541
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
6542
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
6543
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
6544
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
6545
+ ];
6546
+ test("reads the slice_type of real and synthetic slices", () => {
6547
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
6548
+ expect(readH264SliceType(nal), name).toBe(sliceType);
6549
+ }
6550
+ });
6551
+ test("matches the whole-NAL unescape at every truncation", () => {
6552
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
6553
+ for (let end = 0; end <= nal.length; end++) {
6554
+ const cut = nal.subarray(0, end);
6555
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
6556
+ }
6557
+ }
6558
+ });
6559
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
6560
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
6561
+ let seed = 1;
6562
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
6563
+ for (let i = 0; i < 5e3; i++) {
6564
+ const nal = new Uint8Array(2 + next() % 63);
6565
+ nal[0] = 65;
6566
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
6567
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
6568
+ }
6569
+ });
6570
+ test("classifies the x264 slices as keyframes or not", () => {
6571
+ for (const [name, nal, , keyframe] of x264Slices) {
6572
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
6573
+ }
6574
+ });
6575
+ });
6462
6576
  describe("avccToAnnexB", () => {
6463
6577
  test("converts with SPS/PPS on keyframe", () => {
6464
6578
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -7988,8 +8102,8 @@ var MulticastSubscriptionPool = class {
7988
8102
  record.claims--;
7989
8103
  return this.acquire(gateway, config, consumer);
7990
8104
  }
7991
- const token = Symbol(key);
7992
- entry.consumers.set(token, consumer);
8105
+ const token2 = Symbol(key);
8106
+ entry.consumers.set(token2, consumer);
7993
8107
  let released = false;
7994
8108
  return {
7995
8109
  key,
@@ -7997,7 +8111,7 @@ var MulticastSubscriptionPool = class {
7997
8111
  if (released)
7998
8112
  return;
7999
8113
  released = true;
8000
- entry.consumers.delete(token);
8114
+ entry.consumers.delete(token2);
8001
8115
  record.claims--;
8002
8116
  if (record.claims > 0)
8003
8117
  return;
@@ -8625,9 +8739,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
8625
8739
  } catch (error) {
8626
8740
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
8627
8741
  }
8628
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
8742
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
8629
8743
  await rx.close();
8630
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8744
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8631
8745
  }
8632
8746
  const events = new EventTarget();
8633
8747
  let state = "connected";
@@ -8746,14 +8860,15 @@ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
8746
8860
  });
8747
8861
 
8748
8862
  // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
8863
+ var MAX_PENDING_PACKETS = 256;
8749
8864
  var AMTGatewayManager = class {
8750
8865
  subscriptions = /* @__PURE__ */ new Map();
8751
8866
  messageHandler;
8867
+ messageListenerRegistered = false;
8752
8868
  pendingPackets = /* @__PURE__ */ new Map();
8753
8869
  constructor() {
8754
8870
  this.messageHandler = (event) => {
8755
8871
  const data = event.data;
8756
- console.log(`[AMT] SW message received:`, data.type);
8757
8872
  if (data.type === "UDP_PACKET") {
8758
8873
  this.handlePacket(data);
8759
8874
  } else if (data.type === "SOCKET_ERROR") {
@@ -8762,12 +8877,22 @@ var AMTGatewayManager = class {
8762
8877
  console.log(`[AMT SW Debug] ${data.message}`);
8763
8878
  }
8764
8879
  };
8765
- if (typeof navigator !== "undefined" && navigator.serviceWorker) {
8766
- navigator.serviceWorker.addEventListener("message", this.messageHandler);
8767
- console.log("[AMT] Registered service worker message handler");
8768
- } else {
8769
- console.warn("[AMT] Service worker not available");
8880
+ }
8881
+ ensureMessageListener() {
8882
+ if (this.messageListenerRegistered || typeof navigator === "undefined" || !navigator.serviceWorker || !this.messageHandler) {
8883
+ return;
8770
8884
  }
8885
+ navigator.serviceWorker.addEventListener("message", this.messageHandler);
8886
+ this.messageListenerRegistered = true;
8887
+ console.log("[AMT] Registered service worker message handler");
8888
+ }
8889
+ removeMessageListener() {
8890
+ if (!this.messageListenerRegistered)
8891
+ return;
8892
+ if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
8893
+ navigator.serviceWorker.removeEventListener("message", this.messageHandler);
8894
+ }
8895
+ this.messageListenerRegistered = false;
8771
8896
  }
8772
8897
  /**
8773
8898
  * Subscribe via AMT tunnel
@@ -8777,6 +8902,7 @@ var AMTGatewayManager = class {
8777
8902
  if (config.protected) {
8778
8903
  throw new Error("AMTGatewayManager refuses a protected join: it reports no per-datagram sender (multicast-02 7.2.7)");
8779
8904
  }
8905
+ this.ensureMessageListener();
8780
8906
  const keyStr = this.getKeyString(key);
8781
8907
  if (this.subscriptions.has(keyStr)) {
8782
8908
  console.log(`[AMT] Reusing existing subscription to ${keyStr}`);
@@ -8812,6 +8938,8 @@ var AMTGatewayManager = class {
8812
8938
  this.subscriptions.delete(keyStr);
8813
8939
  this.pendingPackets.delete(subscription.subscriptionId);
8814
8940
  }
8941
+ if (this.subscriptions.size === 0)
8942
+ this.removeMessageListener();
8815
8943
  throw new Error(`Failed to subscribe via AMT: ${error instanceof Error ? error.message : String(error)}`);
8816
8944
  }
8817
8945
  }
@@ -8833,6 +8961,8 @@ var AMTGatewayManager = class {
8833
8961
  } finally {
8834
8962
  this.subscriptions.delete(handle);
8835
8963
  this.pendingPackets.delete(subscription.subscriptionId);
8964
+ if (this.subscriptions.size === 0)
8965
+ this.removeMessageListener();
8836
8966
  }
8837
8967
  }
8838
8968
  /**
@@ -8849,14 +8979,12 @@ var AMTGatewayManager = class {
8849
8979
  if (!subscriptionId)
8850
8980
  return;
8851
8981
  const subscription = this.subscriptions.get(subscriptionId);
8852
- if (!subscription) {
8853
- console.warn(`[AMT] Received packet for unknown subscription: ${subscriptionId}`);
8982
+ if (!subscription)
8854
8983
  return;
8855
- }
8856
8984
  if (!subscription.handshakeComplete) {
8857
8985
  const queue = this.pendingPackets.get(subscriptionId);
8858
8986
  const packetData2 = data;
8859
- if (queue) {
8987
+ if (queue && queue.length < MAX_PENDING_PACKETS) {
8860
8988
  queue.push({
8861
8989
  data: packetData2.data,
8862
8990
  remoteAddress: packetData2.remoteAddress,
@@ -8882,19 +9010,15 @@ var AMTGatewayManager = class {
8882
9010
  if (!subscriptionId)
8883
9011
  return;
8884
9012
  const subscription = this.subscriptions.get(subscriptionId);
8885
- if (!subscription) {
8886
- console.warn(`[AMT] Received error for unknown subscription: ${subscriptionId}`);
9013
+ if (!subscription)
8887
9014
  return;
8888
- }
8889
9015
  subscription.config.onError(new Error(error || "Unknown error"));
8890
9016
  }
8891
9017
  /**
8892
9018
  * Cleanup on destroy
8893
9019
  */
8894
9020
  destroy() {
8895
- if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
8896
- navigator.serviceWorker.removeEventListener("message", this.messageHandler);
8897
- }
9021
+ this.removeMessageListener();
8898
9022
  const handles = Array.from(this.subscriptions.keys());
8899
9023
  for (const handle of handles) {
8900
9024
  this.unsubscribe(handle).catch((err) => {
@@ -12425,6 +12549,7 @@ var TrackSession = class {
12425
12549
  this.#state = "idle";
12426
12550
  this.#subscription = null;
12427
12551
  this.#disarmFec();
12552
+ this.#unsuppress();
12428
12553
  }
12429
12554
  // -----------------------------------------------------------------------
12430
12555
  // Internal
@@ -12918,6 +13043,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
12918
13043
  this.#heldEvicted = 0;
12919
13044
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
12920
13045
  this.#holes = [];
13046
+ /** Holes the horizon passed while pending: sources held until closed. */
13047
+ this.#expired = [];
13048
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
13049
+ this.#newlyExpired = [];
13050
+ /**
13051
+ * Spans closed from expired holes: behind the horizon, so kept only for
13052
+ * `locate` while their sources are fed, until the next retirement.
13053
+ */
13054
+ this.#closedBehind = [];
12921
13055
  /**
12922
13056
  * Keep a gap that is missing a source as a pending hole rather than a span,
12923
13057
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -12939,7 +13073,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
12939
13073
  #retentionBlocks;
12940
13074
  #heldEvicted;
12941
13075
  #newest;
13076
+ #newestSource;
12942
13077
  #holes;
13078
+ #expired;
13079
+ #newlyExpired;
13080
+ #closedBehind;
12943
13081
  static #checkedRetention(retentionBlocks) {
12944
13082
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
12945
13083
  throw new Error(
@@ -12976,6 +13114,21 @@ var IsoBlockLocator = class _IsoBlockLocator {
12976
13114
  observe(position) {
12977
13115
  if (this.#newest === void 0 || serial32Precedes(this.#newest, position)) this.#newest = position;
12978
13116
  }
13117
+ /**
13118
+ * The newest source SS_ID noted with `noteSource` (RFC 1982 order). Unlike
13119
+ * `newest`, a repair never moves it: a repair can run ahead of its sources,
13120
+ * a source cannot run ahead of the sources sent before it except by
13121
+ * reordering.
13122
+ */
13123
+ get newestSource() {
13124
+ return this.#newestSource;
13125
+ }
13126
+ /** Note a received source's SS_ID; true when it is the newest one yet. */
13127
+ noteSource(ssId) {
13128
+ if (this.#newestSource !== void 0 && !serial32Precedes(this.#newestSource, ssId)) return false;
13129
+ this.#newestSource = ssId;
13130
+ return true;
13131
+ }
12979
13132
  /** Held sources evicted by `heldCapacity` (never by the horizon itself). */
12980
13133
  get heldEvicted() {
12981
13134
  return this.#heldEvicted;
@@ -12994,17 +13147,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
12994
13147
  }
12995
13148
  /** The known block or span containing `ssId`, with its ESI. */
12996
13149
  locate(ssId) {
12997
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
12998
- const block = this.#blocks[i];
12999
- if (isoBlockContains(block.start, block.length, ssId)) {
13000
- return { block, esi: serial32Distance(block.start, ssId) };
13150
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
13151
+ for (let i = blocks.length - 1; i >= 0; i--) {
13152
+ const block = blocks[i];
13153
+ if (isoBlockContains(block.start, block.length, ssId)) {
13154
+ return { block, esi: serial32Distance(block.start, ssId) };
13155
+ }
13001
13156
  }
13002
13157
  }
13003
13158
  return null;
13004
13159
  }
13005
- /** Number of pending holes. */
13160
+ /** Number of holes not closed yet, pending or past the horizon. */
13006
13161
  get holeCount() {
13007
- return this.#holes.length;
13162
+ return this.#holes.length + this.#expired.length;
13163
+ }
13164
+ /**
13165
+ * The pending holes the horizon has passed since the last call, in the
13166
+ * order it passed them. Each is no longer pending: no repair states a block
13167
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
13168
+ * release gate does not wait for it. Its owner must close it
13169
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
13170
+ */
13171
+ takeExpiredHoles() {
13172
+ return this.#newlyExpired.splice(0);
13008
13173
  }
13009
13174
  /** The stated block (never a span) ending exactly at `end`. */
13010
13175
  blockEndingAt(end) {
@@ -13057,12 +13222,42 @@ var IsoBlockLocator = class _IsoBlockLocator {
13057
13222
  isHeld(ssId) {
13058
13223
  return this.#held.has(ssId);
13059
13224
  }
13225
+ /** The payload held unplaced for `ssId`, if any. */
13226
+ heldSource(ssId) {
13227
+ return this.#held.get(ssId);
13228
+ }
13229
+ /**
13230
+ * The SS_IDs strictly between `a` and `b` that no repair has delimited a
13231
+ * block of yet: those from the coverage end on, or all of them before the
13232
+ * first repair. `missing` is the highest of them no source is held for;
13233
+ * absent, every one of them arrived (C.5.2: SS_IDs are consecutive). Null
13234
+ * when none lies past coverage. `flagged` is whether a source held among
13235
+ * them satisfies `flag` (a RAP fragment, say): the held packets read as
13236
+ * fec-multicast-00 Block Classification item 1 reads bounding packets.
13237
+ */
13238
+ undelimitedBetween(a, b, flag) {
13239
+ if (!serial32Precedes(a, b) || serial32Distance(a, b) <= 1) return null;
13240
+ const first = a + 1 >>> 0;
13241
+ const end = this.#coverageEnd;
13242
+ const start = end !== void 0 && serial32Precedes(first, end) ? end : first;
13243
+ if (!serial32Precedes(start, b)) return null;
13244
+ const length = serial32Distance(start, b);
13245
+ const missing = this.#highestMissing(start, length);
13246
+ let flagged = false;
13247
+ for (let i = 0; flag !== void 0 && !flagged && i < length; i++) {
13248
+ const payload = this.#held.get(serial32Add(start, i));
13249
+ flagged = payload !== void 0 && flag(payload);
13250
+ }
13251
+ return missing === void 0 ? { start, flagged } : { start, missing, flagged };
13252
+ }
13060
13253
  /**
13061
13254
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
13062
13255
  * block states its range and places every held source in it; later repair
13063
- * symbols of the same block change nothing. A range that contradicts a
13064
- * known block (a different length, or an overlap with another block or a
13065
- * span) fails closed: the repair symbol is dropped and no block changes.
13256
+ * symbols of the same block change nothing. A repair whose range is exactly
13257
+ * a repair-less span states that span's one block. A range that contradicts
13258
+ * a known block (a different length, or an overlap with another block or
13259
+ * with part of a span) fails closed: the repair symbol is dropped and no
13260
+ * block changes.
13066
13261
  * A newly stated block retires behind its SS_Start (see the class note).
13067
13262
  * A block so far past `newest` that stating it would retire the position
13068
13263
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -13081,7 +13276,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
13081
13276
  const known = this.blockAt(start);
13082
13277
  if (known !== void 0) {
13083
13278
  if (known.span) {
13084
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
13279
+ if (known.length === length) {
13280
+ const block2 = { start, length, span: false };
13281
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
13282
+ return { status: "placed", block: block2, placed: [] };
13283
+ }
13284
+ return length < known.length ? {
13285
+ status: "overlap",
13286
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
13287
+ ofSpan: known
13288
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
13085
13289
  }
13086
13290
  if (known.length !== length) {
13087
13291
  return {
@@ -13149,18 +13353,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
13149
13353
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
13150
13354
  }
13151
13355
  /**
13152
- * Turn every pending hole inside `[start, start + length)` into a
13153
- * repair-less span, claiming its held sources: its range FETCH ended, so
13154
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
13356
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
13357
+ * claiming its held sources: its range FETCH ended, so nothing more will
13358
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
13359
+ * span that is not kept among the blocks, as the horizon would retire it at
13360
+ * once; only `locate` finds it, until the next retirement, so its sources
13361
+ * can be fed. Returns the spans, in SS_ID order.
13155
13362
  */
13156
13363
  closeHolesWithin(start, length) {
13157
13364
  const closed = [];
13158
- for (const hole of [...this.#holes]) {
13159
- if (!isoBlockContains(start, length, hole.start)) continue;
13160
- this.#holes.splice(this.#holes.indexOf(hole), 1);
13161
- const spanBlock = { start: hole.start, length: hole.length, span: true };
13162
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13163
- this.#blocks.push(spanBlock);
13365
+ for (const holes of [this.#holes, this.#expired]) {
13366
+ for (const hole of [...holes]) {
13367
+ if (!isoBlockContains(start, length, hole.start)) continue;
13368
+ holes.splice(holes.indexOf(hole), 1);
13369
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
13370
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13371
+ if (holes === this.#holes) {
13372
+ this.#blocks.push(spanBlock);
13373
+ } else {
13374
+ this.#closedBehind.push(spanBlock);
13375
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
13376
+ }
13377
+ }
13164
13378
  }
13165
13379
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
13166
13380
  }
@@ -13174,15 +13388,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
13174
13388
  return void 0;
13175
13389
  }
13176
13390
  /**
13177
- * Retire every block and span whose last SS_ID, and every held source,
13178
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
13179
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
13180
- * horizon uses. Returns the retired block starts.
13391
+ * Retire every block and span whose last SS_ID, and every held source
13392
+ * outside a hole, lies more than `retentionBlocks` blocks behind
13393
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
13394
+ * every ISO interleave horizon uses; a pending hole so far behind expires
13395
+ * (`takeExpiredHoles`). Returns the retired block starts.
13181
13396
  */
13182
13397
  retireBehind(position) {
13183
13398
  this.observe(position);
13184
13399
  const horizon = this.#retentionBlocks;
13185
13400
  const retired = [];
13401
+ this.#closedBehind.length = 0;
13186
13402
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
13187
13403
  const block = this.#blocks[i];
13188
13404
  const last = serial32Add(block.start, block.length - 1);
@@ -13194,10 +13410,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
13194
13410
  for (let i = this.#holes.length - 1; i >= 0; i--) {
13195
13411
  const hole = this.#holes[i];
13196
13412
  const last = serial32Add(hole.start, hole.length - 1);
13197
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
13413
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
13414
+ this.#holes.splice(i, 1);
13415
+ this.#expired.push(hole);
13416
+ this.#newlyExpired.push(hole);
13198
13417
  }
13199
13418
  for (const ssId of [...this.#held.keys()]) {
13200
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
13419
+ 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))) {
13420
+ this.#held.delete(ssId);
13421
+ }
13201
13422
  }
13202
13423
  return retired;
13203
13424
  }
@@ -13205,9 +13426,13 @@ var IsoBlockLocator = class _IsoBlockLocator {
13205
13426
  reset() {
13206
13427
  this.#blocks.length = 0;
13207
13428
  this.#holes.length = 0;
13429
+ this.#expired.length = 0;
13430
+ this.#newlyExpired.length = 0;
13431
+ this.#closedBehind.length = 0;
13208
13432
  this.#held.clear();
13209
13433
  this.#coverageEnd = void 0;
13210
13434
  this.#newest = void 0;
13435
+ this.#newestSource = void 0;
13211
13436
  }
13212
13437
  #claim(block) {
13213
13438
  const placed = [];
@@ -13301,31 +13526,26 @@ function deriveBlockClassifierGeometry(input) {
13301
13526
  );
13302
13527
  }
13303
13528
  if (input.trackKind === "audio") return { trackKind: "audio" };
13304
- if (!isPositiveFinite(input.framerate)) {
13305
- return { trackKind: "video", mode: "all-protected", reason: "framerate-absent" };
13306
- }
13307
- const framerate = input.framerate;
13308
13529
  let keyframeInterval;
13309
13530
  if (isPositiveFinite(input.keyframeIntervalTicks) && isPositiveFinite(input.timescale)) {
13310
13531
  keyframeInterval = { ticks: input.keyframeIntervalTicks, timescale: input.timescale };
13311
13532
  } else if (isPositiveFinite(input.keyframeIntervalMs)) {
13312
13533
  keyframeInterval = { ticks: input.keyframeIntervalMs, timescale: 1e3 };
13313
- } else {
13314
- return { trackKind: "video", mode: "all-protected", reason: "keyframe-cadence-absent" };
13315
13534
  }
13535
+ const protect = (reason) => ({
13536
+ trackKind: "video",
13537
+ mode: "all-protected",
13538
+ reason,
13539
+ ...keyframeInterval === void 0 ? {} : { keyframeInterval }
13540
+ });
13541
+ if (!isPositiveFinite(input.framerate)) return protect("framerate-absent");
13542
+ const framerate = input.framerate;
13543
+ if (keyframeInterval === void 0) return protect("keyframe-cadence-absent");
13316
13544
  const gopFrames = exactInteger(keyframeInterval.ticks * framerate, keyframeInterval.timescale);
13317
- if (gopFrames === null) {
13318
- return {
13319
- trackKind: "video",
13320
- mode: "all-protected",
13321
- reason: "keyframe-interval-not-integral"
13322
- };
13323
- }
13545
+ if (gopFrames === null) return protect("keyframe-interval-not-integral");
13324
13546
  const frameDurationMs = 1e3 / framerate;
13325
13547
  const interleaveUnits = deriveFecInterleaveDepth(input.interleaveDepthMs, frameDurationMs);
13326
- if (interleaveUnits >= gopFrames) {
13327
- return { trackKind: "video", mode: "all-protected", reason: "block-spans-gop" };
13328
- }
13548
+ if (interleaveUnits >= gopFrames) return protect("block-spans-gop");
13329
13549
  return {
13330
13550
  trackKind: "video",
13331
13551
  mode: "classifying",
@@ -13336,7 +13556,7 @@ function deriveBlockClassifierGeometry(input) {
13336
13556
  };
13337
13557
  }
13338
13558
  function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
13339
- if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return null;
13559
+ if (geometry2.trackKind !== "video" || geometry2.keyframeInterval === void 0) return null;
13340
13560
  if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0) return null;
13341
13561
  const { ticks, timescale } = geometry2.keyframeInterval;
13342
13562
  if (!Number.isSafeInteger(ticks) || !Number.isSafeInteger(timescale)) return null;
@@ -13345,9 +13565,15 @@ function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
13345
13565
  if (scaled % divisor !== 0n) return null;
13346
13566
  return scaled / divisor;
13347
13567
  }
13568
+ function keyframeInstantBetween(start, interval, from, to) {
13569
+ const k = from >= start ? (from - start) / interval + 1n : 1n;
13570
+ return start + k * interval <= to;
13571
+ }
13348
13572
  function compareDataUnitStarts(a, b) {
13349
- return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset;
13573
+ return a.movieFragment - b.movieFragment | 0 || a.idx - b.idx || a.offset - b.offset;
13350
13574
  }
13575
+ var LATE_RAP_MAX_MPUS_BACK = 64;
13576
+ var UNPLACED = { rapNotMpuStart: false };
13351
13577
  var BlockClassifier = class {
13352
13578
  #geometry;
13353
13579
  #mode;
@@ -13370,8 +13596,24 @@ var BlockClassifier = class {
13370
13596
  #mpuSbnSpans = /* @__PURE__ */ new Map();
13371
13597
  #dataUnitStarts = /* @__PURE__ */ new Map();
13372
13598
  #highestMpu = null;
13373
- /** MPU → movie_fragment_sequence_number observed in it. */
13374
- #mpuFragments = /* @__PURE__ */ new Map();
13599
+ /**
13600
+ * P3 layout, kept for the MPUs within the classification horizon and valid
13601
+ * within one continuous SBN sequence (`noteSourceDiscontinuity`).
13602
+ */
13603
+ #mpus = /* @__PURE__ */ new Map();
13604
+ /** An MPU of this sequence showed two movie fragments: each frame is one. */
13605
+ #fragmentPerFrame = false;
13606
+ /** A DU header of this sequence stated sample_number above 1. */
13607
+ #multiSampleFragment = false;
13608
+ /**
13609
+ * The anchor received last, whether or not its MPU is still in the
13610
+ * horizon. Each new anchor, and the anchor of every DU header's MPU, is
13611
+ * checked against it.
13612
+ */
13613
+ #lastAnchor = null;
13614
+ /** Two anchors were exactly G fragments per MPU apart. */
13615
+ #fragmentsProven = false;
13616
+ /** The first RAP released of the latest MPU a RAP was released in, recorded in every mode. */
13375
13617
  #lastRap = null;
13376
13618
  constructor(geometry2) {
13377
13619
  this.#geometry = geometry2;
@@ -13401,7 +13643,7 @@ var BlockClassifier = class {
13401
13643
  this.#geometry = geometry2;
13402
13644
  this.#blocks.clear();
13403
13645
  this.#clearContiguityLedger();
13404
- this.#mpuFragments.clear();
13646
+ this.#clearMpuLayout();
13405
13647
  this.#lastRap = null;
13406
13648
  this.#mpuBoundsRaps = true;
13407
13649
  if (geometry2.trackKind === "video" && geometry2.mode === "all-protected") {
@@ -13435,11 +13677,14 @@ var BlockClassifier = class {
13435
13677
  /**
13436
13678
  * The stream's SBN sequence restarted (FECManager source discontinuity:
13437
13679
  * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
13438
- * order are comparable only within one continuous sequence, so the P1
13439
- * ledger starts again.
13680
+ * order are comparable only within one continuous sequence, and a
13681
+ * restarted publisher numbers MPUs and movie fragments again, so the P1
13682
+ * ledger and the P3 layout start again.
13440
13683
  */
13441
13684
  noteSourceDiscontinuity() {
13442
13685
  this.#clearContiguityLedger();
13686
+ this.#clearMpuLayout();
13687
+ this.#lastRap = null;
13443
13688
  }
13444
13689
  /** Register a block that exists without evidence (a vanished block). */
13445
13690
  touch(sbn) {
@@ -13458,16 +13703,16 @@ var BlockClassifier = class {
13458
13703
  if (this.#geometry.trackKind === "audio") return [];
13459
13704
  const changes = [];
13460
13705
  const block = this.#blockFor(sbn);
13706
+ const placement = this.#place(evidence);
13461
13707
  if (evidence.rap) block.rapSeen = true;
13462
13708
  if (evidence.mpu !== void 0) block.mpus.add(evidence.mpu);
13463
- if (evidence.idx !== void 0) {
13464
- block.idxMin = block.idxMin === void 0 ? evidence.idx : Math.min(block.idxMin, evidence.idx);
13465
- block.idxMax = block.idxMax === void 0 ? evidence.idx : Math.max(block.idxMax, evidence.idx);
13709
+ const { position } = placement;
13710
+ if (position !== void 0) {
13711
+ block.positionMin = block.positionMin === void 0 ? position : Math.min(block.positionMin, position);
13712
+ block.positionMax = block.positionMax === void 0 ? position : Math.max(block.positionMax, position);
13466
13713
  }
13467
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
13468
- this.#mpuBoundsRaps = false;
13469
- }
13470
- const violation = this.#checkInvariants(sbn, block, evidence);
13714
+ if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false;
13715
+ const violation = this.#checkInvariants(sbn, block, evidence, placement);
13471
13716
  if (violation !== null) changes.push(...this.#disable(violation));
13472
13717
  const next = this.#classify(block);
13473
13718
  if (next !== block.cls && this.#allowed(block.cls, next)) {
@@ -13492,18 +13737,35 @@ var BlockClassifier = class {
13492
13737
  * RAP-bearing block is the one a wrong G calls delta), because the next
13493
13738
  * released RAP then belongs to m+2. Every MPU is one interval long, so the
13494
13739
  * span to any later released RAP proves or refutes all MPUs in between.
13495
- */
13496
- noteReleasedRap(mpu, presentationTime, mediaTimescale) {
13497
- if (this.#geometry.trackKind === "audio" || this.#mode === "all-protected") {
13498
- return [];
13499
- }
13500
- const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13501
- if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
13740
+ *
13741
+ * In every mode it keeps each MPU's first released RAP, with its decode
13742
+ * time, as the start keyframeFreeBetween measures the catalog interval
13743
+ * from, and a second RAP released inside one MPU refutes `mpuBoundsRaps`
13744
+ * when it lies off the catalog lattice (not a whole number of intervals
13745
+ * after the first; draft-ramadan-moq-mmt-02 4.4.3 binds every keyframe to
13746
+ * it): with no repair, released RAPs are the only evidence of where they
13747
+ * lie. Without a usable interval, or a decode time on either, any second
13748
+ * RAP with another presentation time refutes.
13749
+ */
13750
+ noteReleasedRap(mpu, presentationTime, mediaTimescale, decodeTime) {
13751
+ if (this.#geometry.trackKind === "audio") return [];
13502
13752
  const previous = this.#lastRap;
13503
13753
  if (previous !== null && previous.mpu === mpu && previous.mediaTimescale === mediaTimescale) {
13754
+ if (presentationTime === previous.presentationTime) return [];
13755
+ const interval2 = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13756
+ if (interval2 === null || decodeTime === void 0 || previous.decodeTime === void 0 || (decodeTime - previous.decodeTime) % interval2 !== 0n) {
13757
+ this.#mpuBoundsRaps = false;
13758
+ }
13504
13759
  return [];
13505
13760
  }
13506
- this.#lastRap = { mpu, presentationTime, mediaTimescale };
13761
+ if (previous !== null && previous.mediaTimescale === mediaTimescale) {
13762
+ const back = previous.mpu - mpu >>> 0;
13763
+ if (back !== 0 && back <= LATE_RAP_MAX_MPUS_BACK && presentationTime < previous.presentationTime) return [];
13764
+ }
13765
+ this.#lastRap = { mpu, presentationTime, mediaTimescale, ...decodeTime === void 0 ? {} : { decodeTime } };
13766
+ if (this.#mode === "all-protected") return [];
13767
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13768
+ if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
13507
13769
  if (previous === null || mpu < previous.mpu || previous.mediaTimescale !== mediaTimescale) {
13508
13770
  return [];
13509
13771
  }
@@ -13512,6 +13774,22 @@ var BlockClassifier = class {
13512
13774
  }
13513
13775
  return this.#disable("rap-spacing-mismatch");
13514
13776
  }
13777
+ /**
13778
+ * Whether a gap inside MPU `mpu`, between the decode times `from` and `to`
13779
+ * of the frames on either side, holds no keyframe: MPU boundaries still
13780
+ * bound RAPs, the catalog states an interval exact in this timescale, and
13781
+ * none of its instants after the MPU's first released RAP lies in
13782
+ * `(from, to]` (fec-multicast-00 Block Classification item 3). Anything
13783
+ * unknown counts as a keyframe.
13784
+ */
13785
+ keyframeFreeBetween(mpu, from, to, mediaTimescale) {
13786
+ const rap = this.#lastRap;
13787
+ if (!this.#mpuBoundsRaps || rap?.mpu !== mpu || rap.mediaTimescale !== mediaTimescale || rap.decodeTime === void 0) {
13788
+ return false;
13789
+ }
13790
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13791
+ return interval !== null && !keyframeInstantBetween(rap.decodeTime, interval, from, to);
13792
+ }
13515
13793
  #blockFor(sbn) {
13516
13794
  let block = this.#blocks.get(sbn);
13517
13795
  if (!block) {
@@ -13520,35 +13798,89 @@ var BlockClassifier = class {
13520
13798
  }
13521
13799
  return block;
13522
13800
  }
13523
- #checkInvariants(sbn, block, evidence) {
13801
+ #checkInvariants(sbn, block, evidence, placement) {
13524
13802
  if (this.#mode === "all-protected" || this.#geometry.trackKind !== "video") return null;
13525
13803
  const geometry2 = this.#geometry;
13526
13804
  if (geometry2.mode !== "classifying") return null;
13527
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
13528
- return "rap-not-mpu-start";
13529
- }
13530
- if (evidence.idx !== void 0 && evidence.idx >= geometry2.gopFrames) {
13805
+ if (placement.rapNotMpuStart) return "rap-not-mpu-start";
13806
+ if (placement.position !== void 0 && placement.position >= geometry2.gopFrames) {
13531
13807
  return "mpu-longer-than-gop";
13532
13808
  }
13533
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0 && block.idxMax - block.idxMin >= geometry2.interleaveUnits) {
13809
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0 && block.positionMax - block.positionMin >= geometry2.interleaveUnits) {
13534
13810
  return "block-wider-than-interleave";
13535
13811
  }
13536
- if (evidence.mpu !== void 0 && evidence.movieFragment !== void 0) {
13537
- const fragment = this.#mpuFragments.get(evidence.mpu);
13538
- if (fragment === void 0) {
13539
- this.#mpuFragments.set(evidence.mpu, evidence.movieFragment);
13540
- for (const mpu of this.#mpuFragments.keys()) {
13541
- if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu);
13542
- }
13543
- } else if (fragment !== evidence.movieFragment) {
13544
- return "mpu-multiple-fragments";
13545
- }
13546
- }
13812
+ if (placement.violation !== void 0) return placement.violation;
13547
13813
  if (evidence.mpu !== void 0 && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
13548
13814
  return "block-not-contiguous";
13549
13815
  }
13550
13816
  return null;
13551
13817
  }
13818
+ /**
13819
+ * The MPU position a source symbol's DU header proves (P3), and what it
13820
+ * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.
13821
+ */
13822
+ #place(evidence) {
13823
+ const { mpu, idx, movieFragment: fragment } = evidence;
13824
+ if (idx === void 0) return UNPLACED;
13825
+ const bySample = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 };
13826
+ if (mpu === void 0 || fragment === void 0) {
13827
+ return this.#fragmentPerFrame && !this.#multiSampleFragment ? { rapNotMpuStart: bySample.rapNotMpuStart } : bySample;
13828
+ }
13829
+ let layout = this.#mpus.get(mpu);
13830
+ if (layout === void 0) {
13831
+ layout = { low: fragment };
13832
+ this.#mpus.set(mpu, layout);
13833
+ for (const other of this.#mpus.keys()) {
13834
+ if (other + 1 < mpu) this.#mpus.delete(other);
13835
+ }
13836
+ } else if (fragment !== layout.low) {
13837
+ this.#fragmentPerFrame = true;
13838
+ if ((fragment - layout.low | 0) < 0) layout.low = fragment;
13839
+ }
13840
+ if (idx !== 0) this.#multiSampleFragment = true;
13841
+ let arrival;
13842
+ if (evidence.rap && layout.anchor === void 0) {
13843
+ layout.anchor = fragment;
13844
+ arrival = this.#anchorDrift(mpu, fragment);
13845
+ if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true;
13846
+ this.#lastAnchor = { mpu, fragment };
13847
+ }
13848
+ if (!this.#fragmentPerFrame) return bySample;
13849
+ if (this.#multiSampleFragment) return { ...bySample, violation: "mpu-multiple-fragments" };
13850
+ const { anchor } = layout;
13851
+ if (anchor === void 0) return UNPLACED;
13852
+ const drift = arrival ?? this.#anchorDrift(mpu, anchor);
13853
+ const offset = fragment - anchor | 0;
13854
+ return {
13855
+ ...offset === 0 || offset > 0 && this.#fragmentsProven ? { position: offset } : {},
13856
+ rapNotMpuStart: evidence.rap && offset !== 0 || (layout.low - anchor | 0) < 0 || // Fragments count frames: an anchor arriving past the spacing is a
13857
+ // RAP inside its MPU, or an earlier MPU outran G.
13858
+ arrival !== void 0 && arrival > 0 && this.#fragmentsProven,
13859
+ ...drift === void 0 || drift === 0 ? {} : { violation: "rap-spacing-mismatch" }
13860
+ };
13861
+ }
13862
+ /**
13863
+ * How many fragments MPU m's anchor `fragment` lies past the start that
13864
+ * the anchor received last predicts for MPU m: one frame per fragment and
13865
+ * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')
13866
+ * fragments apart, modulo 2^32. Undefined without a last anchor, a
13867
+ * cadence, or this layout.
13868
+ */
13869
+ #anchorDrift(mpu, fragment) {
13870
+ const geometry2 = this.#geometry;
13871
+ const last = this.#lastAnchor;
13872
+ if (last === null || !this.#fragmentPerFrame || this.#multiSampleFragment || geometry2.trackKind !== "video" || geometry2.mode !== "classifying") {
13873
+ return void 0;
13874
+ }
13875
+ return fragment - last.fragment - geometry2.gopFrames * (mpu - last.mpu) | 0;
13876
+ }
13877
+ #clearMpuLayout() {
13878
+ this.#mpus.clear();
13879
+ this.#fragmentPerFrame = false;
13880
+ this.#multiSampleFragment = false;
13881
+ this.#lastAnchor = null;
13882
+ this.#fragmentsProven = false;
13883
+ }
13552
13884
  #clearContiguityLedger() {
13553
13885
  this.#mpuSbnSpans.clear();
13554
13886
  this.#dataUnitStarts.clear();
@@ -13648,9 +13980,9 @@ var BlockClassifier = class {
13648
13980
  if (this.#mode === "all-protected") return "unknown";
13649
13981
  const geometry2 = this.#geometry;
13650
13982
  if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return "unknown";
13651
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0) {
13983
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0) {
13652
13984
  const span = geometry2.interleaveUnits - 1;
13653
- if (block.idxMax - span >= 1 && block.idxMin + span <= geometry2.gopFrames - 1) {
13985
+ if (block.positionMax - span >= 1 && block.positionMin + span <= geometry2.gopFrames - 1) {
13654
13986
  return "delta";
13655
13987
  }
13656
13988
  }
@@ -13827,6 +14159,7 @@ var WORKER_ERROR_LOG_CAP = 5;
13827
14159
  var WORKER_ERROR_KIND_CAP = 32;
13828
14160
  var WORKER_ERROR_OVERFLOW_KIND = "other";
13829
14161
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
14162
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
13830
14163
  function isMulticastSymbolDelivery(value) {
13831
14164
  return value === "datagram" || value === "ordered-relay";
13832
14165
  }
@@ -13920,10 +14253,18 @@ var FECManager = class _FECManager {
13920
14253
  // 'pending' forever, which would park every later frame of its stream in
13921
14254
  // the in-order release gate. Each entry owns its handle; the callback
13922
14255
  // checks it still owns the key, so a settled or reset key is never touched.
14256
+ /**
14257
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
14258
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
14259
+ */
13923
14260
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
13924
14261
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
13925
14262
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
13926
14263
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
14264
+ // Source ESIs per block that another FEC instance rebuilt and fed in
14265
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
14266
+ // not network arrivals and never make a block clean.
14267
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
13927
14268
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
13928
14269
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
13929
14270
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -13932,10 +14273,14 @@ var FECManager = class _FECManager {
13932
14273
  // SSB_length source arrivals and recoverable from SSB_length received
13933
14274
  // symbols; waiting for K fails every one of them.
13934
14275
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
14276
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
14277
+ // a repair states the block there or the span resolves.
14278
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
13935
14279
  this.#ssbLengthConflictCount = 0;
13936
14280
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
13937
14281
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
13938
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
14282
+ // symbols its repair group carries; 0 for a repair-less span no repair can
14283
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
13939
14284
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
13940
14285
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
13941
14286
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -14052,6 +14397,10 @@ var FECManager = class _FECManager {
14052
14397
  // ── Keyframe-protected repair policy (block-policy.ts) ──
14053
14398
  // One classifier per physical stream, built from that stream's geometry.
14054
14399
  this.#classifiers = /* @__PURE__ */ new Map();
14400
+ // A stream without catalog timing has no classifier, so the last RAP it
14401
+ // released stands in for one: "an MPU boundary bounds its RAPs" holds until
14402
+ // a second RAP is released inside one MPU (BLO-52085).
14403
+ this.#noSpanRaps = /* @__PURE__ */ new Map();
14055
14404
  // Geometry a stream-scoped configuration gave one stream (streamKey). ABR
14056
14405
  // rungs can share a packetId with a different framerate or GOP, so the
14057
14406
  // packet-level geometry is only the geometry of a packet whose streams
@@ -14084,6 +14433,14 @@ var FECManager = class _FECManager {
14084
14433
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
14085
14434
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
14086
14435
  this.#isoLocators = /* @__PURE__ */ new Map();
14436
+ // The ts of the run behind the gap the release gate last asked about, per
14437
+ // stream (isoRepairlessWaitMs), keyed on the frame before the gap: kept, as
14438
+ // the source it came from may retire before the run's deadline, and the
14439
+ // earliest found wins, so a late frame that becomes the head restarts
14440
+ // nothing. It stays until the next run gap: a source discontinuity drops
14441
+ // it, and one older than twice the hold ceiling is not this gap's.
14442
+ // `counted` once the deadline passed (onUndelimitedRunGap).
14443
+ this.#runAnchors = /* @__PURE__ */ new Map();
14087
14444
  this.#deferIsoGaps = false;
14088
14445
  this.#isoRepairRefusedCount = 0;
14089
14446
  this.#isoSourceOversizeCount = 0;
@@ -14119,13 +14476,17 @@ var FECManager = class _FECManager {
14119
14476
  this.#workerErrorCounts = /* @__PURE__ */ new Map();
14120
14477
  this.#decoderUnavailableEvents = 0;
14121
14478
  this.#repairSymbolSizeMismatchCount = 0;
14479
+ this.#unlistedRepairTrackRefusals = 0;
14122
14480
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
14123
14481
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
14124
14482
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
14125
14483
  // arrives via onBlockRecovered callback.
14126
14484
  this.onBlockStarted = null;
14127
14485
  this.onBlockComplete = null;
14128
- /** A block reached its fail bound. `blockClass` is its class at failure. */
14486
+ /**
14487
+ * A block reached its fail bound. `blockClass` is its class at failure.
14488
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
14489
+ */
14129
14490
  this.onBlockFailed = null;
14130
14491
  /**
14131
14492
  * Fired once per stream when its Worker decoder stops being routable.
@@ -14167,12 +14528,26 @@ var FECManager = class _FECManager {
14167
14528
  * for it, which it must be.
14168
14529
  */
14169
14530
  this.#onUndelimitedLoss = null;
14531
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
14532
+ this.#onIsoHoleExpired = null;
14170
14533
  /** A block every symbol of which vanished was created by SBN evidence. */
14171
14534
  this.onBlockVanished = null;
14172
14535
  /** A block reached a terminal state (completed, recovered, or failed). */
14173
14536
  this.onBlockResolved = null;
14174
14537
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
14175
14538
  this.onSourceDiscontinuity = null;
14539
+ /** The FEC deadline of a run no repair delimited passed, releasing the gap behind it (once per gap). */
14540
+ this.onUndelimitedRunGap = null;
14541
+ /**
14542
+ * The span and tolerance the catalog states for a keyframe overlay
14543
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
14544
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
14545
+ * undefined while none is installed. A stated block only a late source
14546
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
14547
+ * late source can fill, also wait for that overlay's repair
14548
+ * (#overlayLateWaitMs).
14549
+ */
14550
+ this.keyframeOverlayTiming = null;
14176
14551
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
14177
14552
  /**
14178
14553
  * A recovered source symbol. Return false when admission refused the
@@ -14209,7 +14584,9 @@ var FECManager = class _FECManager {
14209
14584
  #pendingWorkerCleanupBounds;
14210
14585
  #blockSourceCounts;
14211
14586
  #blockSourceEsis;
14587
+ #blockRebuiltEsis;
14212
14588
  #blockAuthoredLengths;
14589
+ #isoSpanKeys;
14213
14590
  #ssbLengthConflictCount;
14214
14591
  #blockRepairRsIds;
14215
14592
  #blockRsbLengths;
@@ -14251,6 +14628,7 @@ var FECManager = class _FECManager {
14251
14628
  #orderedFrontiers;
14252
14629
  #orderedPendingBlocks;
14253
14630
  #classifiers;
14631
+ #noSpanRaps;
14254
14632
  #streamGeometries;
14255
14633
  #failedBlocks;
14256
14634
  #resolvedBlockClasses;
@@ -14260,6 +14638,7 @@ var FECManager = class _FECManager {
14260
14638
  #highestSbn;
14261
14639
  #sourceFrontiers;
14262
14640
  #isoLocators;
14641
+ #runAnchors;
14263
14642
  #deferIsoGaps;
14264
14643
  #isoRepairRefusedCount;
14265
14644
  #isoSourceOversizeCount;
@@ -14274,7 +14653,9 @@ var FECManager = class _FECManager {
14274
14653
  #workerErrorCounts;
14275
14654
  #decoderUnavailableEvents;
14276
14655
  #repairSymbolSizeMismatchCount;
14656
+ #unlistedRepairTrackRefusals;
14277
14657
  #onUndelimitedLoss;
14658
+ #onIsoHoleExpired;
14278
14659
  #encodeTrackName(catalogTrackName) {
14279
14660
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
14280
14661
  if (encoded === void 0) {
@@ -14746,7 +15127,10 @@ var FECManager = class _FECManager {
14746
15127
  timer.handle = null;
14747
15128
  this.#requestRepair(sbn, packetId, catalogTrackName);
14748
15129
  };
14749
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
15130
+ timer.handle = setTimeout(
15131
+ onFire,
15132
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
15133
+ );
14750
15134
  this.#repairDeadlines.set(key, timer);
14751
15135
  }
14752
15136
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -14890,8 +15274,14 @@ var FECManager = class _FECManager {
14890
15274
  * Vanished blocks are not enumerated here: their starts are unknown until a
14891
15275
  * repair states them. The SS_IDs between two stated blocks become one
14892
15276
  * repair-less span when the later block's repair arrives (placeIsoRepair).
15277
+ *
15278
+ * A `held` source arrived before its block was known and is fed only now
15279
+ * that a repair, a span or a closed hole placed it: how far its block start
15280
+ * then lies behind the frontier measures how long the receiver held it, not
15281
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
15282
+ * it (BLO-52085).
14893
15283
  */
14894
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
15284
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
14895
15285
  const streamKey = this.#streamKey(packetId, catalogTrackName);
14896
15286
  const now = performance.now();
14897
15287
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -14912,6 +15302,8 @@ var FECManager = class _FECManager {
14912
15302
  };
14913
15303
  const discontinuity = () => {
14914
15304
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
15305
+ this.#noSpanRaps.delete(streamKey);
15306
+ this.#runAnchors.delete(streamKey);
14915
15307
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
14916
15308
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
14917
15309
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -14929,7 +15321,7 @@ var FECManager = class _FECManager {
14929
15321
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
14930
15322
  };
14931
15323
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
14932
- 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))) {
15324
+ 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))) {
14933
15325
  discontinuity();
14934
15326
  return;
14935
15327
  }
@@ -15191,17 +15583,21 @@ var FECManager = class _FECManager {
15191
15583
  this.#blockWaitDeadlinesMs.delete(key);
15192
15584
  this.#repairHoldUntilMs.delete(key);
15193
15585
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
15194
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
15586
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
15195
15587
  };
15196
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
15588
+ timer.handle = setTimeout(
15589
+ onFire,
15590
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
15591
+ );
15197
15592
  this.#activeBlocks.set(key, timer);
15198
15593
  this.#indexBlockKey(key, sbn, packetId);
15199
15594
  }
15200
15595
  /**
15201
15596
  * Hand a block whose delivery is over to its decoder for finalization: the
15202
- * datagram deadline fired, or the ordered relay moved past it.
15597
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
15598
+ * is when it was due: its deadline, or now.
15203
15599
  */
15204
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
15600
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
15205
15601
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
15206
15602
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
15207
15603
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -15217,7 +15613,7 @@ var FECManager = class _FECManager {
15217
15613
  if (workerClient) {
15218
15614
  this.#pendingWorkerCleanups.add(key);
15219
15615
  this.#pendingWorkerCleanupClients.set(key, workerClient);
15220
- this.#boundOwedCleanup(key, packetId, workerClient);
15616
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
15221
15617
  workerClient.cleanup(sbn);
15222
15618
  } else {
15223
15619
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -15324,6 +15720,9 @@ var FECManager = class _FECManager {
15324
15720
  }
15325
15721
  if (policyChanged) {
15326
15722
  this.#bumpEpoch(packetId);
15723
+ for (const key of [...this.#noSpanRaps.keys()]) {
15724
+ if (this.#belongsToPacket(key, packetId)) this.#noSpanRaps.delete(key);
15725
+ }
15327
15726
  for (const [key, classifier] of [...this.#classifiers]) {
15328
15727
  if (!this.#belongsToPacket(key, packetId)) continue;
15329
15728
  const stream = this.#parseStreamKey(key);
@@ -15424,6 +15823,7 @@ var FECManager = class _FECManager {
15424
15823
  packetId
15425
15824
  })),
15426
15825
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
15826
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
15427
15827
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
15428
15828
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
15429
15829
  };
@@ -15526,7 +15926,9 @@ var FECManager = class _FECManager {
15526
15926
  }
15527
15927
  resetMap(this.#blockSourceCounts);
15528
15928
  resetMap(this.#blockSourceEsis);
15929
+ resetMap(this.#blockRebuiltEsis);
15529
15930
  resetMap(this.#blockAuthoredLengths);
15931
+ resetSet(this.#isoSpanKeys);
15530
15932
  resetMap(this.#blockRepairRsIds);
15531
15933
  resetMap(this.#blockRsbLengths);
15532
15934
  resetMap(this.#heldLayerStates);
@@ -15557,8 +15959,10 @@ var FECManager = class _FECManager {
15557
15959
  resetMap(this.#highestSbn);
15558
15960
  resetMap(this.#sourceFrontiers);
15559
15961
  resetMap(this.#isoLocators);
15962
+ resetMap(this.#runAnchors);
15560
15963
  resetMap(this.#sourceAnchors);
15561
15964
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
15965
+ this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
15562
15966
  this.#bumpEpoch(packetId);
15563
15967
  for (const [sbn, keys] of this.#blockKeysBySbn) {
15564
15968
  for (const key of keys.keys()) {
@@ -15649,7 +16053,9 @@ var FECManager = class _FECManager {
15649
16053
  dropMap(this.#pendingWorkerCleanupClients);
15650
16054
  dropMap(this.#blockSourceCounts);
15651
16055
  dropMap(this.#blockSourceEsis);
16056
+ dropMap(this.#blockRebuiltEsis);
15652
16057
  dropMap(this.#blockAuthoredLengths);
16058
+ dropSet(this.#isoSpanKeys);
15653
16059
  dropMap(this.#blockRepairRsIds);
15654
16060
  dropMap(this.#blockRsbLengths);
15655
16061
  dropMap(this.#blockPathCounts);
@@ -15663,8 +16069,10 @@ var FECManager = class _FECManager {
15663
16069
  dropMap(this.#highestSbn);
15664
16070
  dropMap(this.#sourceFrontiers);
15665
16071
  dropMap(this.#isoLocators);
16072
+ dropMap(this.#runAnchors);
15666
16073
  dropMap(this.#sourceAnchors);
15667
16074
  dropMap(this.#classifiers);
16075
+ dropMap(this.#noSpanRaps);
15668
16076
  dropMap(this.#streamGeometries);
15669
16077
  dropSet(this.#pendingWorkerCleanups);
15670
16078
  dropSet(this.#completedBlocks);
@@ -15810,6 +16218,9 @@ var FECManager = class _FECManager {
15810
16218
  this.#unindexBlockKey(key);
15811
16219
  }
15812
16220
  }
16221
+ if (isSourceSymbol && source === "multicast") {
16222
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
16223
+ }
15813
16224
  return true;
15814
16225
  }
15815
16226
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -15919,8 +16330,10 @@ var FECManager = class _FECManager {
15919
16330
  }
15920
16331
  /**
15921
16332
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
15922
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
15923
- * Undefined for a block that is not open.
16333
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
16334
+ * repair-less span states its length, and RSB_length 0 when it is longer
16335
+ * than K, since no repair can reach it). Undefined for a block that is not
16336
+ * open.
15924
16337
  */
15925
16338
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
15926
16339
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -15988,8 +16401,9 @@ var FECManager = class _FECManager {
15988
16401
  return true;
15989
16402
  }
15990
16403
  /**
15991
- * Drop a block's repair hold: its FETCH ended without delivering. The block
15992
- * falls back to its multicast wait, which may already have passed.
16404
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
16405
+ * back only a repair that cannot complete it. The block falls back to its
16406
+ * multicast wait, which may already have passed.
15993
16407
  */
15994
16408
  releaseRepairHold(sbn, packetId, catalogTrackName) {
15995
16409
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16035,7 +16449,7 @@ var FECManager = class _FECManager {
16035
16449
  }
16036
16450
  const trackConfig = this.#trackConfigs.get(packetId);
16037
16451
  if (trackConfig === void 0) return void 0;
16038
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
16452
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
16039
16453
  }
16040
16454
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
16041
16455
  // -----------------------------------------------------------------------
@@ -16077,6 +16491,9 @@ var FECManager = class _FECManager {
16077
16491
  for (const key of [...this.#isoLocators.keys()]) {
16078
16492
  if (this.#belongsToPacket(key, packetId)) this.#isoLocators.delete(key);
16079
16493
  }
16494
+ for (const key of [...this.#runAnchors.keys()]) {
16495
+ if (this.#belongsToPacket(key, packetId)) this.#runAnchors.delete(key);
16496
+ }
16080
16497
  }
16081
16498
  /**
16082
16499
  * The iso-ssbg1-v1 locator horizon in blocks: every block the manager can
@@ -16126,7 +16543,9 @@ var FECManager = class _FECManager {
16126
16543
  holdIsoSource(packetId, catalogTrackName, ssId, source) {
16127
16544
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16128
16545
  const evictedBefore = locator.heldEvicted;
16129
- const held = locator.hold(ssId, source);
16546
+ const held = locator.hold(ssId, source.arrivedAtMs === void 0 ? { ...source, arrivedAtMs: this.#receiptNow() } : source);
16547
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16548
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16130
16549
  const evicted = locator.heldEvicted - evictedBefore;
16131
16550
  if (evicted > 0) {
16132
16551
  const before = this.#isoHeldEvictedCount;
@@ -16147,17 +16566,20 @@ var FECManager = class _FECManager {
16147
16566
  * contradicts a known block is refused (counted) and must be dropped.
16148
16567
  */
16149
16568
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
16150
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
16569
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16570
+ const placement = locator.placeRepair(ssStart, ssbLength);
16571
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16151
16572
  if (placement.status !== "placed") {
16152
16573
  this.#isoRepairRefusedCount++;
16153
16574
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
16154
16575
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
16155
16576
  }
16577
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
16156
16578
  return placement;
16157
16579
  }
16580
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
16158
16581
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
16159
16582
  if (placement.hole !== void 0) {
16160
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
16161
16583
  const hole = placement.hole.block;
16162
16584
  const previous = locator.blockEndingAt(hole.start);
16163
16585
  const loss = {
@@ -16178,17 +16600,29 @@ var FECManager = class _FECManager {
16178
16600
  * `handler`, instead of a repair-less span; null restores spans. Set by the
16179
16601
  * range repair scheduler; applies to every stream from its next gap. The
16180
16602
  * handler and the deferral are one setting, so no hole is ever created with
16181
- * nobody to close it.
16603
+ * nobody to close it. `onExpired` is told of each pending hole the stream
16604
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
16605
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
16606
+ * reported; otherwise the hole is discarded with its sources.
16182
16607
  */
16183
- setUndelimitedLossHandler(handler) {
16608
+ setUndelimitedLossHandler(handler, onExpired = null) {
16184
16609
  this.#onUndelimitedLoss = handler;
16610
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
16185
16611
  this.#deferIsoGaps = handler !== null;
16186
16612
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
16187
16613
  }
16614
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
16615
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
16616
+ for (const hole of locator.takeExpiredHoles()) {
16617
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
16618
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
16619
+ }
16620
+ }
16188
16621
  /**
16189
- * The range repair for a hole ended: every hole still pending inside
16190
- * `[start, start + length)` becomes a repair-less span. Returns those spans
16191
- * with the held sources they placed, for the caller to feed (MmtpRouter).
16622
+ * The range repair for a hole ended: every hole inside `[start, start +
16623
+ * length)`, pending or expired, becomes a repair-less span. Returns those
16624
+ * spans with the held sources they placed, for the caller to feed
16625
+ * (MmtpRouter).
16192
16626
  */
16193
16627
  closeIsoHoles(packetId, catalogTrackName, start, length) {
16194
16628
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -16204,17 +16638,37 @@ var FECManager = class _FECManager {
16204
16638
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
16205
16639
  * SS_ID of which vanished resolves through its deadline like any vanished
16206
16640
  * block.
16641
+ *
16642
+ * A span longer than K holds more than one block (SSB_length <= K), and the
16643
+ * locator states no block inside a span, only one exactly its range
16644
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
16645
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
16646
+ * Group of it (group-cannot-complete). Every span still keeps its whole
16647
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
16648
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
16649
+ * gate lets those frames go once only a late source can fill the gap
16650
+ * before them, as long after they arrived as the gap's decision allows
16651
+ * (isoRepairlessWaitMs).
16207
16652
  */
16208
16653
  #openIsoSpan(span, packetId, catalogTrackName) {
16209
16654
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
16210
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
16655
+ if (!this.#blockAuthoredLengths.has(key)) {
16656
+ this.#blockAuthoredLengths.set(key, span.block.length);
16657
+ this.#isoSpanKeys.add(key);
16658
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
16659
+ }
16211
16660
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
16212
16661
  }
16213
16662
  /**
16214
16663
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
16215
16664
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
16216
16665
  * that could hold them is pending or not yet stated by a repair, else the
16217
- * starts of the blocks that failed or vanished.
16666
+ * starts of the blocks that failed or vanished. SS_IDs no repair has
16667
+ * delimited yet that all arrived lost nothing and wait for no repair, only
16668
+ * the late-source allowance after the multicast datagram that clocks them
16669
+ * arrived (#lossFreeRunReadyAtMs), and not even that when none of them came
16670
+ * as one; one missing makes a run that waits as one block
16671
+ * (isoRepairlessWaitMs).
16218
16672
  *
16219
16673
  * `untracked` reads as the release gate reads it (MmtpRouter
16220
16674
  * #createFecReleaseGate): a block holding either released frame's SS_ID
@@ -16227,7 +16681,16 @@ var FECManager = class _FECManager {
16227
16681
  isoSpanResolution(packetId, catalogTrackName, fromSsId, toSsId) {
16228
16682
  if (!serial32Precedes(fromSsId, toSsId) || serial32Distance(fromSsId, toSsId) <= 1) return [];
16229
16683
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
16230
- if (!locator || !locator.coversBetween(fromSsId, toSsId)) return null;
16684
+ if (!locator) return null;
16685
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
16686
+ if (run?.missing !== void 0) return null;
16687
+ if (run !== null) {
16688
+ const config = this.#trackConfigs.get(packetId);
16689
+ const readyAtMs = config === void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
16690
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) return null;
16691
+ }
16692
+ if (locator.coverageEnd === void 0) return [];
16693
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return null;
16231
16694
  const highest = this.highestSbn(packetId, catalogTrackName);
16232
16695
  const lost = [];
16233
16696
  for (const block of locator.blocksBetween(fromSsId, toSsId)) {
@@ -16245,6 +16708,148 @@ var FECManager = class _FECManager {
16245
16708
  }
16246
16709
  return lost;
16247
16710
  }
16711
+ /**
16712
+ * When undelimited SS_IDs from `runStart` up to `toSsId` that all arrived
16713
+ * stop holding its frame: the late-source allowance after a multicast
16714
+ * datagram receipt. Until then a frame between them may still complete
16715
+ * from a packet with no SS_ID (an untagged FT=0/FT=1 reordered behind the
16716
+ * next frame), and a repair may delimit them. The receipt is `toSsId`'s
16717
+ * own when it is held from a multicast datagram. Otherwise (its packet
16718
+ * came only as an overlap copy or from a MoQ stream, or was evicted or
16719
+ * retired) it is the newest among those SS_IDs, every one of which is
16720
+ * held and states its path. So the time moves at most once, when the
16721
+ * head's own multicast copy arrives while its frame waits or its held
16722
+ * source is dropped, and never on a later ask.
16723
+ *
16724
+ * Undefined, so the range releases at once, when no SS_ID of it came as a
16725
+ * multicast datagram: a MoQ arrival, an ordered relay's and the frame's
16726
+ * own are no clock for multicast reordering (#lossyReceiptMs). Undefined
16727
+ * too on a track with no catalog span, which states no allowance: the
16728
+ * local timeout is a cleanup bound, and isoRepairlessWaitMs arms no wake
16729
+ * there, so a wait would hold the frame until the next packet. The cost,
16730
+ * on multicast too: an untagged FT=0/FT=1 reordered behind the next frame
16731
+ * of such a track is dropped stale.
16732
+ */
16733
+ #lossFreeRunReadyAtMs(config, locator, runStart, toSsId) {
16734
+ if (!_FECManager.#hasCatalogTiming(config)) return void 0;
16735
+ let clockMs = this.#lossyReceiptMs(locator.heldSource(toSsId));
16736
+ if (clockMs === void 0) {
16737
+ for (let ssId = runStart; ssId !== toSsId; ssId = ssId + 1 >>> 0) {
16738
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
16739
+ if (atMs !== void 0 && (clockMs === void 0 || atMs > clockMs)) clockMs = atMs;
16740
+ }
16741
+ }
16742
+ if (clockMs === void 0) return void 0;
16743
+ return clockMs + Math.max(0, this.#multicastWaitMs(config) - config.interleaveDepthMs);
16744
+ }
16745
+ /**
16746
+ * Receipt time of a held source that came as a multicast datagram, the
16747
+ * one path that loses and reorders packets, else undefined: a MoQ stream
16748
+ * and an ordered relay deliver in order, so their arrivals clock no
16749
+ * reorder allowance and no FEC deadline. The path is the one the feed
16750
+ * stated (IsoHeldSource.source, MulticastSymbolDelivery), never a guess.
16751
+ */
16752
+ #lossyReceiptMs(held) {
16753
+ return held?.source === "multicast" && this.#multicastSymbolDelivery === "datagram" ? held.arrivedAtMs : void 0;
16754
+ }
16755
+ /**
16756
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
16757
+ * between two released frames' SS_IDs once only a late source can still
16758
+ * fill them, else undefined. That is when every one missing (neither
16759
+ * arrived nor held) lies in a repair-less span longer than K, which no
16760
+ * repair can state a block of (#openIsoSpan), or in a stated block its
16761
+ * own repair group cannot complete every SS_ID of which it misses lies
16762
+ * between them (so the gap's decision covers all it lost), and a multicast
16763
+ * source at or past `toSsId` arrived, so each is lost or reordered behind
16764
+ * it (a MoQ source shows nothing: MoQ streams overtake one another). The
16765
+ * span or block itself keeps its own wait.
16766
+ *
16767
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
16768
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
16769
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
16770
+ * Then the frame waits as a stated block its group cannot complete does
16771
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
16772
+ * overlay's span plus the larger of the allowance and its tolerance, or,
16773
+ * for an overlay that states no span, the span's whole wait (undefined).
16774
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
16775
+ * the gap holds a stated block's loss.
16776
+ *
16777
+ * A run of SS_IDs no repair has delimited yet, one of which never arrived,
16778
+ * is one block of its own instead (draft-ramadan-moq-fec-multicast-00,
16779
+ * Receiver Repair Policy): on datagram delivery the frame then waits for
16780
+ * that block's FEC deadline, whatever the flags: ts plus the whole
16781
+ * multicast wait (fec-core-00 9.3), ts the arrival of the lowest held
16782
+ * multicast source above the run, up to the newest (fec-multicast-00,
16783
+ * Deadline Anchoring; under reordering at or after the draft's first
16784
+ * signal, never before). The wait returned counts from `arrivedAtMs`, the
16785
+ * frame's arrival; without it, it is the whole wait. With no such source
16786
+ * held (never arrived, retired, or evicted) the frame keeps the hold
16787
+ * ceiling: a MoQ arrival is no clock for a multicast deadline.
16788
+ */
16789
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false, arrivedAtMs) {
16790
+ const config = this.#trackConfigs.get(packetId);
16791
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
16792
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
16793
+ const locator = this.#isoLocators.get(streamKey);
16794
+ if (locator === void 0) return void 0;
16795
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
16796
+ const readyAtMs = run === null || run.missing !== void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
16797
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) {
16798
+ return Math.max(0, readyAtMs - (arrivedAtMs ?? this.#receiptNow()));
16799
+ }
16800
+ const newestSource = locator.newestSource;
16801
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
16802
+ if (run?.missing !== void 0) {
16803
+ if (this.#multicastSymbolDelivery === "ordered-relay" || this.isoSpanResolution(packetId, catalogTrackName, fromSsId, run.start) === null) {
16804
+ return void 0;
16805
+ }
16806
+ const kept = this.#runAnchors.get(streamKey);
16807
+ const anchor = kept?.fromSsId === fromSsId && this.#receiptNow() - kept.tsMs <= 2 * (config.interleaveDepthMs + 2 * this.#blockLifetimeMs(config)) ? kept : void 0;
16808
+ let tsMs = anchor?.tsMs;
16809
+ for (let ssId = run.missing + 1 >>> 0; !serial32Precedes(newestSource, ssId); ssId = ssId + 1 >>> 0) {
16810
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
16811
+ if (atMs === void 0) continue;
16812
+ if (tsMs === void 0 || atMs < tsMs) tsMs = atMs;
16813
+ break;
16814
+ }
16815
+ if (tsMs === void 0) return void 0;
16816
+ const waitMs2 = this.#multicastWaitMs(config);
16817
+ let counted = anchor?.counted === true;
16818
+ if (!counted && tsMs + waitMs2 <= this.#receiptNow()) {
16819
+ counted = true;
16820
+ this.onUndelimitedRunGap?.(packetId, catalogTrackName);
16821
+ }
16822
+ this.#runAnchors.set(streamKey, { fromSsId, tsMs, counted });
16823
+ return arrivedAtMs === void 0 ? waitMs2 : Math.max(0, tsMs + waitMs2 - arrivedAtMs);
16824
+ }
16825
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return void 0;
16826
+ let repairless = false;
16827
+ let stated = false;
16828
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
16829
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
16830
+ if (this.#completedBlocks.has(key)) continue;
16831
+ if (block.span && block.length > locator.kMax) {
16832
+ repairless = true;
16833
+ continue;
16834
+ }
16835
+ const received = this.#blockSourceEsis.get(key);
16836
+ const rebuilt = this.#blockRebuiltEsis.get(key);
16837
+ let missesInGap = false;
16838
+ let missesOutside = false;
16839
+ for (let esi = 0; esi < block.length; esi++) {
16840
+ const ssId = serial32Add(block.start, esi);
16841
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
16842
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
16843
+ else if (!rebuilt?.has(esi)) missesOutside = true;
16844
+ }
16845
+ if (!missesInGap) continue;
16846
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
16847
+ repairless = stated = true;
16848
+ }
16849
+ if (!repairless) return void 0;
16850
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
16851
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
16852
+ }
16248
16853
  /**
16249
16854
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
16250
16855
  * the sources held now for a block no repair has stated yet, and the held
@@ -16295,11 +16900,34 @@ var FECManager = class _FECManager {
16295
16900
  /**
16296
16901
  * Whether an MPU boundary still bounds this stream's RAPs (see
16297
16902
  * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
16298
- * it does not. A stream with no classifier yet has shown nothing against it.
16299
- */
16300
- mpuBoundsRapsFor(packetId, catalogTrackName) {
16301
- if (!this.#hasCatalogTimingForPacket(packetId)) return false;
16302
- return this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.mpuBoundsRaps ?? true;
16903
+ * it does not. A stream with no classifier yet has shown nothing against it,
16904
+ * and neither has a stream without catalog timing until it releases two
16905
+ * RAPs inside one MPU.
16906
+ *
16907
+ * With catalog timing and a `gap` inside one MPU, between the authored
16908
+ * timing of the frames on either side, it also takes the catalog keyframe
16909
+ * interval to rule a keyframe out of the gap
16910
+ * (`BlockClassifier.keyframeFreeBetween`, fec-multicast-00 Block
16911
+ * Classification item 3), and no source held between the frames' SS_IDs
16912
+ * may carry the RAP flag or another MPU's number (item 1 read on the held
16913
+ * packets: a RAP the loss cut in two is never released, so the frames
16914
+ * alone cannot show it); anything unknown counts as a keyframe.
16915
+ */
16916
+ mpuBoundsRapsFor(packetId, catalogTrackName, gap) {
16917
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
16918
+ if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
16919
+ const classifier = this.#classifiers.get(streamKey);
16920
+ if (gap === void 0) return classifier?.mpuBoundsRaps ?? true;
16921
+ const { mpu, from, to, fromSsId, toSsId } = gap;
16922
+ if (fromSsId !== void 0 && toSsId !== void 0) {
16923
+ const run = this.#isoLocators.get(streamKey)?.undelimitedBetween(
16924
+ fromSsId,
16925
+ toSsId,
16926
+ ({ evidence }) => evidence.rap || evidence.mpu !== void 0 && evidence.mpu !== mpu
16927
+ );
16928
+ if (run?.flagged) return false;
16929
+ }
16930
+ return classifier !== void 0 && from !== void 0 && to !== void 0 && from.mediaTimescale === to.mediaTimescale && classifier.keyframeFreeBetween(mpu, from.decodeTime, to.decodeTime, from.mediaTimescale);
16303
16931
  }
16304
16932
  /** A block's class now, or frozen at its resolution. */
16305
16933
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -16322,17 +16950,27 @@ var FECManager = class _FECManager {
16322
16950
  }
16323
16951
  /**
16324
16952
  * Record a RAP frame released in order, for the classifier's RAP-spacing
16325
- * invariant (consecutive MPUs exactly one keyframe interval apart).
16953
+ * invariant (consecutive MPUs exactly one keyframe interval apart) and,
16954
+ * with its decode time, as the MPU start gap decisions measure the catalog
16955
+ * keyframe interval from (mpuBoundsRapsFor).
16326
16956
  */
16327
- noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
16328
- if (!this.#trackConfigs.has(packetId) || !this.#hasCatalogTimingForPacket(packetId)) return;
16957
+ noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale, decodeTime) {
16958
+ if (!this.#trackConfigs.has(packetId)) return;
16959
+ if (!this.#hasCatalogTimingForPacket(packetId)) {
16960
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
16961
+ const last = this.#noSpanRaps.get(streamKey);
16962
+ const inside = last?.inside === true || last?.mpu === mpu && last.presentationTime !== presentationTime;
16963
+ this.#noSpanRaps.set(streamKey, { mpu, presentationTime, inside });
16964
+ return;
16965
+ }
16329
16966
  this.#applyClassifierChanges(
16330
16967
  packetId,
16331
16968
  catalogTrackName,
16332
16969
  this.#classifierFor(packetId, catalogTrackName).noteReleasedRap(
16333
16970
  mpu,
16334
16971
  presentationTime,
16335
- mediaTimescale
16972
+ mediaTimescale,
16973
+ decodeTime
16336
16974
  )
16337
16975
  );
16338
16976
  }
@@ -16538,11 +17176,14 @@ var FECManager = class _FECManager {
16538
17176
  });
16539
17177
  client.onCleanupComplete((sbn) => {
16540
17178
  if (this.#releasedWorkerClients.has(client)) return;
16541
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
17179
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
17180
+ const cleanupKeys = owed.filter((key) => {
16542
17181
  const block = this.#parseBlockKey(key);
16543
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
17182
+ return block.packetId === packetId && block.sbn === sbn;
16544
17183
  });
16545
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
17184
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
17185
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
17186
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
16546
17187
  });
16547
17188
  client.onError((msg, code) => {
16548
17189
  const requestedKind = code ?? msg;
@@ -16612,9 +17253,11 @@ var FECManager = class _FECManager {
16612
17253
  * fail deadline already passed, so failing it is the decision that deadline
16613
17254
  * made. A late ack then finds nothing owed and is a no-op.
16614
17255
  */
16615
- #boundOwedCleanup(key, packetId, client) {
17256
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
16616
17257
  this.#clearOwedCleanupBound(key);
16617
17258
  const bound = {
17259
+ dueAtMs,
17260
+ askedAtMs: performance.now(),
16618
17261
  handle: setTimeout(() => {
16619
17262
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
16620
17263
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -16712,7 +17355,15 @@ var FECManager = class _FECManager {
16712
17355
  this.#isoSourceOversizeCount++;
16713
17356
  return null;
16714
17357
  }
16715
- const sbn = located.block.start;
17358
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
17359
+ }
17360
+ /**
17361
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
17362
+ * answers through onFrame (null here), or its synchronous decoder, whose
17363
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
17364
+ * stated for `ssId`.
17365
+ */
17366
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
16716
17367
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
16717
17368
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
16718
17369
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -16741,6 +17392,74 @@ var FECManager = class _FECManager {
16741
17392
  }
16742
17393
  return recovered;
16743
17394
  }
17395
+ /**
17396
+ * Feed a source symbol of this stream that another FEC instance over the
17397
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
17398
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
17399
+ * BLO-52085). It joins its block's decoder as a received source would, so
17400
+ * it reduces the erasures the block still has to solve, but it is not a
17401
+ * network arrival: no transport accounting, no classification evidence,
17402
+ * no deadline refresh, and it never makes a block clean.
17403
+ *
17404
+ * Only a block a repair stated takes one (a repair-less span has no
17405
+ * decoder block). A block that is terminal, or already holds that source,
17406
+ * does not. The symbol is the exact protected packet, unpadded, as
17407
+ * feedSourceSymbol takes it.
17408
+ *
17409
+ * `recovered` is the block the synchronous decoder completed with it; the
17410
+ * caller routes it and completes the block, as for any recovery. When
17411
+ * every source of the block is then present, received or rebuilt, and no
17412
+ * decoder returned it (a Worker answers asynchronously, and reports such a
17413
+ * block as clean on its own side), the block is completed here as
17414
+ * recovered, with nothing left to route.
17415
+ */
17416
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
17417
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
17418
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
17419
+ if (located === null || located.block.span) return NOT_TAKEN;
17420
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
17421
+ const sbn = located.block.start;
17422
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
17423
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
17424
+ let rebuilt = this.#blockRebuiltEsis.get(key);
17425
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
17426
+ if (rebuilt === void 0) {
17427
+ rebuilt = /* @__PURE__ */ new Set();
17428
+ this.#blockRebuiltEsis.set(key, rebuilt);
17429
+ }
17430
+ const config = this.#trackConfigs.get(packetId);
17431
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
17432
+ rebuilt.add(located.esi);
17433
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
17434
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
17435
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
17436
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
17437
+ }
17438
+ }
17439
+ return { taken: true, recovered };
17440
+ }
17441
+ /**
17442
+ * A block that holds every one of its `length` sources, received or
17443
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
17444
+ * every packet of it was delivered, by its own arrival or by the instance
17445
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
17446
+ */
17447
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
17448
+ const rebuilt = this.#blockRebuiltEsis.get(key);
17449
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
17450
+ let present = rebuilt.size;
17451
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
17452
+ if (present < length) return false;
17453
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
17454
+ this.countRecovery(packetId, sbn, catalogTrackName);
17455
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17456
+ if (catalogTrackName === void 0) {
17457
+ this.onBlockComplete?.(sbn, packetId);
17458
+ } else {
17459
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
17460
+ }
17461
+ return true;
17462
+ }
16744
17463
  /**
16745
17464
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
16746
17465
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -16802,7 +17521,10 @@ var FECManager = class _FECManager {
16802
17521
  this.#layerAnchorHorizon(packetId),
16803
17522
  this.#sourceFrontiers.get(streamKey)?.sbn
16804
17523
  );
16805
- if (verdict === "discard") return false;
17524
+ if (verdict === "discard") {
17525
+ this.#unlistedRepairTrackRefusals++;
17526
+ return false;
17527
+ }
16806
17528
  if (verdict !== void 0) {
16807
17529
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName);
16808
17530
  return false;
@@ -16943,8 +17665,115 @@ var FECManager = class _FECManager {
16943
17665
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
16944
17666
  return null;
16945
17667
  }
17668
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
16946
17669
  return recovered;
16947
17670
  }
17671
+ /**
17672
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
17673
+ * its sources in send order, so one that moves the stream's newest source
17674
+ * position past a block leaves the sources that block still misses
17675
+ * reordered behind it at best: it shortens the wait of every block it
17676
+ * passed that only a late source can complete. MoQ is left out: its streams
17677
+ * can overtake one another, so a MoQ source shows nothing about the sources
17678
+ * sent before it.
17679
+ */
17680
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
17681
+ const previous = locator.newestSource;
17682
+ if (!locator.noteSource(ssId) || previous === void 0) return;
17683
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
17684
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17685
+ this.#shortenUnrecoverableWait(
17686
+ this.#blockKey(block.start, packetId, catalogTrackName),
17687
+ block.start,
17688
+ packetId,
17689
+ catalogTrackName
17690
+ );
17691
+ }
17692
+ }
17693
+ /**
17694
+ * The wait of a block that only a late source can complete (BLO-52085): a
17695
+ * repair stated it, its received sources plus every symbol its repair group
17696
+ * carries (RSB_length) are short of K' (the repair scheduler's
17697
+ * group-cannot-complete), and a later source of the stream has arrived, so
17698
+ * a source it misses is lost or reordered behind that one. The span, which
17699
+ * covers repair symbols paced after its sources, buys it nothing: it waits
17700
+ * the late-symbol allowance alone, the multicast wait less the span (the
17701
+ * catalog tolerance or the measured delivery gap). Undefined for any other
17702
+ * block. While a keyframe overlay is installed, the block waits for its
17703
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
17704
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
17705
+ * resolution is what releases the frames behind it, and failing it early
17706
+ * released them past a keyframe the overlay was still rebuilding, which
17707
+ * then arrived stale. The release gate lets them go instead
17708
+ * (isoRepairlessWaitMs).
17709
+ */
17710
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
17711
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
17712
+ const authoredLength = this.#blockAuthoredLengths.get(key);
17713
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
17714
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
17715
+ return void 0;
17716
+ }
17717
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
17718
+ }
17719
+ /**
17720
+ * A repair stated the block, and its sources plus every symbol its repair
17721
+ * group carries (RSB_length) are short of its SSB_length.
17722
+ */
17723
+ #groupCannotComplete(key) {
17724
+ const authoredLength = this.#blockAuthoredLengths.get(key);
17725
+ const rsbLength = this.#blockRsbLengths.get(key);
17726
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
17727
+ let present = this.#blockSourceCounts.get(key) ?? 0;
17728
+ const received = this.#blockSourceEsis.get(key);
17729
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
17730
+ return present + rsbLength < authoredLength;
17731
+ }
17732
+ /**
17733
+ * How long a loss only a late source or an installed keyframe overlay can
17734
+ * still fill waits once a later source passed it: the late-symbol
17735
+ * allowance alone (the multicast wait less the span) while no overlay is
17736
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
17737
+ * RAP packet the loss took: a second FEC instance over the same packets
17738
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
17739
+ * span, unrelated to the base's. That packet can complete a stated block
17740
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
17741
+ * first lets the release gate pass the keyframe, whose rebuild then lands
17742
+ * stale. The overlay repair of a packet the loss took goes out within the
17743
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
17744
+ * sent after it, so the loss waits that span plus the larger of the
17745
+ * allowance and the overlay's own tolerance. An overlay that states no
17746
+ * span (its block may then span keyframes), or one whose wait is not
17747
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
17748
+ */
17749
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
17750
+ const waitMs = this.#multicastWaitMs(config);
17751
+ const allowanceMs = waitMs - config.interleaveDepthMs;
17752
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
17753
+ if (overlay === void 0) return allowanceMs;
17754
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
17755
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
17756
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
17757
+ }
17758
+ /**
17759
+ * Bring an open block's wait in to its late-source wait, when it has one.
17760
+ * Never later than it is armed: only a source can complete such a block,
17761
+ * so a repair of its group (paced across the span) must not keep it open.
17762
+ */
17763
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
17764
+ if (!this.#activeBlocks.has(key)) return;
17765
+ const config = this.#trackConfigs.get(packetId);
17766
+ if (config === void 0) return;
17767
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
17768
+ if (waitMs === void 0) return;
17769
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
17770
+ this.#armBlockTimeout(
17771
+ sbn,
17772
+ packetId,
17773
+ catalogTrackName,
17774
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
17775
+ );
17776
+ }
16948
17777
  /**
16949
17778
  * Record a block's authored SSB_length from a repair symbol. Returns false,
16950
17779
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -17042,12 +17871,13 @@ var FECManager = class _FECManager {
17042
17871
  * the inactivity deadline on each symbol, records the symbol's in-band
17043
17872
  * classification evidence, and marks the block clean when all of its
17044
17873
  * authored source symbols arrived: the SSB_length a repair symbol declared,
17045
- * otherwise K.
17874
+ * otherwise K. `held` marks a source held unplaced since it arrived and
17875
+ * placed only now (see #noteSbnSeen).
17046
17876
  *
17047
17877
  * Throws for a packetId that was never configured, so a classified block
17048
17878
  * never reads the manager-global K or timeout.
17049
17879
  */
17050
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
17880
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
17051
17881
  const trackConfig = this.#trackConfigs.get(packetId);
17052
17882
  if (trackConfig === void 0) {
17053
17883
  throw new Error(
@@ -17063,7 +17893,8 @@ var FECManager = class _FECManager {
17063
17893
  catalogTrackName,
17064
17894
  "source",
17065
17895
  evidence.packetSequenceNumber,
17066
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
17896
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
17897
+ held
17067
17898
  );
17068
17899
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
17069
17900
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -17099,6 +17930,15 @@ var FECManager = class _FECManager {
17099
17930
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
17100
17931
  return;
17101
17932
  }
17933
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
17934
+ key,
17935
+ sbn,
17936
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
17937
+ packetId,
17938
+ catalogTrackName
17939
+ )) {
17940
+ return;
17941
+ }
17102
17942
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
17103
17943
  }
17104
17944
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -17107,7 +17947,9 @@ var FECManager = class _FECManager {
17107
17947
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17108
17948
  this.#blockSourceCounts.delete(key);
17109
17949
  this.#blockSourceEsis.delete(key);
17950
+ this.#blockRebuiltEsis.delete(key);
17110
17951
  this.#blockAuthoredLengths.delete(key);
17952
+ this.#isoSpanKeys.delete(key);
17111
17953
  this.#blockRepairRsIds.delete(key);
17112
17954
  this.#blockRsbLengths.delete(key);
17113
17955
  this.#markTerminal(key, sbn, packetId, true);
@@ -17138,6 +17980,19 @@ var FECManager = class _FECManager {
17138
17980
  #receiptNow() {
17139
17981
  return this.#receiptAtMs ?? performance.now();
17140
17982
  }
17983
+ /**
17984
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
17985
+ * scope: counted from the receipt time, as the timer of a symbol fed when
17986
+ * it was received was, less the whole ms since. So it fires on the tick
17987
+ * that timer would have, never later than a delay counted from now, and
17988
+ * its handler still re-arms a timer that fires before its deadline.
17989
+ * Counted from now, a deadline set from the receipt time is rounded up
17990
+ * from another fraction of a ms (BLO-52085).
17991
+ */
17992
+ #receiptTimerDelayMs(deadlineMs, minMs) {
17993
+ const receivedAtMs = this.#receiptAtMs;
17994
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
17995
+ }
17141
17996
  /**
17142
17997
  * A held packet admitted late arms from its (earlier) receipt time; that
17143
17998
  * never pulls in a deadline later activity already armed. Outside a
@@ -17173,10 +18028,20 @@ var FECManager = class _FECManager {
17173
18028
  this.#repairDeadlineMs(trackConfig)
17174
18029
  );
17175
18030
  }
17176
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
18031
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
18032
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
18033
+ return;
18034
+ }
18035
+ this.#armBlockTimeout(
18036
+ sbn,
18037
+ packetId,
18038
+ catalogTrackName,
18039
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
18040
+ );
17177
18041
  }
17178
18042
  #failBlock(sbn, packetId, catalogTrackName) {
17179
18043
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
18044
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
17180
18045
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
17181
18046
  this.#clearRepairDeadline(key);
17182
18047
  this.#clearBlockTimer(key);
@@ -17186,6 +18051,7 @@ var FECManager = class _FECManager {
17186
18051
  }
17187
18052
  this.#blockSourceCounts.delete(key);
17188
18053
  this.#blockSourceEsis.delete(key);
18054
+ this.#blockRebuiltEsis.delete(key);
17189
18055
  this.#blockAuthoredLengths.delete(key);
17190
18056
  this.#blockRepairRsIds.delete(key);
17191
18057
  this.#blockRsbLengths.delete(key);
@@ -17195,7 +18061,8 @@ var FECManager = class _FECManager {
17195
18061
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
17196
18062
  this.#fecStats.blocksFailed++;
17197
18063
  this.#statsForPacket(packetId).blocksFailed++;
17198
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18064
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18065
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
17199
18066
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
17200
18067
  }
17201
18068
  /**
@@ -17224,7 +18091,9 @@ var FECManager = class _FECManager {
17224
18091
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
17225
18092
  this.#blockSourceCounts.delete(key);
17226
18093
  this.#blockSourceEsis.delete(key);
18094
+ this.#blockRebuiltEsis.delete(key);
17227
18095
  this.#blockAuthoredLengths.delete(key);
18096
+ this.#isoSpanKeys.delete(key);
17228
18097
  this.#blockRepairRsIds.delete(key);
17229
18098
  this.#blockRsbLengths.delete(key);
17230
18099
  this.#clearBlockTimer(key);
@@ -17315,7 +18184,9 @@ var FECManager = class _FECManager {
17315
18184
  this.#blockKeysBySbn.clear();
17316
18185
  this.#blockSourceCounts.clear();
17317
18186
  this.#blockSourceEsis.clear();
18187
+ this.#blockRebuiltEsis.clear();
17318
18188
  this.#blockAuthoredLengths.clear();
18189
+ this.#isoSpanKeys.clear();
17319
18190
  this.#blockRepairRsIds.clear();
17320
18191
  this.#blockRsbLengths.clear();
17321
18192
  this.#heldLayerStates.clear();
@@ -17340,6 +18211,7 @@ var FECManager = class _FECManager {
17340
18211
  this.#blockAnchorsMs.clear();
17341
18212
  this.#blockCatalogTrackNames.clear();
17342
18213
  this.#classifiers.clear();
18214
+ this.#noSpanRaps.clear();
17343
18215
  this.#streamGeometries.clear();
17344
18216
  this.#failedBlocks.clear();
17345
18217
  this.#resolvedBlockClasses.clear();
@@ -17348,6 +18220,7 @@ var FECManager = class _FECManager {
17348
18220
  this.#highestSbn.clear();
17349
18221
  this.#sourceFrontiers.clear();
17350
18222
  this.#isoLocators.clear();
18223
+ this.#runAnchors.clear();
17351
18224
  this.#sourceAnchors.clear();
17352
18225
  this.#trackConfigs.clear();
17353
18226
  this.#fecDecoders.clear();
@@ -17870,9 +18743,21 @@ var IsoBmffTimingResolver = class {
17870
18743
  }
17871
18744
  #track = null;
17872
18745
  #fragments = /* @__PURE__ */ new Map();
18746
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
18747
+ #firstSamples = /* @__PURE__ */ new Map();
18748
+ /**
18749
+ * First sample and sample count of the newest fragments whose every slot was
18750
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
18751
+ * matches the combiner, since it retires an abandoned sample as well.
18752
+ */
18753
+ #delivered = /* @__PURE__ */ new Map();
17873
18754
  #pendingSamples = 0;
17874
18755
  #evictedSamples = 0;
17875
18756
  #lastMovieFragmentRejection = null;
18757
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
18758
+ get initialized() {
18759
+ return this.#track !== null;
18760
+ }
17876
18761
  get pendingSampleCount() {
17877
18762
  return this.#pendingSamples;
17878
18763
  }
@@ -17896,7 +18781,14 @@ var IsoBmffTimingResolver = class {
17896
18781
  this.#track = timing;
17897
18782
  return true;
17898
18783
  }
17899
- addMovieFragment(mpuSequenceNumber2, data, additionalSampleLimit = this.maxPendingSamples) {
18784
+ /**
18785
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
18786
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
18787
+ * fragment whose samples are all done is a duplicate: admitting it again
18788
+ * would charge stale timing and could displace the live MPU's. A source
18789
+ * copy is still admitted again (a rendition switch re-arms timing that way).
18790
+ */
18791
+ addMovieFragment(mpuSequenceNumber2, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
17900
18792
  this.#lastMovieFragmentRejection = null;
17901
18793
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
17902
18794
  this.#lastMovieFragmentRejection = "invalid";
@@ -17922,6 +18814,8 @@ var IsoBmffTimingResolver = class {
17922
18814
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
17923
18815
  );
17924
18816
  }
18817
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
18818
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
17925
18819
  let freed = 0;
17926
18820
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
17927
18821
  freed += this.#evictOldestFragment();
@@ -17935,6 +18829,7 @@ var IsoBmffTimingResolver = class {
17935
18829
  return false;
17936
18830
  }
17937
18831
  this.#fragments.set(key, [...parsed.samples]);
18832
+ this.#firstSamples.set(key, parsed.samples[0]);
17938
18833
  this.#pendingSamples += parsed.samples.length;
17939
18834
  return true;
17940
18835
  }
@@ -17992,6 +18887,7 @@ var IsoBmffTimingResolver = class {
17992
18887
  let live = 0;
17993
18888
  for (const sample of samples) if (sample !== null) live++;
17994
18889
  this.#fragments.delete(oldest);
18890
+ this.#firstSamples.delete(oldest);
17995
18891
  this.#pendingSamples -= live;
17996
18892
  this.#evictedSamples += live;
17997
18893
  return live;
@@ -18007,12 +18903,23 @@ var IsoBmffTimingResolver = class {
18007
18903
  if (!samples || !samples[index]) return false;
18008
18904
  samples[index] = null;
18009
18905
  this.#pendingSamples--;
18010
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
18906
+ if (samples.every((value) => value === null)) {
18907
+ this.#fragments.delete(key);
18908
+ const first = this.#firstSamples.get(key);
18909
+ this.#firstSamples.delete(key);
18910
+ this.#delivered.delete(key);
18911
+ this.#delivered.set(key, { first, sampleCount: samples.length });
18912
+ if (this.#delivered.size > this.maxPendingSamples) {
18913
+ this.#delivered.delete(this.#delivered.keys().next().value);
18914
+ }
18915
+ }
18011
18916
  return true;
18012
18917
  }
18013
18918
  reset() {
18014
18919
  this.#track = null;
18015
18920
  this.#fragments.clear();
18921
+ this.#firstSamples.clear();
18922
+ this.#delivered.clear();
18016
18923
  this.#pendingSamples = 0;
18017
18924
  }
18018
18925
  };
@@ -18182,6 +19089,9 @@ function authoredGap(before, after) {
18182
19089
  function ssIdAfter(a, b) {
18183
19090
  return (a - b | 0) > 0;
18184
19091
  }
19092
+ function holdsRebuilt(stream) {
19093
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
19094
+ }
18185
19095
  var FecReleaseSequencer = class {
18186
19096
  #streams = /* @__PURE__ */ new Map();
18187
19097
  #gate;
@@ -18244,6 +19154,7 @@ var FecReleaseSequencer = class {
18244
19154
  stream.lastSbn = void 0;
18245
19155
  stream.discontinuity = false;
18246
19156
  stream.rapSsId = void 0;
19157
+ stream.sourced = false;
18247
19158
  }
18248
19159
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
18249
19160
  this.#recordStat("droppedStale");
@@ -18270,6 +19181,7 @@ var FecReleaseSequencer = class {
18270
19181
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
18271
19182
  else hi = mid;
18272
19183
  }
19184
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
18273
19185
  stream.buf.splice(lo, 0, frame);
18274
19186
  this.#drainUnlessDeferred(stream);
18275
19187
  }
@@ -18305,6 +19217,41 @@ var FecReleaseSequencer = class {
18305
19217
  }
18306
19218
  return false;
18307
19219
  }
19220
+ /**
19221
+ * These streams' sink is being replaced by one that has seen no source
19222
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
19223
+ * release to the sink being replaced the frames the unanchored path had
19224
+ * already released to it (#cursorPassed): there they waited in its queue,
19225
+ * which its replacement flushes. A stream that holds none is not drained:
19226
+ * it holds nothing the anchor kept back, and a drain would still force out
19227
+ * a frame held past the hold limit, which before the anchor waited for the
19228
+ * next push. Then treat the streams as unsourced until a source frame is
19229
+ * released.
19230
+ */
19231
+ unsource(packetId, catalogTrackName) {
19232
+ for (const stream of this.#streams.values()) {
19233
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
19234
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
19235
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
19236
+ else this.#drain(stream, true);
19237
+ }
19238
+ stream.sourced = false;
19239
+ }
19240
+ }
19241
+ }
19242
+ /**
19243
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
19244
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
19245
+ * packetId.
19246
+ */
19247
+ holdsRebuilt(packetId, catalogTrackName) {
19248
+ for (const stream of this.#streams.values()) {
19249
+ if (stream.packetId !== packetId) continue;
19250
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
19251
+ if (holdsRebuilt(stream)) return true;
19252
+ }
19253
+ return false;
19254
+ }
18308
19255
  /** Re-evaluate held gaps after FEC state changed. */
18309
19256
  poke(streamKey) {
18310
19257
  if (streamKey !== void 0) {
@@ -18396,16 +19343,32 @@ var FecReleaseSequencer = class {
18396
19343
  last: null,
18397
19344
  lastSbn: void 0,
18398
19345
  discontinuity: false,
18399
- rapSsId: void 0
19346
+ rapSsId: void 0,
19347
+ sourced: false,
19348
+ draining: 0
18400
19349
  };
18401
19350
  this.#streams.set(streamKey, stream);
18402
19351
  }
18403
19352
  return stream;
18404
19353
  }
18405
- #drain(stream) {
19354
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
19355
+ #drain(stream, asUnanchored = false) {
19356
+ stream.draining++;
19357
+ try {
19358
+ this.#drainLoop(stream, asUnanchored);
19359
+ } finally {
19360
+ stream.draining--;
19361
+ }
19362
+ }
19363
+ #drainLoop(stream, asUnanchored) {
18406
19364
  while (stream.buf.length > 0 && stream.last !== null) {
18407
19365
  const head = stream.buf[0];
18408
19366
  const last = stream.last;
19367
+ if (compareFrameOrder(head, last) <= 0) {
19368
+ stream.buf.shift();
19369
+ this.#release(stream, head, void 0);
19370
+ continue;
19371
+ }
18409
19372
  if (stream.discontinuity) {
18410
19373
  stream.discontinuity = false;
18411
19374
  stream.buf.shift();
@@ -18419,9 +19382,10 @@ var FecReleaseSequencer = class {
18419
19382
  }
18420
19383
  const headSbn = head.meta.fecSbn;
18421
19384
  const from = stream.lastSbn ?? headSbn;
18422
- const to = headSbn ?? stream.lastSbn;
19385
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
18423
19386
  let lost = [];
18424
19387
  const unanchored = from === void 0 && to === void 0;
19388
+ let unresolved = false;
18425
19389
  if (from !== void 0 && to !== void 0) {
18426
19390
  const resolved = this.#gate.resolvedLoss(
18427
19391
  stream.packetId,
@@ -18430,7 +19394,8 @@ var FecReleaseSequencer = class {
18430
19394
  Math.max(from, to),
18431
19395
  from
18432
19396
  );
18433
- if (resolved === null) {
19397
+ unresolved = resolved === null;
19398
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
18434
19399
  const heldMs = performance.now() - head.arrivedAtMs;
18435
19400
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
18436
19401
  this.#recordStat("forcedWindowFlushes");
@@ -18438,22 +19403,69 @@ var FecReleaseSequencer = class {
18438
19403
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
18439
19404
  continue;
18440
19405
  }
18441
- lost = resolved;
19406
+ lost = resolved ?? [];
18442
19407
  }
18443
19408
  stream.buf.shift();
18444
19409
  this.#release(
18445
19410
  stream,
18446
19411
  head,
18447
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
19412
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
18448
19413
  );
18449
19414
  }
18450
19415
  }
19416
+ /**
19417
+ * The head has waited out a gap only a late source can still fill
19418
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
19419
+ * the stream when it has (`wakeAt`), since no packet may come by then.
19420
+ */
19421
+ #unrepairableWaitOver(stream, last, head, from, to) {
19422
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
19423
+ if (waitMs === void 0) return false;
19424
+ const atMs = head.arrivedAtMs + waitMs;
19425
+ if (performance.now() >= atMs) return true;
19426
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
19427
+ return false;
19428
+ }
19429
+ /**
19430
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
19431
+ * source cursor holds it unanchored, and neither does a later frame behind
19432
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
19433
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
19434
+ * like each frame that arrived in front of it since (stale there). The head
19435
+ * then goes, decided as it would be unanchored, once a frame the base path
19436
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
19437
+ * marked one: the base path has passed that one, so a frame still missing
19438
+ * before it can only come from a repair. It also goes while no source frame
19439
+ * has been released, when the direct path shows a recovered frame at once.
19440
+ * And it goes at once while a staged switch decides on when frames arrive
19441
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
19442
+ * sink being replaced: unanchored, it had already reached the sink.
19443
+ * The scan also writes: the `passed` marks it sets stay on the frames,
19444
+ * and push marks a frame it inserts in front of a marked one from them.
19445
+ */
19446
+ #cursorPassed(stream, asUnanchored) {
19447
+ let at2 = -1;
19448
+ for (let i = 0; i < stream.buf.length; i++) {
19449
+ const frame = stream.buf[i];
19450
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
19451
+ frame.passed = true;
19452
+ if (at2 < 0) at2 = i;
19453
+ } else if (frame.passed !== true) break;
19454
+ }
19455
+ if (at2 < 0) return false;
19456
+ 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));
19457
+ }
18451
19458
  #release(stream, frame, decision) {
19459
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
19460
+ if (stale) this.#recordStat("droppedStale");
18452
19461
  if (decision) frame.meta.gapBefore = decision;
18453
19462
  stream.last = frame;
18454
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
19463
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
19464
+ stream.lastSbn = frame.meta.fecSbn;
19465
+ }
19466
+ if (frame.meta.recovered !== true) stream.sourced = true;
18455
19467
  this.#gate.onReleased?.(frame.data, frame.meta);
18456
- this.#emit(frame.data, frame.meta);
19468
+ if (!stale) this.#emit(frame.data, frame.meta);
18457
19469
  }
18458
19470
  };
18459
19471
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -18494,6 +19506,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18494
19506
  this.#reclaimedTimingSamples = 0;
18495
19507
  this.#evictedTimingSamples = 0;
18496
19508
  this.#rejectedMovieFragments = 0;
19509
+ this.#recoveredHeadsAwaitingTiming = {
19510
+ held: 0,
19511
+ expired: 0,
19512
+ discarded: 0,
19513
+ superseded: 0
19514
+ };
18497
19515
  this.#sequencers = /* @__PURE__ */ new Map();
18498
19516
  this.#fecGate = null;
18499
19517
  this.#fecSequencer = null;
@@ -18602,6 +19620,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
18602
19620
  #reclaimedTimingSamples;
18603
19621
  #evictedTimingSamples;
18604
19622
  #rejectedMovieFragments;
19623
+ #recoveredHeadsAwaitingTiming;
18605
19624
  #sequencers;
18606
19625
  #fecGate;
18607
19626
  #fecSequencer;
@@ -18707,11 +19726,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18707
19726
  /**
18708
19727
  * Typed view of the ISO-BMFF timing-sample budget.
18709
19728
  *
18710
- * This is the acceptance signal for the budget ratchet: `pending` walking
18711
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
18712
- * and it is observable here rather than only as media silently stopping.
18713
- * Per repo policy this is a producer-owned counter -- never infer budget
18714
- * state by parsing logs.
19729
+ * Each stream admits timing against its own window of `capacity` slots
19730
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
19731
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
19732
+ * timing a stream declared and never delivered shows up there. `pending`
19733
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
19734
+ * a producer-owned counter -- never infer budget state by parsing logs.
18715
19735
  */
18716
19736
  get timingBudgetStats() {
18717
19737
  return {
@@ -18722,6 +19742,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
18722
19742
  rejectedMovieFragments: this.#rejectedMovieFragments
18723
19743
  };
18724
19744
  }
19745
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
19746
+ get recoveredHeadsAwaitingTiming() {
19747
+ let pending = 0;
19748
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
19749
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
19750
+ }
19751
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
19752
+ }
18725
19753
  get reorderStats() {
18726
19754
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
18727
19755
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -18763,6 +19791,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
18763
19791
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
18764
19792
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
18765
19793
  }
19794
+ /** See FecReleaseSequencer.unsource. */
19795
+ unsourceFecRelease(packetId, catalogTrackName) {
19796
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
19797
+ }
19798
+ /** See FecReleaseSequencer.holdsRebuilt. */
19799
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
19800
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
19801
+ }
18766
19802
  /** Re-evaluate held gaps after FEC block state changed. */
18767
19803
  pokeFecRelease(packetId, catalogTrackName) {
18768
19804
  if (!this.#fecSequencer) return;
@@ -18850,10 +19886,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
18850
19886
  get reassemblerDataUnitsReturned() {
18851
19887
  return this.#reassemblerDataUnitsReturned;
18852
19888
  }
18853
- #countOutcome(token) {
18854
- const count = (this.#feedOutcomes.get(token) ?? 0) + 1;
18855
- this.#feedOutcomes.set(token, count);
18856
- this.#lastOutcome = token;
19889
+ #countOutcome(token2) {
19890
+ const count = (this.#feedOutcomes.get(token2) ?? 0) + 1;
19891
+ this.#feedOutcomes.set(token2, count);
19892
+ this.#lastOutcome = token2;
18857
19893
  this.#lastOutcomeCount = count;
18858
19894
  }
18859
19895
  #countDeferredOutcome(reason) {
@@ -18895,7 +19931,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
18895
19931
  const now = Date.now();
18896
19932
  for (const { awaitingTiming } of this.#timingStreams.values()) {
18897
19933
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
18898
- awaitingTiming.shift();
19934
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
18899
19935
  }
18900
19936
  }
18901
19937
  }
@@ -19013,11 +20049,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
19013
20049
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
19014
20050
  return this.#drop("fragment-unexpected-fragmentation");
19015
20051
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
19016
- if (!resolver2) return this.#drop("fragment-no-resolver");
20052
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
19017
20053
  const pendingBefore = resolver2.pendingSampleCount;
19018
20054
  const evictedBefore = resolver2.evictedSampleCount;
19019
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
19020
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
20055
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
20056
+ const admitted = resolver2.addMovieFragment(
20057
+ mpu.mpuSequenceNumber,
20058
+ data,
20059
+ remaining,
20060
+ options?.recovered === true
20061
+ );
19021
20062
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
19022
20063
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
19023
20064
  if (!admitted) {
@@ -19037,7 +20078,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19037
20078
  };
19038
20079
  }
19039
20080
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
19040
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
20081
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
19041
20082
  if (!resolver) return this.#drop("mfu-no-resolver");
19042
20083
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
19043
20084
  return this.#drop("mfu-empty-payload");
@@ -19058,6 +20099,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19058
20099
  mpuSequenceNumber: mpu.mpuSequenceNumber,
19059
20100
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
19060
20101
  sampleNumber: mfuDuHeader.sampleNumber,
20102
+ sequenceNumber: info.sequenceNumber,
19061
20103
  arrivedAt: Date.now()
19062
20104
  });
19063
20105
  return this.#drop("mfu-sample-timing-missing");
@@ -19083,7 +20125,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19083
20125
  info,
19084
20126
  resolver,
19085
20127
  options?.recovered === true,
19086
- options?.fecSbn
20128
+ options?.fecSbn,
20129
+ options?.fecSbnFirst
19087
20130
  );
19088
20131
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
19089
20132
  }
@@ -19176,7 +20219,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19176
20219
  info,
19177
20220
  resolver,
19178
20221
  options?.recovered === true,
19179
- options?.fecSbn
20222
+ options?.fecSbn,
20223
+ options?.fecSbnFirst
19180
20224
  );
19181
20225
  if (outcome.record !== void 0) return outcome.record;
19182
20226
  return this.#drop(outcome.reason);
@@ -19196,7 +20240,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19196
20240
  * attribution exists to keep readable. Leaving the choice at the call site
19197
20241
  * is what keeps both true.
19198
20242
  */
19199
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
20243
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
19200
20244
  const timing = resolver.sampleTiming(
19201
20245
  combined.mpuSequenceNumber,
19202
20246
  combined.movieFragmentSequenceNumber,
@@ -19213,6 +20257,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19213
20257
  );
19214
20258
  if (!meta) return { reason: "combined-meta-build-failed" };
19215
20259
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
20260
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
19216
20261
  if (!resolver.consumeSample(
19217
20262
  combined.mpuSequenceNumber,
19218
20263
  combined.movieFragmentSequenceNumber,
@@ -19381,6 +20426,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
19381
20426
  }
19382
20427
  this.#emitFrame(data, meta);
19383
20428
  }
20429
+ /** Whether FT=1 metadata already names this sample, without claiming it. */
20430
+ hasAuthoredTimingFor(packetId, mpuSequenceNumber2, movieFragmentSequenceNumber, sampleNumber, catalogTrackName) {
20431
+ return this.#timingResolver(this.#streamKey(packetId, catalogTrackName), packetId, false)?.sampleTiming(mpuSequenceNumber2, movieFragmentSequenceNumber, sampleNumber) != null;
20432
+ }
19384
20433
  /**
19385
20434
  * Claim and return the authored timing for a recovered sample. Recovery does
19386
20435
  * not pass through the ordinary `feed()` completion path, so it must retire
@@ -19442,6 +20491,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
19442
20491
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
19443
20492
  this.#sequencers.clear();
19444
20493
  this.#fecSequencer?.discard();
20494
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
20495
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
20496
+ }
19445
20497
  this.#timingStreams.clear();
19446
20498
  this.#pendingTimingSamples = 0;
19447
20499
  this.#reliableMoqStartupGate.clear();
@@ -19460,10 +20512,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
19460
20512
  return resolver;
19461
20513
  }
19462
20514
  #awaitTiming(streamKey, head) {
19463
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
19464
- if (!awaitingTiming) return;
20515
+ const state = this.#timingStreams.get(streamKey);
20516
+ if (!state) return;
20517
+ if (!head.options?.recovered) {
20518
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
20519
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
20520
+ state.awaitingTiming = kept;
20521
+ }
20522
+ const awaitingTiming = state.awaitingTiming;
19465
20523
  awaitingTiming.push(head);
19466
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
20524
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
20525
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
20526
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
20527
+ }
20528
+ }
20529
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
20530
+ #leaveAwaitingTiming(head, outcome) {
20531
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
19467
20532
  }
19468
20533
  /**
19469
20534
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -19491,6 +20556,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19491
20556
  const state = this.#timingStreams.get(streamKey);
19492
20557
  if (!state) return;
19493
20558
  this.#timingStreams.delete(streamKey);
20559
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
19494
20560
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
19495
20561
  if (this.#pendingTimingSamples < 0) {
19496
20562
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -22697,7 +23763,18 @@ function keyframeOverlaySsId(header) {
22697
23763
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
22698
23764
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
22699
23765
  }
23766
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
23767
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
23768
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
23769
+ }
23770
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
23771
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
23772
+ return headerPsn + offset >>> 0;
23773
+ }
23774
+ var OVERLAY_ROUTED_LIMIT = 1024;
23775
+ var OVERLAY_PENDING_LIMIT = 256;
22700
23776
  var OVERLAY_OFFSET_MPUS = 16;
23777
+ var OVERLAY_REBUILT_LIMIT = 256;
22701
23778
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
22702
23779
  function assertStreamIdentity(role, stream) {
22703
23780
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -22808,6 +23885,7 @@ var MmtpRouter = class {
22808
23885
  #provenance = /* @__PURE__ */ new Map();
22809
23886
  #onFlowProtected = null;
22810
23887
  #unadmittedListedDrops = 0;
23888
+ #admittedSourceDatagrams = 0;
22811
23889
  #unlistedRepairSetAside = 0;
22812
23890
  #assistBlocks = /* @__PURE__ */ new Map();
22813
23891
  #assistFailures = /* @__PURE__ */ new Map();
@@ -22864,6 +23942,26 @@ var MmtpRouter = class {
22864
23942
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
22865
23943
  */
22866
23944
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23945
+ /**
23946
+ * Per stream, the SS_ID offset at which a base recovery last showed the
23947
+ * sender's own packet_sequence_number: a recovered packet's header psn
23948
+ * equal to its SS_ID minus that offset. While it equals the stream's
23949
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
23950
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
23951
+ * an MPU no member of which arrived).
23952
+ */
23953
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23954
+ /**
23955
+ * The same, shown by the overlay alone, before any base recovery did: a
23956
+ * packet it rebuilt whose base copy carries its protected psn
23957
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
23958
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
23959
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
23960
+ * make the base drop a late base copy of a keyframe the overlay never
23961
+ * finished, and lift a block's late-source cut, which nothing before
23962
+ * this offset did.
23963
+ */
23964
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
22867
23965
  /**
22868
23966
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
22869
23967
  * not parsed, typically because its overlap copy was parsed first
@@ -22909,6 +24007,8 @@ var MmtpRouter = class {
22909
24007
  // end: a synchronous recovery completes its block BEFORE routing the
22910
24008
  // recovered frames, and releasing a held gap in between would strand them.
22911
24009
  #fecPokeDepth = 0;
24010
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
24011
+ #fecWakes = /* @__PURE__ */ new Map();
22912
24012
  #pendingFecPokes = /* @__PURE__ */ new Map();
22913
24013
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
22914
24014
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -22933,7 +24033,9 @@ var MmtpRouter = class {
22933
24033
  recovered: 0,
22934
24034
  restarts: 0,
22935
24035
  unsequencedDropped: 0,
22936
- protectedDropped: 0
24036
+ protectedDropped: 0,
24037
+ baseFed: 0,
24038
+ baseUndetermined: 0
22937
24039
  };
22938
24040
  /** Callback fired when a delta-track FEC block completes or fails. */
22939
24041
  #onDeltaBlockCompleteCb = null;
@@ -23106,7 +24208,7 @@ var MmtpRouter = class {
23106
24208
  const cb = this.#getFrameCallback(packetId);
23107
24209
  if (isVideo && !assembler) {
23108
24210
  if (frameMeta.recovered) {
23109
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
24211
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
23110
24212
  } else {
23111
24213
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
23112
24214
  }
@@ -23139,13 +24241,18 @@ var MmtpRouter = class {
23139
24241
  this.#onDeltaBlockCompleteCb?.(packetId, false);
23140
24242
  }
23141
24243
  };
23142
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
24244
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
23143
24245
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
23144
24246
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
23145
24247
  this.#onDeltaBlockCompleteCb?.(packetId, true);
23146
24248
  }
23147
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23148
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
24249
+ if (span === void 0) {
24250
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
24251
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
24252
+ } else {
24253
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
24254
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
24255
+ }
23149
24256
  };
23150
24257
  }
23151
24258
  }
@@ -23190,8 +24297,9 @@ var MmtpRouter = class {
23190
24297
  }
23191
24298
  /**
23192
24299
  * FEC-recovered source symbols whose reconstructed header named a
23193
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
23194
- * a hop re-stamped the sequence after the sender protected the packet.
24300
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
24301
+ * or, rebuilt by the overlay, than their base copy carries: a hop
24302
+ * re-stamped the sequence after the sender protected the packet.
23195
24303
  */
23196
24304
  get restampedRecoveredSequenceCount() {
23197
24305
  return this.#restampedRecoveredSeqs;
@@ -23370,6 +24478,7 @@ var MmtpRouter = class {
23370
24478
  enableMseAssembler(packetId, config, catalogTrackName) {
23371
24479
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
23372
24480
  const previous = this.#mseAssemblers.get(assemblerKey);
24481
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
23373
24482
  if (previous) {
23374
24483
  previous.flush();
23375
24484
  previous.dispose();
@@ -23496,6 +24605,10 @@ var MmtpRouter = class {
23496
24605
  get keyframeOverlayStats() {
23497
24606
  return { ...this.#overlayStats };
23498
24607
  }
24608
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
24609
+ get recoveredHeadsAwaitingTiming() {
24610
+ return this.#parser.recoveredHeadsAwaitingTiming;
24611
+ }
23499
24612
  #isOverlayRepair(repairPacketId, repairTrackName) {
23500
24613
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
23501
24614
  }
@@ -23516,7 +24629,8 @@ var MmtpRouter = class {
23516
24629
  fec,
23517
24630
  k,
23518
24631
  offsets: /* @__PURE__ */ new Map(),
23519
- moqBlocks: /* @__PURE__ */ new Set()
24632
+ moqBlocks: /* @__PURE__ */ new Set(),
24633
+ rebuilt: /* @__PURE__ */ new Map()
23520
24634
  };
23521
24635
  this.#overlays.set(repairPacketId, inst);
23522
24636
  return () => {
@@ -23546,12 +24660,18 @@ var MmtpRouter = class {
23546
24660
  */
23547
24661
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
23548
24662
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
24663
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
24664
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
24665
+ stream.overlayToBase.routed.clear();
24666
+ stream.overlayToBase.pending.clear();
24667
+ }
23549
24668
  }
23550
24669
  #resetOverlay(inst) {
23551
24670
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
23552
24671
  inst.last = void 0;
23553
24672
  inst.offsets.clear();
23554
24673
  inst.moqBlocks.clear();
24674
+ inst.rebuilt.clear();
23555
24675
  }
23556
24676
  #overlaysForSource(sourcePacketId, catalogTrackName) {
23557
24677
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -23602,18 +24722,33 @@ var MmtpRouter = class {
23602
24722
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
23603
24723
  * every overlay installed for its source, at that SS_ID, with the bytes the
23604
24724
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
23605
- * included (7.1, 7.4.3).
23606
- */
23607
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
24725
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
24726
+ * FEC reads it.
24727
+ *
24728
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
24729
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
24730
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
24731
+ * the stream unstamped at the SS_ID offset it states, for the release gate
24732
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
24733
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
24734
+ */
24735
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
23608
24736
  if (this.#overlays.size === 0) return;
23609
24737
  const ssId = keyframeOverlaySsId(header);
23610
24738
  if (ssId === void 0) return;
24739
+ let rebuiltPsn;
23611
24740
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
23612
24741
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
24742
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
24743
+ inst.rebuilt.delete(ssId);
23613
24744
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
23614
24745
  if (identity !== null) {
23615
24746
  inst.offsets.delete(identity.mpuSequenceNumber);
23616
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
24747
+ inst.offsets.set(identity.mpuSequenceNumber, {
24748
+ psnOffset: ssId - sequenceNumber >>> 0,
24749
+ overlaySsId: ssId,
24750
+ ...baseSsId === void 0 ? {} : { baseSsId }
24751
+ });
23617
24752
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
23618
24753
  }
23619
24754
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23635,6 +24770,14 @@ var MmtpRouter = class {
23635
24770
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
23636
24771
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
23637
24772
  }
24773
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
24774
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
24775
+ if (rebuiltPsn !== sequenceNumber) {
24776
+ this.#restampedRecoveredSeqs++;
24777
+ } else if (baseSsId !== void 0) {
24778
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24779
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24780
+ }
23638
24781
  }
23639
24782
  #noteOverlayMoqBlock(inst, blockStart) {
23640
24783
  inst.moqBlocks.add(blockStart);
@@ -23668,11 +24811,16 @@ var MmtpRouter = class {
23668
24811
  }
23669
24812
  /**
23670
24813
  * Route an overlay-recovered block's packets as source media of the
23671
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
23672
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
23673
- * base re-stamp, no block advance. Each packet's wire sequence is restored
23674
- * from its keyframe's own offset; without one, a stream the base never
23675
- * re-stamped keeps the header's sequence and any other drops the packet.
24814
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
24815
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
24816
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
24817
+ * base FEC recovered does, so it waits behind base frames still in flight,
24818
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
24819
+ * longer than unanchored; one whose base SS_ID is undetermined has no
24820
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
24821
+ * advance. Each packet's wire sequence is restored from its keyframe's own
24822
+ * offset; without one, a stream the base never re-stamped keeps the
24823
+ * header's sequence and any other drops the packet.
23676
24824
  */
23677
24825
  #routeOverlayRecovered(inst, blockStart, recovered) {
23678
24826
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23692,22 +24840,139 @@ var MmtpRouter = class {
23692
24840
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
23693
24841
  const restamped = this.#restampedStreams.has(streamKey);
23694
24842
  const restored = /* @__PURE__ */ new Set();
24843
+ const baseSsIds = /* @__PURE__ */ new Map();
24844
+ const gateOnly = /* @__PURE__ */ new Set();
23695
24845
  const symbols = result.symbols.flatMap((sym) => {
23696
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
23697
- if (offset !== void 0) {
23698
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
24846
+ const overlaySsId = serial32Add(blockStart, sym.index);
24847
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
24848
+ if (anchor !== void 0) {
24849
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
23699
24850
  restored.add(packetSequenceNumber);
23700
- return [{ ...sym, packetSequenceNumber }];
24851
+ const out = { ...sym, packetSequenceNumber };
24852
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
24853
+ if (baseSsId !== void 0) {
24854
+ baseSsIds.set(sym.index, baseSsId);
24855
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24856
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
24857
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24858
+ }
24859
+ }
24860
+ return [out];
24861
+ }
24862
+ if (!restamped) {
24863
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24864
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24865
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24866
+ if (baseSsId !== void 0) {
24867
+ baseSsIds.set(sym.index, baseSsId);
24868
+ if (fedSsId === void 0) gateOnly.add(sym.index);
24869
+ } else {
24870
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
24871
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
24872
+ }
24873
+ return [sym];
23701
24874
  }
23702
- if (!restamped) return [sym];
23703
24875
  this.#overlayStats.unsequencedDropped++;
23704
24876
  return [];
23705
24877
  });
23706
24878
  this.#overlayStats.recovered++;
24879
+ const mpuFirst = /* @__PURE__ */ new Map();
24880
+ for (const sym of symbols) {
24881
+ const ssId = baseSsIds.get(sym.index);
24882
+ const mpu = sym.fragment.mpuSequenceNumber;
24883
+ const first = mpuFirst.get(mpu);
24884
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
24885
+ }
24886
+ const firstSsIds = /* @__PURE__ */ new Map();
24887
+ for (const sym of symbols) {
24888
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
24889
+ }
23707
24890
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
23708
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
24891
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
24892
+ baseSsIds,
24893
+ firstSsIds
23709
24894
  });
23710
24895
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
24896
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
24897
+ }
24898
+ /**
24899
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
24900
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
24901
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
24902
+ * base recovery showed; `baseSsIds` holds no other),
24903
+ * so it is fed to the base decoder as a rebuilt source
24904
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
24905
+ * fewer to solve, and its repair can recover the block's other packets.
24906
+ * A base block no repair has stated yet takes it when one does
24907
+ * (#feedPendingRebuilt).
24908
+ *
24909
+ * The overlay route already handled each packet fed (delivered it, or
24910
+ * held an untimed head for its FT=1), so a base recovery routes none of
24911
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
24912
+ * held head would wait in the parser for timing its first copy consumed.
24913
+ * Only an overlay block decoded from multicast symbols alone is fed: with
24914
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
24915
+ * that crossed no multicast socket, which the provenance counted from the
24916
+ * block's own arrivals cannot show.
24917
+ */
24918
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
24919
+ const fec = this.#fecManager;
24920
+ const owner = inst.leg.sourcePacketId;
24921
+ const name = inst.leg.sourceCatalogTrackName;
24922
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
24923
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
24924
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
24925
+ const feeds = [];
24926
+ for (const sym of symbols) {
24927
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
24928
+ const ssId = baseSsIds.get(sym.index);
24929
+ if (ssId === void 0) {
24930
+ this.#overlayStats.baseUndetermined++;
24931
+ continue;
24932
+ }
24933
+ routed.delete(ssId);
24934
+ routed.add(ssId);
24935
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
24936
+ feeds.push([ssId, sym.rawSymbol]);
24937
+ }
24938
+ for (const [ssId, symbolData] of feeds) {
24939
+ if (this.#classifyPacketId(owner) === null) return;
24940
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
24941
+ }
24942
+ }
24943
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
24944
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
24945
+ const fec = this.#fecManager;
24946
+ if (!fec?.feedRebuiltSourceSymbol) return;
24947
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
24948
+ if (coords == null) {
24949
+ const pending = this.#stream(owner, name).overlayToBase.pending;
24950
+ pending.delete(ssId);
24951
+ pending.set(ssId, symbolData.slice());
24952
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
24953
+ return;
24954
+ }
24955
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
24956
+ if (!fed.taken) return;
24957
+ this.#overlayStats.baseFed++;
24958
+ if (fed.recovered === null) return;
24959
+ const sbn = coords.sbn;
24960
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
24961
+ fec.cancelBlockTimeout(sbn, owner, name);
24962
+ fec.countRecovery(owner, sbn, name);
24963
+ fec.markBlockCompleted(sbn, owner, name);
24964
+ });
24965
+ }
24966
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
24967
+ #feedPendingRebuilt(owner, name, block) {
24968
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
24969
+ if (pending === void 0 || pending.size === 0) return;
24970
+ for (const [ssId, symbolData] of [...pending]) {
24971
+ if (this.#classifyPacketId(owner) === null) return;
24972
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
24973
+ pending.delete(ssId);
24974
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
24975
+ }
23711
24976
  }
23712
24977
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
23713
24978
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -23847,6 +25112,10 @@ var MmtpRouter = class {
23847
25112
  get unadmittedListedDropCount() {
23848
25113
  return this.#unadmittedListedDrops;
23849
25114
  }
25115
+ /** 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. */
25116
+ get admittedSourceDatagramCount() {
25117
+ return this.#admittedSourceDatagrams;
25118
+ }
23850
25119
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
23851
25120
  get unlistedRepairSetAsideCount() {
23852
25121
  return this.#unlistedRepairSetAside;
@@ -24333,6 +25602,8 @@ var MmtpRouter = class {
24333
25602
  )) return;
24334
25603
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
24335
25604
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
25605
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
25606
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
24336
25607
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
24337
25608
  const recovered = fec.feedRepairSymbol(
24338
25609
  ownerPacketId,
@@ -24383,7 +25654,7 @@ var MmtpRouter = class {
24383
25654
  catalogTrackName
24384
25655
  )) continue;
24385
25656
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
24386
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
25657
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
24387
25658
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
24388
25659
  }
24389
25660
  if (payload.oversized) continue;
@@ -24470,6 +25741,8 @@ var MmtpRouter = class {
24470
25741
  this.#droppedPreSyncVideo.delete(streamKey);
24471
25742
  this.#latestVideoSeqByStream.delete(streamKey);
24472
25743
  this.#ssIdSeqOffsetByStream.delete(streamKey);
25744
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
25745
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
24473
25746
  this.#multicastRapTwinByStream.delete(streamKey);
24474
25747
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
24475
25748
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -24596,6 +25869,12 @@ var MmtpRouter = class {
24596
25869
  * the outgoing stream stops. The hold is bounded by the incoming stream's
24597
25870
  * own RAP cadence, so no timer is involved.
24598
25871
  *
25872
+ * While the switch is staged, the FEC release gate lets a keyframe the
25873
+ * overlay rebuilt reach it, on either side, when the keyframe did before
25874
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
25875
+ * decides on what each side delivered, and the commit discards the gate's
25876
+ * frames of the outgoing stream.
25877
+ *
24599
25878
  * The commit is one synchronous transition inside the frame path: the
24600
25879
  * outgoing stream's already-admitted frames are released (its queued FEC
24601
25880
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -24646,6 +25925,9 @@ var MmtpRouter = class {
24646
25925
  droppedIncomingFrames: 0
24647
25926
  };
24648
25927
  this.#staged = state;
25928
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
25929
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
25930
+ }
24649
25931
  return {
24650
25932
  cancel: () => {
24651
25933
  if (this.#staged !== state) return false;
@@ -24728,7 +26010,17 @@ var MmtpRouter = class {
24728
26010
  */
24729
26011
  #routeParsedFrame(data, meta) {
24730
26012
  if (this.#classifyPacketId(meta.packetId) === null) return;
24731
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
26013
+ if (this.#staged !== null) {
26014
+ let consumed = false;
26015
+ this.#fecPokeDepth++;
26016
+ try {
26017
+ consumed = this.#interceptSwitchFrame(data, meta);
26018
+ } finally {
26019
+ this.#fecPokeDepth--;
26020
+ this.#flushPendingFecPokes();
26021
+ }
26022
+ if (consumed) return;
26023
+ }
24732
26024
  this.#deliverParsedFrame(data, meta);
24733
26025
  }
24734
26026
  #commitStreamSwitch(state, rap, reason) {
@@ -24777,6 +26069,8 @@ var MmtpRouter = class {
24777
26069
  this.#disposed = true;
24778
26070
  this.#staged = null;
24779
26071
  this.cancelKeyframeLostTimer();
26072
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
26073
+ this.#fecWakes.clear();
24780
26074
  this.#parser.dispose();
24781
26075
  this.#streams.clear();
24782
26076
  this.#trackPacketCallbacks.clear();
@@ -24880,12 +26174,16 @@ var MmtpRouter = class {
24880
26174
  this.#parser.deferFecRelease(work);
24881
26175
  } finally {
24882
26176
  this.#fecPokeDepth--;
24883
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
24884
- const pokes = [...this.#pendingFecPokes.values()];
24885
- this.#pendingFecPokes.clear();
24886
- for (const poke of pokes) {
24887
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
24888
- }
26177
+ this.#flushPendingFecPokes();
26178
+ }
26179
+ }
26180
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
26181
+ #flushPendingFecPokes() {
26182
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
26183
+ const pokes = [...this.#pendingFecPokes.values()];
26184
+ this.#pendingFecPokes.clear();
26185
+ for (const poke of pokes) {
26186
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
24889
26187
  }
24890
26188
  }
24891
26189
  }
@@ -24954,6 +26252,34 @@ var MmtpRouter = class {
24954
26252
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
24955
26253
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
24956
26254
  },
26255
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
26256
+ // late source can), its frame waits the late-symbol allowance when the
26257
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
26258
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
26259
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
26260
+ // unless the gap holds a stated block's loss: the overlay may rebuild
26261
+ // that MPU's FT=0, and the block's group then complete it), or
26262
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
26263
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
26264
+ // overlay protects) waits for that overlay's repair too (BLO-52085
26265
+ // D4). A run no repair has delimited instead waits for its FEC
26266
+ // deadline, whatever the decision (FECManager.isoRepairlessWaitMs). The
26267
+ // FEC check comes first: most held gaps are not behind such a span, and
26268
+ // deciding one scans both frames' bitstreams.
26269
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
26270
+ const fec = this.#fecManager;
26271
+ const { packetId, catalogTrackName } = after.meta;
26272
+ const arrivedAtMs = after.arrivedAtMs;
26273
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, false, arrivedAtMs);
26274
+ if (!fec || allowanceMs === void 0) return void 0;
26275
+ const decision = this.#decideGap(before, after, [], false);
26276
+ const mpu = before.meta.mpuSequenceNumber;
26277
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
26278
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
26279
+ return fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true, false, arrivedAtMs);
26280
+ }
26281
+ return decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true, arrivedAtMs) : allowanceMs;
26282
+ },
24957
26283
  decide: (before, after, lostBlocks, discontinuity) => {
24958
26284
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
24959
26285
  this.#onFrameGap?.(decision);
@@ -24963,6 +26289,28 @@ var MmtpRouter = class {
24963
26289
  onRap: (packetId, catalogTrackName, ssId) => {
24964
26290
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
24965
26291
  },
26292
+ // One timer per stream, at the earliest wake asked: its drain re-arms
26293
+ // for the next frame still waiting.
26294
+ wakeAt: (packetId, catalogTrackName, atMs) => {
26295
+ if (this.#disposed) return;
26296
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
26297
+ const armed = this.#fecWakes.get(key);
26298
+ if (armed !== void 0 && armed.atMs <= atMs) return;
26299
+ if (armed !== void 0) clearTimeout(armed.timer);
26300
+ const timer = setTimeout(() => {
26301
+ this.#fecWakes.delete(key);
26302
+ this.#requestFecPoke(packetId, catalogTrackName);
26303
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
26304
+ this.#fecWakes.set(key, { atMs, timer });
26305
+ },
26306
+ // A staged switch commits on when each side's frames reach it
26307
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
26308
+ // they did unanchored.
26309
+ releaseUnanchored: (packetId, catalogTrackName) => {
26310
+ const staged = this.#staged;
26311
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
26312
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
26313
+ },
24966
26314
  onReleased: (data, meta) => {
24967
26315
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
24968
26316
  const timing = meta.authoredTiming;
@@ -24972,7 +26320,8 @@ var MmtpRouter = class {
24972
26320
  meta.catalogTrackName,
24973
26321
  meta.mpuSequenceNumber,
24974
26322
  timing.presentationTime,
24975
- timing.mediaTimescale
26323
+ timing.mediaTimescale,
26324
+ timing.decodeTime
24976
26325
  );
24977
26326
  }
24978
26327
  };
@@ -24990,8 +26339,20 @@ var MmtpRouter = class {
24990
26339
  #decideGap(before, after, lostBlocks, discontinuity) {
24991
26340
  const { packetId, catalogTrackName } = after.meta;
24992
26341
  const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
24993
- const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying";
24994
- const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
26342
+ const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying" && before.meta.movieFragmentSequenceNumber === after.meta.movieFragmentSequenceNumber;
26343
+ const mpu = before.meta.mpuSequenceNumber;
26344
+ const sameMpu = trackKind === "video" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu;
26345
+ const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(
26346
+ packetId,
26347
+ catalogTrackName,
26348
+ sameMpu ? {
26349
+ mpu,
26350
+ from: before.meta.authoredTiming,
26351
+ to: after.meta.authoredTiming,
26352
+ fromSsId: before.meta.fecSbn,
26353
+ toSsId: after.meta.fecSbnFirst ?? after.meta.fecSbn
26354
+ } : void 0
26355
+ ) === true;
24995
26356
  const evidence = (frame) => {
24996
26357
  const timing = frame.meta.authoredTiming;
24997
26358
  const sampleNumber = frame.meta.sampleNumber;
@@ -25104,6 +26465,7 @@ var MmtpRouter = class {
25104
26465
  const parsed = this.#parser.parsePacket(packet);
25105
26466
  if (!parsed) return;
25106
26467
  const info = parsed.info;
26468
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
25107
26469
  if (source === "multicast" && !manifestAdmitted) {
25108
26470
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
25109
26471
  }
@@ -25282,6 +26644,7 @@ var MmtpRouter = class {
25282
26644
  evidence: sourceSymbolEvidence(packet, parsed.header, info.rapFlag, info.sequenceNumber),
25283
26645
  oversized: !(this.#fecManager.isoSourceFits?.(info.packetId, rawSymbol.length) ?? false)
25284
26646
  }) ?? false;
26647
+ if (held) this.#requestFecPoke(info.packetId, catalogTrackName);
25285
26648
  parseSourceSymbol = held && !duplicates.parsedSymbols.has(ssId);
25286
26649
  }
25287
26650
  } else if (fecUnreadable && info.fecPayloadId) {
@@ -25385,7 +26748,8 @@ var MmtpRouter = class {
25385
26748
  parsed.header,
25386
26749
  info.sequenceNumber,
25387
26750
  info.rapFlag,
25388
- source
26751
+ source,
26752
+ fecPayloadId?.ssId
25389
26753
  );
25390
26754
  }
25391
26755
  }
@@ -25411,7 +26775,8 @@ var MmtpRouter = class {
25411
26775
  source: parserOptions?.source,
25412
26776
  deliveryProvenance: parserOptions?.deliveryProvenance,
25413
26777
  catalogTrackName: parserOptions?.catalogTrackName,
25414
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
26778
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
26779
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
25415
26780
  };
25416
26781
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
25417
26782
  else this.#parser.feed(packet, feedOptions);
@@ -25535,7 +26900,8 @@ var MmtpRouter = class {
25535
26900
  if (stream === void 0) {
25536
26901
  stream = {
25537
26902
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
25538
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
26903
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
26904
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
25539
26905
  };
25540
26906
  byName.set(catalogTrackName, stream);
25541
26907
  }
@@ -25650,8 +27016,16 @@ var MmtpRouter = class {
25650
27016
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
25651
27017
  this.#emitDirectVideo(packetId, data, meta, cb);
25652
27018
  }
25653
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
27019
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
25654
27020
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
27021
+ if (this.#isFecTrack(packetId)) {
27022
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
27023
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
27024
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
27025
+ this.#emitDirectVideo(packetId, data, meta, cb);
27026
+ return;
27027
+ }
27028
+ }
25655
27029
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
25656
27030
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
25657
27031
  this.#drainDirectRecoveredVideo(
@@ -25805,6 +27179,13 @@ var MmtpRouter = class {
25805
27179
  * frames by epoch only if pre-protection input ever matters.
25806
27180
  */
25807
27181
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
27182
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
27183
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
27184
+ result = {
27185
+ ...result,
27186
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
27187
+ };
27188
+ }
25808
27189
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
25809
27190
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
25810
27191
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -25861,7 +27242,12 @@ var MmtpRouter = class {
25861
27242
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
25862
27243
  if (ownerPacketId == null) return;
25863
27244
  if (this.#classifyPacketId(ownerPacketId) === null) return;
25864
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
27245
+ const fecSbnOf = (index) => {
27246
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
27247
+ const fecSbn = overlay.baseSsIds.get(index);
27248
+ const fecSbnFirst = overlay.firstSsIds.get(index);
27249
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
27250
+ };
25865
27251
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
25866
27252
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
25867
27253
  if (ssIdSeqOffset !== void 0) {
@@ -25869,7 +27255,10 @@ var MmtpRouter = class {
25869
27255
  ...result,
25870
27256
  symbols: result.symbols.map((sym) => {
25871
27257
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
25872
- if (wire === sym.packetSequenceNumber) return sym;
27258
+ if (wire === sym.packetSequenceNumber) {
27259
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
27260
+ return sym;
27261
+ }
25873
27262
  this.#restampedRecoveredSeqs++;
25874
27263
  this.#restampedStreams.add(streamKey);
25875
27264
  return { ...sym, packetSequenceNumber: wire };
@@ -25905,6 +27294,29 @@ var MmtpRouter = class {
25905
27294
  }
25906
27295
  );
25907
27296
  }
27297
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
27298
+ ownerPacketId,
27299
+ sym.fragment.mpuSequenceNumber,
27300
+ sym.fragment.movieFragmentSequenceNumber,
27301
+ sym.fragment.sampleNumber,
27302
+ catalogTrackName
27303
+ );
27304
+ for (const sym of result.symbols) {
27305
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
27306
+ this.#feedViaParser(
27307
+ sym.rawSymbol,
27308
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
27309
+ void 0,
27310
+ {
27311
+ skipFecPayloadId: true,
27312
+ recovered: true,
27313
+ deliveryProvenance,
27314
+ ...fecSbnOf(sym.index),
27315
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
27316
+ }
27317
+ );
27318
+ }
27319
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
25908
27320
  const gated = this.#isFecTrack(ownerPacketId);
25909
27321
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
25910
27322
  if (assembler) {
@@ -27525,6 +28937,7 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
27525
28937
  stalls: 0,
27526
28938
  concealedBlocks: 0,
27527
28939
  concealedGaps: 0,
28940
+ undelimitedRunGaps: 0,
27528
28941
  concealedFrames: 0,
27529
28942
  concealedAudioMs: 0,
27530
28943
  vanishedBlocks: 0
@@ -27631,6 +29044,12 @@ function isNonNegativeSafeInteger(value) {
27631
29044
  function isSymbolCounts(value) {
27632
29045
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
27633
29046
  }
29047
+ function isSpanFailure(value) {
29048
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
29049
+ const length = value["length"];
29050
+ const sources = value["sources"];
29051
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
29052
+ }
27634
29053
  function isNullableNonNegative(value) {
27635
29054
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
27636
29055
  }
@@ -27650,7 +29069,10 @@ function isRepairLifecycleEvent(value) {
27650
29069
  case "recovered":
27651
29070
  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"]);
27652
29071
  case "failed":
27653
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
29072
+ return hasExactKeys(
29073
+ value,
29074
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
29075
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
27654
29076
  case "repair-preempted":
27655
29077
  case "repair-deferred":
27656
29078
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -27859,6 +29281,8 @@ var MulticastManager = class {
27859
29281
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
27860
29282
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
27861
29283
  #repairReleases = /* @__PURE__ */ new Map();
29284
+ /** Protected repair flows owned by each live repair-endpoint release. */
29285
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
27862
29286
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
27863
29287
  #overlayBindings = /* @__PURE__ */ new Map();
27864
29288
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -27916,7 +29340,7 @@ var MulticastManager = class {
27916
29340
  onPublisherRestart: (packetId, catalogTrackName) => {
27917
29341
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
27918
29342
  },
27919
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
29343
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
27920
29344
  const pathCount = this.#fec.blockPathCount(
27921
29345
  sbn,
27922
29346
  packetId,
@@ -27934,7 +29358,8 @@ var MulticastManager = class {
27934
29358
  symbols: {
27935
29359
  multicast: pathCount?.multicastSymbols ?? 0,
27936
29360
  moq: pathCount?.moqSymbols ?? 0
27937
- }
29361
+ },
29362
+ ...span === void 0 ? {} : { span }
27938
29363
  });
27939
29364
  },
27940
29365
  onFrameGap: (decision) => {
@@ -28019,9 +29444,17 @@ var MulticastManager = class {
28019
29444
  reason
28020
29445
  });
28021
29446
  };
29447
+ this.#fec.onUndelimitedRunGap = (packetId, catalogTrackName) => {
29448
+ this.#statsFor(packetId, catalogTrackName).undelimitedRunGaps++;
29449
+ };
28022
29450
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
28023
29451
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
28024
29452
  };
29453
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
29454
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
29455
+ if (binding === void 0) return void 0;
29456
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
29457
+ };
28025
29458
  this.#fec.onDecoderUnavailable = (event) => {
28026
29459
  this.#emitRepairLifecycle({
28027
29460
  version: 2,
@@ -28524,6 +29957,9 @@ var MulticastManager = class {
28524
29957
  this.#transport.onFailback((reason) => {
28525
29958
  const joined = this.#provenanceJoin;
28526
29959
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
29960
+ for (const flows of this.#repairProvenanceFlows.values()) {
29961
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
29962
+ }
28527
29963
  this.#onFailback?.(reason);
28528
29964
  });
28529
29965
  }
@@ -28558,6 +29994,12 @@ var MulticastManager = class {
28558
29994
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
28559
29995
  );
28560
29996
  }
29997
+ if (provenanceFlow !== void 0) {
29998
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
29999
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
30000
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
30001
+ }
30002
+ }
28561
30003
  const staged = this.#renditionSwitch;
28562
30004
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
28563
30005
  this.configureFec(config);
@@ -28565,8 +30007,8 @@ var MulticastManager = class {
28565
30007
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
28566
30008
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
28567
30009
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
28568
- this.#releaseProvenanceJoin();
28569
30010
  const provenance = config.provenance;
30011
+ this.#releaseProvenanceJoin();
28570
30012
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
28571
30013
  const ingress = protectedTracks === void 0 ? void 0 : {
28572
30014
  tracks: Object.freeze(
@@ -28619,8 +30061,13 @@ var MulticastManager = class {
28619
30061
  * feeds the flow's receiver; media datagrams are held until one admits them.
28620
30062
  */
28621
30063
  #joinProvenance(provenance, ingress) {
30064
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
30065
+ this.#hookFailback();
30066
+ this.#provenanceJoin = { flow: ingress.flow };
30067
+ }
30068
+ #provenanceReceiver(provenance) {
28622
30069
  const { flow, auth } = provenance;
28623
- const receiver = new BcProvenanceV2Receiver({
30070
+ return new BcProvenanceV2Receiver({
28624
30071
  ...provenance.receiver,
28625
30072
  // The caller's ctx when it passes one, else the catalog's: an explicit
28626
30073
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -28637,9 +30084,6 @@ var MulticastManager = class {
28637
30084
  maxAuthDelayMs: flow.maxAuthDelayMs,
28638
30085
  manifestTimerMs: flow.manifestTimerMs
28639
30086
  });
28640
- this.#router.registerProvenanceFlow(ingress, receiver);
28641
- this.#hookFailback();
28642
- this.#provenanceJoin = { flow: ingress.flow };
28643
30087
  }
28644
30088
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
28645
30089
  #releaseProvenanceJoin() {
@@ -28670,8 +30114,25 @@ var MulticastManager = class {
28670
30114
  * callback delivers must come from a subscription opened on
28671
30115
  * `options.gateway`. A callback that also merges another source (a MoQ or
28672
30116
  * WebSocket repair feed) must not name a native provider here.
30117
+ *
30118
+ * An endpoint's `provenance` makes its group a protected flow of its own
30119
+ * (multicast-02 7.2.7), registered here and released with the group; its
30120
+ * records ride in band on the group's port. On the user-agent path a
30121
+ * flow-less repair group of a protected track is set aside, never read, so
30122
+ * a player joining a protected catalog's repair groups passes it.
28673
30123
  */
28674
30124
  joinRepairEndpoints(endpoints, provider, options) {
30125
+ for (const { provenance, flow, source, group, port: port2 } of endpoints) {
30126
+ if (provenance === void 0) continue;
30127
+ if (flow !== void 0) {
30128
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
30129
+ }
30130
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port2 !== provenance.flow.port) {
30131
+ throw new RangeError(
30132
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
30133
+ );
30134
+ }
30135
+ }
28675
30136
  const releases = [];
28676
30137
  let released = false;
28677
30138
  const safely = (each) => {
@@ -28681,17 +30142,36 @@ var MulticastManager = class {
28681
30142
  console.warn("[MulticastManager] repair group release failed", error);
28682
30143
  }
28683
30144
  };
30145
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
30146
+ const preparedProvenance = endpoints.map((endpoint) => {
30147
+ if (endpoint.provenance === void 0) return void 0;
30148
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
30149
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
30150
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
30151
+ }
30152
+ usedFlows.add(flow);
30153
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
30154
+ });
30155
+ const provenanceFlows = [];
28684
30156
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
28685
30157
  ...owner,
28686
30158
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
28687
30159
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
28688
30160
  }));
28689
30161
  this.#applyRepairOwners(repairOwners);
28690
- for (const endpoint of endpoints) {
30162
+ for (const [index, endpoint] of endpoints.entries()) {
30163
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
28691
30164
  const ingress = {
28692
30165
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
28693
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
30166
+ ...flow === void 0 ? {} : { flow }
28694
30167
  };
30168
+ if (endpoint.provenance !== void 0) {
30169
+ const prepared = preparedProvenance[index];
30170
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
30171
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
30172
+ provenanceFlows.push(prepared.flow);
30173
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
30174
+ }
28695
30175
  let sender;
28696
30176
  const feed = (packet, sourceAddress, ingressToFeed) => {
28697
30177
  if (released) return;
@@ -28721,7 +30201,7 @@ var MulticastManager = class {
28721
30201
  packetIds: endpoint.packetIds,
28722
30202
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
28723
30203
  // A protected repair group's records ride in band on its port (7.2.3).
28724
- ...endpoint.flow === void 0 ? {} : { protected: true }
30204
+ ...flow === void 0 ? {} : { protected: true }
28725
30205
  }, ingress).then((joined) => {
28726
30206
  if (!joined && !released) fail(transport.lastJoinOutcome);
28727
30207
  });
@@ -28730,9 +30210,12 @@ var MulticastManager = class {
28730
30210
  if (released) return;
28731
30211
  released = true;
28732
30212
  this.#repairReleases.delete(release);
30213
+ this.#repairProvenanceFlows.delete(release);
28733
30214
  for (const each of releases.splice(0)) safely(each);
28734
30215
  };
28735
30216
  this.#repairReleases.set(release, repairOwners);
30217
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
30218
+ if (provenanceFlows.length) this.#hookFailback();
28736
30219
  return release;
28737
30220
  }
28738
30221
  #applyRepairOwners(owners) {
@@ -29218,7 +30701,8 @@ var MulticastManager = class {
29218
30701
  blockProfile: parseFecBlockProfile(
29219
30702
  geometry2.blockProfile,
29220
30703
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
29221
- )
30704
+ ),
30705
+ geometry: geometry2
29222
30706
  });
29223
30707
  }
29224
30708
  }
@@ -29257,7 +30741,7 @@ var MulticastManager = class {
29257
30741
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
29258
30742
  const before = this.#overlayBindings.get(sourcePacketId);
29259
30743
  const after = overlayBindings.get(sourcePacketId);
29260
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
30744
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
29261
30745
  if (!same) install.dispose();
29262
30746
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
29263
30747
  else install.reattach();
@@ -29314,10 +30798,12 @@ var MulticastManager = class {
29314
30798
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
29315
30799
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
29316
30800
  * pending hole and reported here, and `closeIsoHoles` must be called for it
29317
- * once its range FETCH ends (or none is sent).
30801
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
30802
+ * pending hole the stream runs past the locator's horizon: returning true,
30803
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
29318
30804
  */
29319
- onUndelimitedLoss(cb) {
29320
- this.#fec.setUndelimitedLossHandler(cb);
30805
+ onUndelimitedLoss(cb, onExpired) {
30806
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
29321
30807
  }
29322
30808
  /**
29323
30809
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -29553,7 +31039,8 @@ var MulticastManager = class {
29553
31039
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
29554
31040
  ...event,
29555
31041
  block: Object.freeze({ ...event.block }),
29556
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
31042
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
31043
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
29557
31044
  }
29558
31045
  );
29559
31046
  if (this.#logRepairLifecycle) {
@@ -29666,7 +31153,7 @@ async function setupFecWorkerForTrack(opts) {
29666
31153
  blockProfile,
29667
31154
  k: opts.fecK,
29668
31155
  // P as this receiver joined it, not the catalog total: the worker snapshot
29669
- // and CMCD `x-bc-fec-p` are read from this. Identity on a single layer.
31156
+ // and CMCD `com.blockcast-fp` are read from this. Identity on a single layer.
29670
31157
  repairCount: opts.joinedRepairCount ?? opts.fecRepairCount,
29671
31158
  symbolSize: opts.fecSymbolSize,
29672
31159
  interleaveDepth: interleaveDepthBlocks,
@@ -30208,24 +31695,24 @@ var MediaRouter = class {
30208
31695
  if (!this.#multicastVideoKeyed) return;
30209
31696
  if (this.#requireAudio && !this.#multicastAudioReceived) return;
30210
31697
  if (this.#requireAudio && !this.#moqAudioWarmed) return;
30211
- const token = ++this.#sourceSwitchToken;
31698
+ const token2 = ++this.#sourceSwitchToken;
30212
31699
  const maybeReady = this.#onSourceSwitch?.("multicast");
30213
31700
  if (!maybeReady || typeof maybeReady.then !== "function") {
30214
- this.#commitMulticastActivation(token);
31701
+ this.#commitMulticastActivation(token2);
30215
31702
  return;
30216
31703
  }
30217
31704
  const ready = Promise.resolve(maybeReady);
30218
- this.#pendingMulticastToken = token;
31705
+ this.#pendingMulticastToken = token2;
30219
31706
  this.#sourceSwitchReady = ready;
30220
31707
  void ready.then(
30221
- () => this.#commitMulticastActivation(token),
30222
- (err) => this.#rejectMulticastActivation(token, err)
31708
+ () => this.#commitMulticastActivation(token2),
31709
+ (err) => this.#rejectMulticastActivation(token2, err)
30223
31710
  ).finally(() => {
30224
31711
  if (this.#sourceSwitchReady === ready) this.#sourceSwitchReady = null;
30225
31712
  });
30226
31713
  }
30227
- #commitMulticastActivation(token) {
30228
- if (token !== this.#sourceSwitchToken) return;
31714
+ #commitMulticastActivation(token2) {
31715
+ if (token2 !== this.#sourceSwitchToken) return;
30229
31716
  this.#active = "multicast";
30230
31717
  this.#suppressed = true;
30231
31718
  this.#pendingMulticastToken = null;
@@ -30236,9 +31723,9 @@ var MediaRouter = class {
30236
31723
  if (video) this.#onVideoFrame?.(video.data, video.meta);
30237
31724
  if (audio) this.#onAudioFrame?.(audio.data, audio.meta);
30238
31725
  }
30239
- #rejectMulticastActivation(token, err) {
30240
- if (token !== this.#sourceSwitchToken) return;
30241
- if (this.#pendingMulticastToken === token) this.#pendingMulticastToken = null;
31726
+ #rejectMulticastActivation(token2, err) {
31727
+ if (token2 !== this.#sourceSwitchToken) return;
31728
+ if (this.#pendingMulticastToken === token2) this.#pendingMulticastToken = null;
30242
31729
  this.#pendingMulticastVideo = null;
30243
31730
  this.#pendingMulticastAudio = null;
30244
31731
  console.warn("[MediaRouter] onSourceSwitch(multicast) failed", err);
@@ -31207,63 +32694,65 @@ var FecStarvationDetector = class {
31207
32694
 
31208
32695
  // src/cmcd-producer.ts
31209
32696
  var PLAY_MODES = ["full", "base-only", "single-track"];
31210
- function sanitize(value) {
31211
- return value.replace(/[,\r\n]/g, "");
31212
- }
31213
- function buildFecParams(stats) {
31214
- const params = {};
31215
- const cfg = stats.config;
31216
- params["x-bc-fec-algo"] = cfg.algorithm;
31217
- params["x-bc-fec-k"] = cfg.k;
31218
- params["x-bc-fec-p"] = cfg.repairCount;
31219
- params["x-bc-fec-recovery"] = parseFloat((stats.recoveryRate / 100).toFixed(4));
31220
- return params;
31221
- }
31222
- function buildTransportParams(snap) {
31223
- if (!snap) return {};
31224
- const params = {};
31225
- params["x-bc-transport"] = snap.transport;
31226
- if (snap.multicastGroup != null) {
31227
- params["x-bc-multicast-group"] = snap.multicastGroup;
31228
- }
31229
- if (snap.multicastSource != null) {
31230
- params["x-bc-multicast-source"] = snap.multicastSource;
31231
- }
31232
- if (snap.amtRelay != null) {
31233
- params["x-bc-amt-relay"] = snap.amtRelay;
31234
- }
31235
- return params;
31236
- }
31237
- function formatQueryString(params) {
31238
- return Object.keys(params).sort().map((key) => {
31239
- const v = params[key];
31240
- if (typeof v === "string") return `${key}=${sanitize(v)}`;
31241
- return `${key}=${v}`;
32697
+ var DEFAULT_INTERVAL_MS = 3e4;
32698
+ var CUSTOM_PREFIX = "com.blockcast-";
32699
+ var MAX_CUSTOM_VALUE = 64;
32700
+ var TRANSPORT_TOKEN = {
32701
+ native: "ssm",
32702
+ amt: "amt",
32703
+ moq: "moq"
32704
+ };
32705
+ function sfString(value) {
32706
+ return `"${value.replace(/[^\x20-\x7e]/g, "").replace(/[\\"]/g, "\\$&")}"`;
32707
+ }
32708
+ function encodeCmcdRecord(record) {
32709
+ return Object.keys(record).sort().map((key) => {
32710
+ const value = record[key];
32711
+ if (typeof value === "number") return `${key}=${value}`;
32712
+ if (typeof value === "string") return `${key}=${sfString(value)}`;
32713
+ if (Array.isArray(value)) return `${key}=(${value.map(sfString).join(" ")})`;
32714
+ return `${key}=${value.token}`;
31242
32715
  }).join(",");
31243
32716
  }
32717
+ var token = (value) => ({ token: value });
32718
+ function putCustom(record, name, value) {
32719
+ if (value === void 0) return;
32720
+ if (typeof value === "number") value = String(value);
32721
+ if (typeof value === "string" && value.length > MAX_CUSTOM_VALUE) return;
32722
+ record[CUSTOM_PREFIX + name] = value;
32723
+ }
31244
32724
  var CmcdProducer = class {
31245
- #onCmcdParams;
31246
32725
  #onCmcdPost;
32726
+ #intervalMs;
32727
+ #sessionId;
32728
+ #now;
32729
+ #sn = 0;
32730
+ #lastHeartbeat = null;
31247
32731
  #transport;
31248
32732
  #lastStats;
31249
- // Phase 14 state — Plan 03 Task 2 (D-12, D-15).
31250
32733
  #playMode = null;
31251
32734
  #deltaFailRate = null;
31252
32735
  #switchMiscount = 0;
31253
32736
  #manifestStats = null;
31254
32737
  #fecFailClosed = null;
32738
+ /** Video-block resolutions from the repair lifecycle; null until the player feeds one. */
32739
+ #lifecycle = null;
31255
32740
  constructor(options) {
31256
- this.#onCmcdParams = options.onCmcdParams;
31257
32741
  this.#onCmcdPost = options.onCmcdPost;
32742
+ this.#intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
32743
+ if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {
32744
+ throw new Error(`[CmcdProducer] invalid intervalMs "${String(options.intervalMs)}"; expected a positive number`);
32745
+ }
32746
+ this.#sessionId = options.sessionId ?? globalThis.crypto.randomUUID();
32747
+ this.#now = options.now ?? Date.now;
31258
32748
  }
31259
32749
  /** Update the stored transport state. Called by player wiring layer. */
31260
32750
  updateTransport(snapshot) {
31261
32751
  this.#transport = snapshot;
31262
32752
  }
31263
32753
  /**
31264
- * Set the current play-mode. Emitted as `x-bc-play-mode` on subsequent
31265
- * snapshots. Throws on any value outside {'full','base-only','single-track'}
31266
- * (CLAUDE.md: error on bad init).
32754
+ * Set the current play-mode, reported as `com.blockcast-pm`. Throws on any
32755
+ * value outside {'full','base-only','single-track'} (CLAUDE.md: error on bad init).
31267
32756
  */
31268
32757
  updatePlayMode(mode) {
31269
32758
  if (typeof mode !== "string" || !PLAY_MODES.includes(mode)) {
@@ -31274,9 +32763,8 @@ var CmcdProducer = class {
31274
32763
  this.#playMode = mode;
31275
32764
  }
31276
32765
  /**
31277
- * Set the delta-track FEC block-failure rate (0..1 inclusive). Emitted as
31278
- * `x-bc-delta-fail-rate` on snapshots when play-mode is 'full' or 'base-only'.
31279
- * Omitted on single-track streams.
32766
+ * Set the delta-track FEC block-failure rate (0..1 inclusive), reported as
32767
+ * `com.blockcast-dfr` when play-mode is 'full' or 'base-only'.
31280
32768
  */
31281
32769
  updateDeltaFailRate(rate) {
31282
32770
  if (typeof rate !== "number" || !Number.isFinite(rate) || rate < 0 || rate > 1) {
@@ -31286,112 +32774,139 @@ var CmcdProducer = class {
31286
32774
  }
31287
32775
  this.#deltaFailRate = rate;
31288
32776
  }
31289
- /**
31290
- * Bump the cumulative switching-set misalignment counter. Emitted as
31291
- * `x-bc-switch-miscount` on snapshots when the counter is > 0.
31292
- */
32777
+ /** Bump the cumulative switching-set misalignment counter (`com.blockcast-sm`). */
31293
32778
  incrementSwitchMiscount() {
31294
32779
  this.#switchMiscount += 1;
31295
32780
  }
31296
32781
  /**
31297
- * Record that FEC failed closed at runtime (fec-01 6.3.9). Every later
31298
- * snapshot carries `x-bc-fec-fail-closed` (the reason code) and
31299
- * `x-bc-fec-fail-layer` (the held layer i whose total B_i was undercut), so a
31300
- * stream playing without FEC is told apart from one with no loss.
32782
+ * Record that FEC failed closed at runtime (fec-01 6.3.9). Reported at once
32783
+ * as `e=e` with the reason code in `ec`, and on every later counter report
32784
+ * as `com.blockcast-ffc` / `com.blockcast-ffl` (the held layer whose total
32785
+ * B_i was undercut), so a stream playing without FEC is told apart from one
32786
+ * with no loss.
31301
32787
  */
31302
32788
  updateFecFailClosed(reason) {
32789
+ const changed = this.#fecFailClosed?.code !== reason.code || this.#fecFailClosed?.layer !== reason.layer;
31303
32790
  this.#fecFailClosed = reason;
32791
+ if (changed) this.#post([{ ...this.#base("e"), ec: [reason.code] }]);
31304
32792
  }
31305
32793
  updateManifestVerification(stats) {
31306
32794
  this.#manifestStats = stats;
31307
32795
  }
31308
32796
  /**
31309
- * One-shot emit of `x-bc-switch-drift-us` for a single misalignment event.
31310
- * Does NOT mutate snapshot state — subsequent onSnapshot() calls will not
31311
- * include the drift key until the next emitSwitchDrift(). Mirrors the
31312
- * existing onTransition() pattern.
32797
+ * Count a video block's resolution from the repair lifecycle: recovered in
32798
+ * band (`com.blockcast-fbr`), recovered by repair FETCH (`-fbq`), or failed
32799
+ * as a keyframe-class block (`-fbfk`). Audio blocks are not counted, matching
32800
+ * the video-track `-fbf`. Until the player feeds this, the three are absent.
31313
32801
  */
32802
+ onRepairLifecycle(event) {
32803
+ this.#lifecycle ??= { inband: 0, fetch: 0, failedKeyframe: 0 };
32804
+ if (event.type === "recovered" && event.blockClass !== "audio") {
32805
+ if (event.via === "inband") this.#lifecycle.inband++;
32806
+ else this.#lifecycle.fetch++;
32807
+ } else if (event.type === "failed" && event.blockClass === "keyframe") {
32808
+ this.#lifecycle.failedKeyframe++;
32809
+ }
32810
+ }
32811
+ /** One-shot custom event `com.blockcast-switch-drift` for a single misalignment. */
31314
32812
  emitSwitchDrift(driftUs) {
31315
32813
  if (typeof driftUs !== "number" || !Number.isFinite(driftUs) || driftUs < 0) {
31316
32814
  throw new Error(
31317
32815
  `[CmcdProducer] invalid drift-us "${String(driftUs)}"; expected a non-negative finite number`
31318
32816
  );
31319
32817
  }
31320
- const params = {};
31321
- if (this.#lastStats) Object.assign(params, buildFecParams(this.#lastStats));
31322
- Object.assign(params, buildTransportParams(this.#transport));
31323
- if (this.#switchMiscount > 0) params["x-bc-switch-miscount"] = this.#switchMiscount;
31324
- params["x-bc-switch-drift-us"] = driftUs;
31325
- this.#emit(params);
32818
+ const record = { ...this.#base("ce"), cen: CUSTOM_PREFIX + "switch-drift" };
32819
+ putCustom(record, "sdu", Math.round(driftUs));
32820
+ this.#post([record]);
31326
32821
  }
31327
- /**
31328
- * Process a FecTrackStats snapshot. Finds the video track, builds
31329
- * x-bc-* vendor keys, and fires both delivery callbacks.
31330
- */
32822
+ /** Take a FecTrackStats snapshot (first video track) and send the heartbeat when due. */
31331
32823
  onSnapshot(data) {
31332
32824
  const videoTrack = data.tracks.find((t) => t.config.trackType === "video");
31333
32825
  if (!videoTrack) return;
31334
32826
  this.#lastStats = videoTrack;
31335
- const params = {
31336
- ...buildFecParams(videoTrack),
31337
- ...buildTransportParams(this.#transport)
31338
- };
31339
- if (this.#playMode !== null) {
31340
- params["x-bc-play-mode"] = this.#playMode;
31341
- }
31342
- if (this.#fecFailClosed) {
31343
- params["x-bc-fec-fail-closed"] = this.#fecFailClosed.code;
31344
- params["x-bc-fec-fail-layer"] = this.#fecFailClosed.layer;
31345
- }
31346
- if (this.#playMode !== null && this.#playMode !== "single-track" && this.#deltaFailRate !== null) {
31347
- params["x-bc-delta-fail-rate"] = parseFloat(this.#deltaFailRate.toFixed(4));
31348
- }
31349
- if (this.#switchMiscount > 0) {
31350
- params["x-bc-switch-miscount"] = this.#switchMiscount;
31351
- }
31352
- if (this.#manifestStats) {
31353
- params["x-bc-manifest-verified"] = this.#manifestStats.verified > 0;
31354
- params["x-bc-manifest-failures"] = Object.values(this.#manifestStats.failures).reduce((total, count) => total + count, 0);
31355
- }
31356
- this.#emit(params);
32827
+ this.#heartbeat();
31357
32828
  }
31358
32829
  /**
31359
- * Emit transport state without inventing FEC metrics. Cadence is owned by
31360
- * the caller because only the transport integration knows when state changed.
32830
+ * Take transport state for receivers that do not own FEC stats, and send the
32831
+ * heartbeat when due.
31361
32832
  */
31362
32833
  onTransportSnapshot(data) {
31363
32834
  if (!Number.isFinite(data.timestampMs) || data.timestampMs < 0) {
31364
32835
  throw new Error("[CmcdProducer] transport snapshot timestamp must be a non-negative finite number");
31365
32836
  }
31366
32837
  if (data.playMode !== void 0) this.updatePlayMode(data.playMode);
31367
- if (data.switchMiscount !== void 0 && (!Number.isSafeInteger(data.switchMiscount) || data.switchMiscount < 0)) {
31368
- throw new Error("[CmcdProducer] transport snapshot switch-miscount must be a non-negative safe integer");
32838
+ if (data.switchMiscount !== void 0) {
32839
+ if (!Number.isSafeInteger(data.switchMiscount) || data.switchMiscount < 0) {
32840
+ throw new Error("[CmcdProducer] transport snapshot switch-miscount must be a non-negative safe integer");
32841
+ }
32842
+ this.#switchMiscount = data.switchMiscount;
31369
32843
  }
31370
32844
  this.#transport = data.transport;
31371
- const params = buildTransportParams(data.transport);
31372
- if (this.#playMode !== null) params["x-bc-play-mode"] = this.#playMode;
31373
- const switchMiscount = data.switchMiscount ?? this.#switchMiscount;
31374
- if (switchMiscount > 0) params["x-bc-switch-miscount"] = switchMiscount;
31375
- this.#emit(params);
32845
+ this.#heartbeat();
31376
32846
  }
31377
- /**
31378
- * Signal a transport transition event. Fires an immediate out-of-band
31379
- * emit with x-bc-ct set. The subsequent onSnapshot() will NOT include
31380
- * x-bc-ct (one-shot).
31381
- */
32847
+ /** Report a transport transition at once, as custom event `com.blockcast-ct`. */
31382
32848
  onTransition(event) {
31383
- const params = {};
31384
- if (this.#lastStats) {
31385
- Object.assign(params, buildFecParams(this.#lastStats));
32849
+ const record = { ...this.#base("ce"), cen: CUSTOM_PREFIX + "ct" };
32850
+ putCustom(record, "ct", token(event));
32851
+ this.#putTransport(record);
32852
+ this.#post([record]);
32853
+ }
32854
+ #base(event) {
32855
+ return { e: token(event), sid: this.#sessionId, sn: this.#sn++, ts: Math.floor(this.#now()), v: 2 };
32856
+ }
32857
+ #heartbeat() {
32858
+ const now = this.#now();
32859
+ if (this.#lastHeartbeat !== null && now - this.#lastHeartbeat < this.#intervalMs) return;
32860
+ this.#lastHeartbeat = now;
32861
+ this.#post([this.#base("t"), this.#counters()]);
32862
+ }
32863
+ #putTransport(record) {
32864
+ const snap = this.#transport;
32865
+ if (!snap) return;
32866
+ putCustom(record, "tr", token(TRANSPORT_TOKEN[snap.transport]));
32867
+ if (snap.multicastGroup != null && snap.multicastSource != null) {
32868
+ putCustom(record, "sg", `${snap.multicastGroup}@${snap.multicastSource}`);
32869
+ }
32870
+ putCustom(record, "ar", snap.amtRelay);
32871
+ }
32872
+ /** The `e=ce` counter report. */
32873
+ #counters() {
32874
+ const record = { ...this.#base("ce"), cen: CUSTOM_PREFIX + "fec" };
32875
+ const stats = this.#lastStats;
32876
+ if (stats) {
32877
+ putCustom(record, "fa", stats.config.algorithm);
32878
+ putCustom(record, "fk", stats.config.k);
32879
+ putCustom(record, "fp", stats.config.repairCount);
32880
+ putCustom(record, "pr", stats.sourceSymbols);
32881
+ putCustom(record, "pl", stats.sourcePacketsMissing);
32882
+ putCustom(record, "pu", stats.sourcePacketsUnrecovered);
32883
+ putCustom(record, "fbf", stats.blocksFailed);
32884
+ }
32885
+ if (this.#lifecycle) {
32886
+ putCustom(record, "fbr", this.#lifecycle.inband);
32887
+ putCustom(record, "fbq", this.#lifecycle.fetch);
32888
+ putCustom(record, "fbfk", this.#lifecycle.failedKeyframe);
32889
+ }
32890
+ this.#putTransport(record);
32891
+ if (this.#playMode !== null) {
32892
+ putCustom(record, "pm", token(this.#playMode));
32893
+ if (this.#playMode !== "single-track" && this.#deltaFailRate !== null) {
32894
+ putCustom(record, "dfr", this.#deltaFailRate.toFixed(3));
32895
+ }
32896
+ }
32897
+ if (this.#fecFailClosed) {
32898
+ putCustom(record, "ffc", token(this.#fecFailClosed.code));
32899
+ putCustom(record, "ffl", this.#fecFailClosed.layer);
31386
32900
  }
31387
- Object.assign(params, buildTransportParams(this.#transport));
31388
- params["x-bc-ct"] = event;
31389
- this.#emit(params);
32901
+ if (this.#switchMiscount > 0) putCustom(record, "sm", this.#switchMiscount);
32902
+ if (this.#manifestStats) {
32903
+ putCustom(record, "mv", this.#manifestStats.verified);
32904
+ putCustom(record, "mf", Object.values(this.#manifestStats.failures).reduce((a, b) => a + b, 0));
32905
+ }
32906
+ return record;
31390
32907
  }
31391
- /** Fire both delivery callbacks with the given params. */
31392
- #emit(params) {
31393
- this.#onCmcdParams?.(params);
31394
- this.#onCmcdPost?.(formatQueryString(params));
32908
+ #post(records) {
32909
+ this.#onCmcdPost?.(records.map(encodeCmcdRecord).join("\n"));
31395
32910
  }
31396
32911
  };
31397
32912
 
@@ -31487,6 +33002,19 @@ function resolveRepairLayers(catalog, source) {
31487
33002
  totalBaseRepairSymbols: binding.totalBaseRepairSymbols
31488
33003
  };
31489
33004
  }
33005
+ function valueAt(catalog, pointer) {
33006
+ let node = catalog;
33007
+ for (const segment of pointer.split("/").slice(1)) {
33008
+ if (typeof node !== "object" || node === null) return void 0;
33009
+ node = node[segment.replace(/~1/g, "/").replace(/~0/g, "~")];
33010
+ }
33011
+ return node;
33012
+ }
33013
+ function catalogTrackDeliveryMode(catalog, source) {
33014
+ const binding = bindingOf(catalog, source);
33015
+ const entry = binding ? valueAt(catalog, binding.pointer) : void 0;
33016
+ return entry?.deliveryMode === "stream" ? "stream" : "datagram";
33017
+ }
31490
33018
  function moqtPriority2(value) {
31491
33019
  return Number.isSafeInteger(value) && value >= 0 && value <= 255 ? value : null;
31492
33020
  }
@@ -31530,6 +33058,7 @@ function fecParams(catalog, track, fps, sampleRate) {
31530
33058
  repairTrackName: base.repairTrack,
31531
33059
  repairLayers: repair.baseLayers,
31532
33060
  repairOverlays: repair.overlays,
33061
+ deliveryMode: catalogTrackDeliveryMode(catalog, track),
31533
33062
  ...mediaRate
31534
33063
  };
31535
33064
  }
@@ -32054,7 +33583,7 @@ var RepairLayerSubscriptions = class {
32054
33583
  * or interleaved sequences read as loss.
32055
33584
  */
32056
33585
  noteSourceSequence(seq) {
32057
- if (this.#disposed || this.#opts.delivery === "stream") return;
33586
+ if (this.#disposed || this.#delivery() === "stream") return;
32058
33587
  seq >>>= 0;
32059
33588
  if (this.#lastSeq === void 0) {
32060
33589
  this.#lastSeq = seq;
@@ -32087,12 +33616,12 @@ var RepairLayerSubscriptions = class {
32087
33616
  this.#expected = 0;
32088
33617
  this.#lost = 0;
32089
33618
  this.#wantFewer = 0;
32090
- this.#layerCount = Math.min(this.#layerCount, this.#layers().length);
33619
+ this.#layerCount = this.#delivery() === "stream" ? 0 : Math.min(this.#layerCount, this.#layers().length);
32091
33620
  this.#reconcile();
32092
33621
  }
32093
33622
  snapshot() {
32094
33623
  return {
32095
- delivery: this.#opts.delivery,
33624
+ delivery: this.#delivery(),
32096
33625
  layerCount: this.#layerCount,
32097
33626
  subscribedTracks: [...this.#subs.keys()],
32098
33627
  repairPackets: this.#repairPackets,
@@ -32106,6 +33635,9 @@ var RepairLayerSubscriptions = class {
32106
33635
  this.#closeAll();
32107
33636
  this.#disposed = true;
32108
33637
  }
33638
+ #delivery() {
33639
+ return this.#source.deliveryMode === "stream" ? "stream" : "datagram";
33640
+ }
32109
33641
  #layers() {
32110
33642
  return this.#source.repairLayers ?? [];
32111
33643
  }
@@ -32180,6 +33712,7 @@ var RepairLayerSubscriptions = class {
32180
33712
 
32181
33713
  // src/repair-fetch.ts
32182
33714
  var MOQT_PRIORITY_MAX = 255;
33715
+ var WALK_LEAD_MS = 3;
32183
33716
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
32184
33717
  function isMoqtPriority(value) {
32185
33718
  return Number.isSafeInteger(value) && value >= 0 && value <= MOQT_PRIORITY_MAX;
@@ -32230,8 +33763,17 @@ function wireRepairFetch(mc, opts) {
32230
33763
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
32231
33764
  };
32232
33765
  const clearEntry = (entry) => {
32233
- if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
32234
- else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33766
+ const { range } = entry;
33767
+ if (range) {
33768
+ atReport(range, () => mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, range.holeLength));
33769
+ } else {
33770
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33771
+ }
33772
+ };
33773
+ const atReport = (range, work) => {
33774
+ const fec = mc.fecManager;
33775
+ if (range.groups !== null || fec.withReceiptTime === void 0) work();
33776
+ else fec.withReceiptTime(range.reportedAt, work);
32235
33777
  };
32236
33778
  const releaseHold = (entry) => {
32237
33779
  if (entry.range) return;
@@ -32243,7 +33785,7 @@ function wireRepairFetch(mc, opts) {
32243
33785
  if (!run) return;
32244
33786
  entry.running = null;
32245
33787
  run.stopped = reason;
32246
- run.controller.abort();
33788
+ run.controller.abort(reason);
32247
33789
  if (reason === "preempted") releaseHold(entry);
32248
33790
  mc.noteRepairStopped?.(reason, entry.sbn, entry.packetId, entry.catalogTrackName);
32249
33791
  };
@@ -32298,21 +33840,42 @@ function wireRepairFetch(mc, opts) {
32298
33840
  const admit = (entry, now) => {
32299
33841
  const budgetMs = entry.deadlineAt - now;
32300
33842
  const rttMs = readRtt();
32301
- const reason = !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < budgetMs ? null : "rtt-exceeds-budget";
33843
+ const reason = refusal(entry, now, rttMs);
32302
33844
  if (reason === null) return rttMs;
32303
33845
  skip(entry, reason, rttMs, budgetMs);
32304
33846
  return null;
32305
33847
  };
33848
+ 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";
32306
33849
  const retire = (entry) => {
32307
33850
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
32308
33851
  if (entry.expiry !== void 0) clearTimeout(entry.expiry);
32309
33852
  };
32310
- const outstandingBelow = (priority) => {
33853
+ const holdsBack = (entry, priority, videoWalks = true) => {
33854
+ if (entry.priority >= priority) return false;
33855
+ const { walk } = entry;
33856
+ if (walk === void 0) return true;
33857
+ if (entry.priority !== 0 || !videoWalks) return false;
33858
+ return entry.running === null || walk.group !== null && !walk.group.controller.signal.aborted;
33859
+ };
33860
+ const outstandingBelow = (priority, videoWalks = true) => {
32311
33861
  for (const entry of entries.values()) {
32312
- if (entry.priority < priority) return true;
33862
+ if (holdsBack(entry, priority, videoWalks)) return true;
32313
33863
  }
32314
33864
  return false;
32315
33865
  };
33866
+ const yieldVideoWalks = (queued) => {
33867
+ const now = performance.now();
33868
+ const rttMs = readRtt();
33869
+ const due = queued.some((entry) => entry.priority !== 0 && entry.walk === void 0 && !outstandingBelow(entry.priority, false) && refusal(entry, now, rttMs) === null);
33870
+ if (!due) return;
33871
+ for (const entry of entries.values()) {
33872
+ const walk = entry.walk;
33873
+ if (entry.priority !== 0 || walk === void 0 || walk.group === null) continue;
33874
+ if (walk.group.controller.signal.aborted) continue;
33875
+ walk.yielded = true;
33876
+ walk.group.controller.abort();
33877
+ }
33878
+ };
32316
33879
  const preemptBestEffort = () => {
32317
33880
  for (const entry of entries.values()) {
32318
33881
  if (entry.priority === 0 || !entry.running) continue;
@@ -32341,7 +33904,8 @@ function wireRepairFetch(mc, opts) {
32341
33904
  }
32342
33905
  const rttMs = admit(entry, now);
32343
33906
  if (rttMs === null) return;
32344
- if (entry.priority === 0) preemptBestEffort();
33907
+ if (entry.priority === 0 && entry.walk === void 0) preemptBestEffort();
33908
+ if (entry.range === void 0) leaveWalkedGroup(entry);
32345
33909
  if (counted) entry.attempts++;
32346
33910
  mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
32347
33911
  rttMs,
@@ -32363,6 +33927,14 @@ function wireRepairFetch(mc, opts) {
32363
33927
  }
32364
33928
  void execute(entry, run);
32365
33929
  };
33930
+ const leaveWalkedGroup = (block) => {
33931
+ for (const entry of entries.values()) {
33932
+ const group = entry.walk?.group;
33933
+ if (group?.sbn === block.sbn && entry.packetId === block.packetId && entry.catalogTrackName === block.catalogTrackName) {
33934
+ group.controller.abort();
33935
+ }
33936
+ }
33937
+ };
32366
33938
  const dispatch = () => {
32367
33939
  if (disposed) return;
32368
33940
  const now = performance.now();
@@ -32387,6 +33959,7 @@ function wireRepairFetch(mc, opts) {
32387
33959
  for (const entry of queued) {
32388
33960
  if (entry.priority === 0) start(entry);
32389
33961
  }
33962
+ yieldVideoWalks(queued);
32390
33963
  if (outstandingBelow(1)) return;
32391
33964
  for (const entry of queued) {
32392
33965
  if (entry.priority === 1) start(entry);
@@ -32413,6 +33986,16 @@ function wireRepairFetch(mc, opts) {
32413
33986
  }
32414
33987
  return counts.sources + counts.repairGroupLength >= counts.authoredLength;
32415
33988
  };
33989
+ const groupServed = (sbn, packetId, catalogTrackName) => {
33990
+ if (mc.fecManager.blockSymbolCounts === void 0) return false;
33991
+ const counts = symbolCounts(sbn, packetId, catalogTrackName);
33992
+ if (counts === void 0 || counts.authoredLength === void 0) return true;
33993
+ return counts.sources + counts.repairs >= counts.authoredLength || !groupCanComplete(sbn, packetId, catalogTrackName);
33994
+ };
33995
+ const statedEnd = (sbn, packetId, catalogTrackName) => {
33996
+ const length = symbolCounts(sbn, packetId, catalogTrackName)?.authoredLength;
33997
+ return length === void 0 ? void 0 : serial32Add(sbn, length);
33998
+ };
32416
33999
  const finish = (entry, run, fed, error) => {
32417
34000
  if (run.stopped !== null || entry.running !== run || entries.get(entry.key) !== entry) {
32418
34001
  return;
@@ -32457,27 +34040,81 @@ function wireRepairFetch(mc, opts) {
32457
34040
  signal: run.controller.signal,
32458
34041
  subscriberPriority: entry.subscriberPriority
32459
34042
  };
34043
+ const { range } = entry;
34044
+ const feed = (packet) => {
34045
+ if (entry.catalogTrackName === void 0) {
34046
+ mc.processRepairFromMoQ(packet, entry.packetId);
34047
+ } else {
34048
+ mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
34049
+ }
34050
+ };
32460
34051
  try {
32461
- const packets = entry.range ? opts.rangeTransport({
34052
+ const packets = range === void 0 ? opts.transport({ ...common, sbn: entry.sbn }) : entry.walk !== void 0 ? walkHole(entry, entry.walk, range, common) : opts.rangeTransport({
32462
34053
  ...common,
32463
- startGroup: entry.range.startGroup,
32464
- endGroup: entry.range.endGroup,
32465
- lostSsId: entry.range.lostSsId
32466
- }) : opts.transport({ ...common, sbn: entry.sbn });
34054
+ startGroup: range.groups.startGroup,
34055
+ endGroup: range.groups.endGroup,
34056
+ lostSsId: range.lostSsId
34057
+ });
32467
34058
  for await (const packet of packets) {
32468
34059
  if (run.stopped !== null || entry.running !== run) break;
32469
34060
  fed++;
32470
- if (entry.catalogTrackName === void 0) {
32471
- mc.processRepairFromMoQ(packet, entry.packetId);
32472
- } else {
32473
- mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
32474
- }
34061
+ if (range === void 0) feed(packet);
34062
+ else atReport(range, () => feed(packet));
32475
34063
  }
32476
34064
  finish(entry, run, fed, void 0);
32477
34065
  } catch (error) {
32478
34066
  finish(entry, run, fed, error ?? new Error("repair transport rejected"));
32479
34067
  }
32480
34068
  };
34069
+ async function* walkHole(entry, walk, hole, common) {
34070
+ const lostAt = serial32Distance(entry.sbn, hole.lostSsId);
34071
+ for (let first = true; !common.signal.aborted; first = false) {
34072
+ if (!first && entry.priority !== 0 && outstandingBelow(1)) {
34073
+ stop(entry, "preempted");
34074
+ note("repair-preempted", entry);
34075
+ return;
34076
+ }
34077
+ if (!first && entry.priority === 0) {
34078
+ dispatch();
34079
+ if (common.signal.aborted) return;
34080
+ }
34081
+ const sbn = walk.next;
34082
+ let next;
34083
+ if (entries.get(requestKey(sbn, entry.packetId, entry.catalogTrackName))?.running == null) {
34084
+ const rsIds = /* @__PURE__ */ new Set();
34085
+ const group = new AbortController();
34086
+ const cancel = () => group.abort(common.signal.reason);
34087
+ common.signal.addEventListener("abort", cancel, { once: true });
34088
+ walk.group = { sbn, controller: group };
34089
+ try {
34090
+ for await (const packet of opts.transport({ ...common, sbn, signal: group.signal })) {
34091
+ yield packet;
34092
+ const id = extractRepairFecPayloadId(packet);
34093
+ if (id === null || id.ssStart !== sbn || id.ssbLength === 0) continue;
34094
+ next ??= serial32Add(sbn, id.ssbLength);
34095
+ rsIds.add(id.rsId);
34096
+ if (rsIds.size >= id.rsbLength || groupServed(sbn, entry.packetId, entry.catalogTrackName)) {
34097
+ group.abort();
34098
+ break;
34099
+ }
34100
+ }
34101
+ } catch (error) {
34102
+ if (!group.signal.aborted || common.signal.aborted) throw error;
34103
+ } finally {
34104
+ common.signal.removeEventListener("abort", cancel);
34105
+ walk.group = null;
34106
+ }
34107
+ if (walk.yielded) {
34108
+ walk.yielded = false;
34109
+ continue;
34110
+ }
34111
+ }
34112
+ next ??= statedEnd(sbn, entry.packetId, entry.catalogTrackName);
34113
+ if (next === void 0) return;
34114
+ if (serial32Distance(entry.sbn, next) > lostAt) return;
34115
+ walk.next = next;
34116
+ }
34117
+ }
32481
34118
  const removeResetObserver = mc.addTrackResetObserver((packetId, catalogTrackName) => {
32482
34119
  for (const entry of [...entries.values()]) {
32483
34120
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
@@ -32673,7 +34310,37 @@ function wireRepairFetch(mc, opts) {
32673
34310
  throw error;
32674
34311
  }
32675
34312
  };
32676
- if (opts.rangeTransport !== void 0) {
34313
+ const trackKind = (packetId) => {
34314
+ try {
34315
+ return mc.fecManager.trackKindFor?.(packetId);
34316
+ } catch {
34317
+ return void 0;
34318
+ }
34319
+ };
34320
+ const walkDeadlineAt = (packetId, now, deadlineAt) => {
34321
+ let repairDeadlineMs;
34322
+ try {
34323
+ repairDeadlineMs = mc.fecManager.repairDeadlineMsForPacket?.(packetId);
34324
+ } catch {
34325
+ repairDeadlineMs = void 0;
34326
+ }
34327
+ if (repairDeadlineMs === void 0 || !Number.isFinite(repairDeadlineMs)) return deadlineAt;
34328
+ return Math.min(deadlineAt, now + repairDeadlineMs - WALK_LEAD_MS);
34329
+ };
34330
+ const onHoleExpired = (hole) => {
34331
+ if (disposed) return false;
34332
+ 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);
34333
+ if (entry === void 0) return false;
34334
+ queueMicrotask(() => {
34335
+ if (entries.get(entry.key) !== entry) return;
34336
+ retire(entry);
34337
+ stop(entry, "expired");
34338
+ clearEntry(entry);
34339
+ dispatch();
34340
+ });
34341
+ return true;
34342
+ };
34343
+ if (mc.onUndelimitedLoss !== void 0 && mc.closeIsoHoles !== void 0) {
32677
34344
  mc.onUndelimitedLoss((loss) => {
32678
34345
  const { packetId, catalogTrackName, holeStart, holeLength } = loss;
32679
34346
  const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
@@ -32681,9 +34348,11 @@ function wireRepairFetch(mc, opts) {
32681
34348
  const blockProfile = blockProfileOf(packetId);
32682
34349
  const target = opts.resolveTarget(packetId, catalogTrackName);
32683
34350
  if (!target) return close();
32684
- const priority = repairPriorityForClass("unknown");
32685
- const range = rangeFor(loss, target.repairTrack);
32686
- if (range === null) {
34351
+ const walked = opts.rangeTransport === void 0;
34352
+ const holeClass = walked && trackKind(packetId) === "audio" ? "audio" : "unknown";
34353
+ const priority = repairPriorityForClass(holeClass);
34354
+ const groups = walked ? null : rangeFor(loss, target.repairTrack);
34355
+ if (!walked && groups === null) {
32687
34356
  close();
32688
34357
  mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
32689
34358
  return;
@@ -32694,8 +34363,10 @@ function wireRepairFetch(mc, opts) {
32694
34363
  packetId,
32695
34364
  ...catalogTrackName === void 0 ? {} : { catalogTrackName }
32696
34365
  };
32697
- const wire = wirePriority(identity, "unknown");
32698
- const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
34366
+ const wire = wirePriority(identity, holeClass);
34367
+ if (wire === null) return close();
34368
+ const now = performance.now();
34369
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, now, holeClass);
32699
34370
  if (deadline === null) {
32700
34371
  close();
32701
34372
  mc.noteRepairSkipped(
@@ -32707,6 +34378,7 @@ function wireRepairFetch(mc, opts) {
32707
34378
  );
32708
34379
  return;
32709
34380
  }
34381
+ const deadlineAt = walked ? walkDeadlineAt(packetId, now, deadline.deadlineAt) : deadline.deadlineAt;
32710
34382
  const entry = {
32711
34383
  key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
32712
34384
  ...identity,
@@ -32714,15 +34386,16 @@ function wireRepairFetch(mc, opts) {
32714
34386
  blockProfile,
32715
34387
  priority,
32716
34388
  subscriberPriority: wire.subscriberPriority,
32717
- deadlineAt: deadline.deadlineAt,
32718
- playoutDeadlineAt: deadline.deadlineAt - deadline.extensionMs,
34389
+ deadlineAt,
34390
+ playoutDeadlineAt: deadlineAt - deadline.extensionMs,
32719
34391
  anchorAt: deadline.anchorAt,
32720
34392
  delayMs: deadline.delayMs,
32721
34393
  bound: deadline.bound,
32722
34394
  order: enqueueOrder++,
32723
34395
  attempts: 0,
32724
34396
  running: null,
32725
- range: { ...range, lostSsId: loss.lostSsId, holeLength }
34397
+ range: { lostSsId: loss.lostSsId, holeLength, groups, reportedAt: now },
34398
+ ...walked ? { walk: { next: holeStart, group: null, yielded: false } } : {}
32726
34399
  };
32727
34400
  const previous = entries.get(entry.key);
32728
34401
  if (previous) {
@@ -32732,7 +34405,7 @@ function wireRepairFetch(mc, opts) {
32732
34405
  entries.set(entry.key, entry);
32733
34406
  entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
32734
34407
  dispatch();
32735
- });
34408
+ }, onHoleExpired);
32736
34409
  }
32737
34410
  const removeRapObserver = mc.addRapCompleteObserver?.((packetId) => {
32738
34411
  queueMicrotask(() => {
@@ -32848,6 +34521,7 @@ export {
32848
34521
  catalogGroupDurationMs,
32849
34522
  catalogKeyframeCadenceMs,
32850
34523
  catalogRepairTarget,
34524
+ catalogTrackDeliveryMode,
32851
34525
  catalogTrackFecUnavailable,
32852
34526
  classifyH264Keyframe,
32853
34527
  classifyHevcKeyframe,
@@ -32868,6 +34542,7 @@ export {
32868
34542
  detectH264Keyframe,
32869
34543
  detectHevcKeyframe,
32870
34544
  driftCheck,
34545
+ encodeCmcdRecord,
32871
34546
  encodeDataSegment,
32872
34547
  encodeFecSourceInfo,
32873
34548
  encodeLocTimestamp,
@@ -32944,6 +34619,7 @@ export {
32944
34619
  resolveGroupDurationMs,
32945
34620
  resolveGroupDurationTicks,
32946
34621
  resolveRepairLayers,
34622
+ runtimeFecCatalogReport,
32947
34623
  secondsFromTicks,
32948
34624
  setupFecWorkerForTrack,
32949
34625
  setupTrackPipeline,