@blockcast/mmt-container 2.2.0-main.a88c3a0aa4f3 → 2.2.0-main.aee8d33d2cc8

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 (118) hide show
  1. package/README.md +34 -19
  2. package/dist/block-policy.d.ts +55 -13
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +104 -32
  5. package/dist/block-policy.js.map +2 -2
  6. package/dist/browser-runtime.js +2094 -385
  7. package/dist/browser-runtime.js.map +4 -4
  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 +114 -15
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +639 -95
  30. package/dist/fec-manager.js.map +2 -2
  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 +6 -5
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +12 -2
  40. package/dist/index.js.map +2 -2
  41. package/dist/iso-block-locator.d.ts +48 -13
  42. package/dist/iso-block-locator.d.ts.map +1 -1
  43. package/dist/iso-block-locator.js +97 -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 +12 -19
  51. package/dist/mfu-reassembler.js.map +2 -2
  52. package/dist/mmtp-container-parser.d.ts +106 -12
  53. package/dist/mmtp-container-parser.d.ts.map +1 -1
  54. package/dist/mmtp-container-parser.js +324 -46
  55. package/dist/mmtp-container-parser.js.map +2 -2
  56. package/dist/mmtp-container-parser.no-modules.js +466 -66
  57. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  58. package/dist/mmtp-decode-pipeline.js +323 -46
  59. package/dist/mmtp-decode-pipeline.js.map +2 -2
  60. package/dist/mmtp-fec-session.d.ts +41 -3
  61. package/dist/mmtp-fec-session.d.ts.map +1 -1
  62. package/dist/mmtp-fec-session.js +118 -13
  63. package/dist/mmtp-fec-session.js.map +3 -3
  64. package/dist/mmtp-router.d.ts +36 -8
  65. package/dist/mmtp-router.d.ts.map +1 -1
  66. package/dist/mmtp-router.js +716 -100
  67. package/dist/mmtp-router.js.map +3 -3
  68. package/dist/multicast-auth-catalog.js.map +2 -2
  69. package/dist/multicast-input.js.map +2 -2
  70. package/dist/multicast-manager.d.ts +28 -3
  71. package/dist/multicast-manager.d.ts.map +1 -1
  72. package/dist/multicast-manager.js +1451 -215
  73. package/dist/multicast-manager.js.map +3 -3
  74. package/dist/multicast-transport.js +28 -18
  75. package/dist/multicast-transport.js.map +2 -2
  76. package/dist/multicast-unwrap.js +12 -19
  77. package/dist/multicast-unwrap.js.map +2 -2
  78. package/dist/no-modules.d.ts +1 -0
  79. package/dist/no-modules.d.ts.map +1 -1
  80. package/dist/no-modules.js +463 -64
  81. package/dist/no-modules.js.map +4 -4
  82. package/dist/repair-fetch.d.ts +38 -8
  83. package/dist/repair-fetch.d.ts.map +1 -1
  84. package/dist/repair-fetch.js +286 -27
  85. package/dist/repair-fetch.js.map +3 -3
  86. package/dist/repair-layer-subscriptions.d.ts +82 -0
  87. package/dist/repair-layer-subscriptions.d.ts.map +1 -0
  88. package/dist/repair-layer-subscriptions.js +192 -0
  89. package/dist/repair-layer-subscriptions.js.map +7 -0
  90. package/dist/signaling.js.map +2 -2
  91. package/dist/timestamp-codec.js +12 -19
  92. package/dist/timestamp-codec.js.map +2 -2
  93. package/dist/track-session.d.ts +1 -1
  94. package/dist/track-session.d.ts.map +1 -1
  95. package/dist/track-session.js +1 -0
  96. package/dist/track-session.js.map +2 -2
  97. package/dist/wasm-mfu-reassembler.js.map +2 -2
  98. package/dist/wasm-mmtp-container-parser.js +323 -46
  99. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  100. package/package.json +8 -5
  101. package/schemas/catalog.schema.json +4 -0
  102. package/src/block-policy.ts +216 -52
  103. package/src/catalog-fec-params.ts +37 -1
  104. package/src/cmcd-producer.ts +189 -179
  105. package/src/codec-utils.ts +121 -1
  106. package/src/fec-manager.ts +619 -37
  107. package/src/fec-worker-setup.ts +2 -2
  108. package/src/index.ts +22 -2
  109. package/src/iso-block-locator.ts +133 -31
  110. package/src/iso-bmff-timing.ts +40 -1
  111. package/src/mmtp-container-parser.ts +353 -32
  112. package/src/mmtp-fec-session.ts +115 -15
  113. package/src/mmtp-router.ts +618 -44
  114. package/src/multicast-manager.ts +139 -16
  115. package/src/no-modules.ts +3 -0
  116. package/src/repair-fetch.ts +366 -50
  117. package/src/repair-layer-subscriptions.ts +261 -0
  118. package/src/track-session.ts +4 -1
@@ -149,30 +149,26 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
149
149
  const authLength = view2.getUint16(2, false);
150
150
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
151
151
  }
152
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
152
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
153
153
  if (declaredEnd > payload.length)
154
154
  return null;
155
155
  if (options?.skipFecId) {
156
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
156
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
157
157
  }
158
- const overlay = options?.overlayDeclared === true && rapFlag;
159
158
  if (fecType === 1) {
160
- const fecStart = payload.length - sourceFecTrailerSize(overlay);
159
+ const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
161
160
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
162
161
  return null;
163
162
  }
164
- return { hasFecId: true, hasOverlayFecId: overlay };
163
+ return { hasFecId: true };
165
164
  }
166
- if (fecType !== 0 || overlay)
165
+ if (fecType !== 0)
167
166
  return null;
168
167
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
169
- return { hasFecId: false, hasOverlayFecId: false };
168
+ return { hasFecId: false };
170
169
  }
171
170
  return null;
172
171
  }
173
- function sourceFecTrailerSize(overlay) {
174
- return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
175
- }
176
172
  function planMfuExtraction(mmtpPacket, options, parsedHeader) {
177
173
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {
178
174
  return {
@@ -225,11 +221,11 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
225
221
  if ("rejection" in layoutResult)
226
222
  return layoutResult;
227
223
  const { layout } = layoutResult;
228
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
224
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
229
225
  if (!trailerLayout) {
230
226
  if (!options?.skipFecId && header.fecType === 1) {
231
227
  const observed = payload.length - layout.dataEnd;
232
- const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
228
+ const expected = SOURCE_FEC_PAYLOAD_ID_SIZE;
233
229
  if (observed !== expected) {
234
230
  return {
235
231
  rejection: {
@@ -261,13 +257,10 @@ function extractPlannedMfu(mmtpPacket, result) {
261
257
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
262
258
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
263
259
  const data = payload.subarray(mfuOffset, dataEnd);
264
- const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
265
- const ssIdAt = (offset) => ({
266
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
267
- });
268
- const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
269
- const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
270
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
260
+ const fecPayloadId = trailerLayout.hasFecId ? {
261
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, 4).getUint32(0, false)
262
+ } : null;
263
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
271
264
  }
272
265
  function sourceFecPayloadIdOf(mmtpPacket, header) {
273
266
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE)
@@ -1617,14 +1610,15 @@ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
1617
1610
  });
1618
1611
 
1619
1612
  // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
1613
+ var MAX_PENDING_PACKETS = 256;
1620
1614
  var AMTGatewayManager = class {
1621
1615
  subscriptions = /* @__PURE__ */ new Map();
1622
1616
  messageHandler;
1617
+ messageListenerRegistered = false;
1623
1618
  pendingPackets = /* @__PURE__ */ new Map();
1624
1619
  constructor() {
1625
1620
  this.messageHandler = (event) => {
1626
1621
  const data = event.data;
1627
- console.log(`[AMT] SW message received:`, data.type);
1628
1622
  if (data.type === "UDP_PACKET") {
1629
1623
  this.handlePacket(data);
1630
1624
  } else if (data.type === "SOCKET_ERROR") {
@@ -1633,12 +1627,22 @@ var AMTGatewayManager = class {
1633
1627
  console.log(`[AMT SW Debug] ${data.message}`);
1634
1628
  }
1635
1629
  };
1636
- if (typeof navigator !== "undefined" && navigator.serviceWorker) {
1637
- navigator.serviceWorker.addEventListener("message", this.messageHandler);
1638
- console.log("[AMT] Registered service worker message handler");
1639
- } else {
1640
- console.warn("[AMT] Service worker not available");
1630
+ }
1631
+ ensureMessageListener() {
1632
+ if (this.messageListenerRegistered || typeof navigator === "undefined" || !navigator.serviceWorker || !this.messageHandler) {
1633
+ return;
1641
1634
  }
1635
+ navigator.serviceWorker.addEventListener("message", this.messageHandler);
1636
+ this.messageListenerRegistered = true;
1637
+ console.log("[AMT] Registered service worker message handler");
1638
+ }
1639
+ removeMessageListener() {
1640
+ if (!this.messageListenerRegistered)
1641
+ return;
1642
+ if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
1643
+ navigator.serviceWorker.removeEventListener("message", this.messageHandler);
1644
+ }
1645
+ this.messageListenerRegistered = false;
1642
1646
  }
1643
1647
  /**
1644
1648
  * Subscribe via AMT tunnel
@@ -1648,6 +1652,7 @@ var AMTGatewayManager = class {
1648
1652
  if (config.protected) {
1649
1653
  throw new Error("AMTGatewayManager refuses a protected join: it reports no per-datagram sender (multicast-02 7.2.7)");
1650
1654
  }
1655
+ this.ensureMessageListener();
1651
1656
  const keyStr = this.getKeyString(key);
1652
1657
  if (this.subscriptions.has(keyStr)) {
1653
1658
  console.log(`[AMT] Reusing existing subscription to ${keyStr}`);
@@ -1683,6 +1688,8 @@ var AMTGatewayManager = class {
1683
1688
  this.subscriptions.delete(keyStr);
1684
1689
  this.pendingPackets.delete(subscription.subscriptionId);
1685
1690
  }
1691
+ if (this.subscriptions.size === 0)
1692
+ this.removeMessageListener();
1686
1693
  throw new Error(`Failed to subscribe via AMT: ${error instanceof Error ? error.message : String(error)}`);
1687
1694
  }
1688
1695
  }
@@ -1704,6 +1711,8 @@ var AMTGatewayManager = class {
1704
1711
  } finally {
1705
1712
  this.subscriptions.delete(handle);
1706
1713
  this.pendingPackets.delete(subscription.subscriptionId);
1714
+ if (this.subscriptions.size === 0)
1715
+ this.removeMessageListener();
1707
1716
  }
1708
1717
  }
1709
1718
  /**
@@ -1720,14 +1729,12 @@ var AMTGatewayManager = class {
1720
1729
  if (!subscriptionId)
1721
1730
  return;
1722
1731
  const subscription = this.subscriptions.get(subscriptionId);
1723
- if (!subscription) {
1724
- console.warn(`[AMT] Received packet for unknown subscription: ${subscriptionId}`);
1732
+ if (!subscription)
1725
1733
  return;
1726
- }
1727
1734
  if (!subscription.handshakeComplete) {
1728
1735
  const queue = this.pendingPackets.get(subscriptionId);
1729
1736
  const packetData2 = data;
1730
- if (queue) {
1737
+ if (queue && queue.length < MAX_PENDING_PACKETS) {
1731
1738
  queue.push({
1732
1739
  data: packetData2.data,
1733
1740
  remoteAddress: packetData2.remoteAddress,
@@ -1753,19 +1760,15 @@ var AMTGatewayManager = class {
1753
1760
  if (!subscriptionId)
1754
1761
  return;
1755
1762
  const subscription = this.subscriptions.get(subscriptionId);
1756
- if (!subscription) {
1757
- console.warn(`[AMT] Received error for unknown subscription: ${subscriptionId}`);
1763
+ if (!subscription)
1758
1764
  return;
1759
- }
1760
1765
  subscription.config.onError(new Error(error || "Unknown error"));
1761
1766
  }
1762
1767
  /**
1763
1768
  * Cleanup on destroy
1764
1769
  */
1765
1770
  destroy() {
1766
- if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
1767
- navigator.serviceWorker.removeEventListener("message", this.messageHandler);
1768
- }
1771
+ this.removeMessageListener();
1769
1772
  const handles = Array.from(this.subscriptions.keys());
1770
1773
  for (const handle of handles) {
1771
1774
  this.unsubscribe(handle).catch((err) => {
@@ -4824,9 +4827,10 @@ function isH264IntraSlice(nal) {
4824
4827
  const sliceType = readH264SliceType(nal);
4825
4828
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
4826
4829
  }
4830
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
4827
4831
  function readH264SliceType(nal) {
4828
4832
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
4829
- const rbsp = removeEmulationPrevention(nal.subarray(1));
4833
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
4830
4834
  const state = { bitOffset: 0 };
4831
4835
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
4832
4836
  return readUnsignedExpGolomb(rbsp, state);
@@ -4973,6 +4977,96 @@ if (void 0) {
4973
4977
  ]))).toBe(false);
4974
4978
  });
4975
4979
  });
4980
+ describe("readH264SliceType", () => {
4981
+ const wholeNalSliceType = (nal) => {
4982
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
4983
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
4984
+ const state = { bitOffset: 0 };
4985
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
4986
+ return readUnsignedExpGolomb(rbsp, state);
4987
+ };
4988
+ const hex = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
4989
+ const ue = (value) => {
4990
+ const code = (value + 1).toString(2);
4991
+ return "0".repeat(code.length - 1) + code;
4992
+ };
4993
+ const sliceNal = (bits) => {
4994
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
4995
+ const nal = [1];
4996
+ let zeros = 0;
4997
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
4998
+ if (zeros >= 2 && byte <= 3) {
4999
+ nal.push(3);
5000
+ zeros = 0;
5001
+ }
5002
+ nal.push(byte);
5003
+ zeros = byte === 0 ? zeros + 1 : 0;
5004
+ }
5005
+ return Uint8Array.from(nal);
5006
+ };
5007
+ const x264Slices = [
5008
+ ["64x48 P", hex("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
5009
+ ["64x48 B", hex("419e414212fffeeade283707cb70f7"), 6, false],
5010
+ ["64x48 non-IDR I", hex(
5011
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
5012
+ ), 7, true],
5013
+ ["1280x720 B, escape at byte 10", hex(
5014
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
5015
+ ), 6, false],
5016
+ ["1280x720 P, escape at byte 15", hex(
5017
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
5018
+ ), 5, false],
5019
+ ["1280x720 B, escape at byte 22", hex("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
5020
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex(
5021
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
5022
+ ), null, true],
5023
+ ["7680x4320 P, first_mb_in_slice 32640", hex(
5024
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
5025
+ ), 5, false],
5026
+ ["7680x4320 P, first_mb_in_slice 97440", hex(
5027
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
5028
+ ), 5, false]
5029
+ ];
5030
+ const syntheticSlices = [
5031
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
5032
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
5033
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
5034
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
5035
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
5036
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
5037
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
5038
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
5039
+ ];
5040
+ test("reads the slice_type of real and synthetic slices", () => {
5041
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
5042
+ expect(readH264SliceType(nal), name).toBe(sliceType);
5043
+ }
5044
+ });
5045
+ test("matches the whole-NAL unescape at every truncation", () => {
5046
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
5047
+ for (let end = 0; end <= nal.length; end++) {
5048
+ const cut = nal.subarray(0, end);
5049
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
5050
+ }
5051
+ }
5052
+ });
5053
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
5054
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
5055
+ let seed = 1;
5056
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
5057
+ for (let i = 0; i < 5e3; i++) {
5058
+ const nal = new Uint8Array(2 + next() % 63);
5059
+ nal[0] = 65;
5060
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
5061
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
5062
+ }
5063
+ });
5064
+ test("classifies the x264 slices as keyframes or not", () => {
5065
+ for (const [name, nal, , keyframe] of x264Slices) {
5066
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
5067
+ }
5068
+ });
5069
+ });
4976
5070
  describe("avccToAnnexB", () => {
4977
5071
  test("converts with SPS/PPS on keyframe", () => {
4978
5072
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -7674,9 +7768,21 @@ var IsoBmffTimingResolver = class {
7674
7768
  }
7675
7769
  #track = null;
7676
7770
  #fragments = /* @__PURE__ */ new Map();
7771
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
7772
+ #firstSamples = /* @__PURE__ */ new Map();
7773
+ /**
7774
+ * First sample and sample count of the newest fragments whose every slot was
7775
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
7776
+ * matches the combiner, since it retires an abandoned sample as well.
7777
+ */
7778
+ #delivered = /* @__PURE__ */ new Map();
7677
7779
  #pendingSamples = 0;
7678
7780
  #evictedSamples = 0;
7679
7781
  #lastMovieFragmentRejection = null;
7782
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
7783
+ get initialized() {
7784
+ return this.#track !== null;
7785
+ }
7680
7786
  get pendingSampleCount() {
7681
7787
  return this.#pendingSamples;
7682
7788
  }
@@ -7700,7 +7806,14 @@ var IsoBmffTimingResolver = class {
7700
7806
  this.#track = timing;
7701
7807
  return true;
7702
7808
  }
7703
- addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples) {
7809
+ /**
7810
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
7811
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
7812
+ * fragment whose samples are all done is a duplicate: admitting it again
7813
+ * would charge stale timing and could displace the live MPU's. A source
7814
+ * copy is still admitted again (a rendition switch re-arms timing that way).
7815
+ */
7816
+ addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
7704
7817
  this.#lastMovieFragmentRejection = null;
7705
7818
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
7706
7819
  this.#lastMovieFragmentRejection = "invalid";
@@ -7726,6 +7839,8 @@ var IsoBmffTimingResolver = class {
7726
7839
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
7727
7840
  );
7728
7841
  }
7842
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
7843
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
7729
7844
  let freed = 0;
7730
7845
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
7731
7846
  freed += this.#evictOldestFragment();
@@ -7739,6 +7854,7 @@ var IsoBmffTimingResolver = class {
7739
7854
  return false;
7740
7855
  }
7741
7856
  this.#fragments.set(key, [...parsed.samples]);
7857
+ this.#firstSamples.set(key, parsed.samples[0]);
7742
7858
  this.#pendingSamples += parsed.samples.length;
7743
7859
  return true;
7744
7860
  }
@@ -7796,6 +7912,7 @@ var IsoBmffTimingResolver = class {
7796
7912
  let live = 0;
7797
7913
  for (const sample of samples) if (sample !== null) live++;
7798
7914
  this.#fragments.delete(oldest);
7915
+ this.#firstSamples.delete(oldest);
7799
7916
  this.#pendingSamples -= live;
7800
7917
  this.#evictedSamples += live;
7801
7918
  return live;
@@ -7811,12 +7928,23 @@ var IsoBmffTimingResolver = class {
7811
7928
  if (!samples || !samples[index]) return false;
7812
7929
  samples[index] = null;
7813
7930
  this.#pendingSamples--;
7814
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
7931
+ if (samples.every((value) => value === null)) {
7932
+ this.#fragments.delete(key);
7933
+ const first = this.#firstSamples.get(key);
7934
+ this.#firstSamples.delete(key);
7935
+ this.#delivered.delete(key);
7936
+ this.#delivered.set(key, { first, sampleCount: samples.length });
7937
+ if (this.#delivered.size > this.maxPendingSamples) {
7938
+ this.#delivered.delete(this.#delivered.keys().next().value);
7939
+ }
7940
+ }
7815
7941
  return true;
7816
7942
  }
7817
7943
  reset() {
7818
7944
  this.#track = null;
7819
7945
  this.#fragments.clear();
7946
+ this.#firstSamples.clear();
7947
+ this.#delivered.clear();
7820
7948
  this.#pendingSamples = 0;
7821
7949
  }
7822
7950
  };
@@ -7986,6 +8114,9 @@ function authoredGap(before, after) {
7986
8114
  function ssIdAfter(a, b) {
7987
8115
  return (a - b | 0) > 0;
7988
8116
  }
8117
+ function holdsRebuilt(stream) {
8118
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
8119
+ }
7989
8120
  var FecReleaseSequencer = class {
7990
8121
  #streams = /* @__PURE__ */ new Map();
7991
8122
  #gate;
@@ -8048,6 +8179,7 @@ var FecReleaseSequencer = class {
8048
8179
  stream.lastSbn = void 0;
8049
8180
  stream.discontinuity = false;
8050
8181
  stream.rapSsId = void 0;
8182
+ stream.sourced = false;
8051
8183
  }
8052
8184
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
8053
8185
  this.#recordStat("droppedStale");
@@ -8074,6 +8206,7 @@ var FecReleaseSequencer = class {
8074
8206
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
8075
8207
  else hi = mid;
8076
8208
  }
8209
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
8077
8210
  stream.buf.splice(lo, 0, frame);
8078
8211
  this.#drainUnlessDeferred(stream);
8079
8212
  }
@@ -8109,6 +8242,41 @@ var FecReleaseSequencer = class {
8109
8242
  }
8110
8243
  return false;
8111
8244
  }
8245
+ /**
8246
+ * These streams' sink is being replaced by one that has seen no source
8247
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
8248
+ * release to the sink being replaced the frames the unanchored path had
8249
+ * already released to it (#cursorPassed): there they waited in its queue,
8250
+ * which its replacement flushes. A stream that holds none is not drained:
8251
+ * it holds nothing the anchor kept back, and a drain would still force out
8252
+ * a frame held past the hold limit, which before the anchor waited for the
8253
+ * next push. Then treat the streams as unsourced until a source frame is
8254
+ * released.
8255
+ */
8256
+ unsource(packetId, catalogTrackName) {
8257
+ for (const stream of this.#streams.values()) {
8258
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
8259
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
8260
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
8261
+ else this.#drain(stream, true);
8262
+ }
8263
+ stream.sourced = false;
8264
+ }
8265
+ }
8266
+ }
8267
+ /**
8268
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
8269
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
8270
+ * packetId.
8271
+ */
8272
+ holdsRebuilt(packetId, catalogTrackName) {
8273
+ for (const stream of this.#streams.values()) {
8274
+ if (stream.packetId !== packetId) continue;
8275
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
8276
+ if (holdsRebuilt(stream)) return true;
8277
+ }
8278
+ return false;
8279
+ }
8112
8280
  /** Re-evaluate held gaps after FEC state changed. */
8113
8281
  poke(streamKey) {
8114
8282
  if (streamKey !== void 0) {
@@ -8200,16 +8368,32 @@ var FecReleaseSequencer = class {
8200
8368
  last: null,
8201
8369
  lastSbn: void 0,
8202
8370
  discontinuity: false,
8203
- rapSsId: void 0
8371
+ rapSsId: void 0,
8372
+ sourced: false,
8373
+ draining: 0
8204
8374
  };
8205
8375
  this.#streams.set(streamKey, stream);
8206
8376
  }
8207
8377
  return stream;
8208
8378
  }
8209
- #drain(stream) {
8379
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
8380
+ #drain(stream, asUnanchored = false) {
8381
+ stream.draining++;
8382
+ try {
8383
+ this.#drainLoop(stream, asUnanchored);
8384
+ } finally {
8385
+ stream.draining--;
8386
+ }
8387
+ }
8388
+ #drainLoop(stream, asUnanchored) {
8210
8389
  while (stream.buf.length > 0 && stream.last !== null) {
8211
8390
  const head = stream.buf[0];
8212
8391
  const last = stream.last;
8392
+ if (compareFrameOrder(head, last) <= 0) {
8393
+ stream.buf.shift();
8394
+ this.#release(stream, head, void 0);
8395
+ continue;
8396
+ }
8213
8397
  if (stream.discontinuity) {
8214
8398
  stream.discontinuity = false;
8215
8399
  stream.buf.shift();
@@ -8223,9 +8407,10 @@ var FecReleaseSequencer = class {
8223
8407
  }
8224
8408
  const headSbn = head.meta.fecSbn;
8225
8409
  const from = stream.lastSbn ?? headSbn;
8226
- const to = headSbn ?? stream.lastSbn;
8410
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
8227
8411
  let lost = [];
8228
8412
  const unanchored = from === void 0 && to === void 0;
8413
+ let unresolved = false;
8229
8414
  if (from !== void 0 && to !== void 0) {
8230
8415
  const resolved = this.#gate.resolvedLoss(
8231
8416
  stream.packetId,
@@ -8234,7 +8419,8 @@ var FecReleaseSequencer = class {
8234
8419
  Math.max(from, to),
8235
8420
  from
8236
8421
  );
8237
- if (resolved === null) {
8422
+ unresolved = resolved === null;
8423
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
8238
8424
  const heldMs = performance.now() - head.arrivedAtMs;
8239
8425
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
8240
8426
  this.#recordStat("forcedWindowFlushes");
@@ -8242,22 +8428,69 @@ var FecReleaseSequencer = class {
8242
8428
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
8243
8429
  continue;
8244
8430
  }
8245
- lost = resolved;
8431
+ lost = resolved ?? [];
8246
8432
  }
8247
8433
  stream.buf.shift();
8248
8434
  this.#release(
8249
8435
  stream,
8250
8436
  head,
8251
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
8437
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
8252
8438
  );
8253
8439
  }
8254
8440
  }
8441
+ /**
8442
+ * The head has waited out a gap only a late source can still fill
8443
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
8444
+ * the stream when it has (`wakeAt`), since no packet may come by then.
8445
+ */
8446
+ #unrepairableWaitOver(stream, last, head, from, to) {
8447
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
8448
+ if (waitMs === void 0) return false;
8449
+ const atMs = head.arrivedAtMs + waitMs;
8450
+ if (performance.now() >= atMs) return true;
8451
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
8452
+ return false;
8453
+ }
8454
+ /**
8455
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
8456
+ * source cursor holds it unanchored, and neither does a later frame behind
8457
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
8458
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
8459
+ * like each frame that arrived in front of it since (stale there). The head
8460
+ * then goes, decided as it would be unanchored, once a frame the base path
8461
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
8462
+ * marked one: the base path has passed that one, so a frame still missing
8463
+ * before it can only come from a repair. It also goes while no source frame
8464
+ * has been released, when the direct path shows a recovered frame at once.
8465
+ * And it goes at once while a staged switch decides on when frames arrive
8466
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
8467
+ * sink being replaced: unanchored, it had already reached the sink.
8468
+ * The scan also writes: the `passed` marks it sets stay on the frames,
8469
+ * and push marks a frame it inserts in front of a marked one from them.
8470
+ */
8471
+ #cursorPassed(stream, asUnanchored) {
8472
+ let at = -1;
8473
+ for (let i = 0; i < stream.buf.length; i++) {
8474
+ const frame = stream.buf[i];
8475
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
8476
+ frame.passed = true;
8477
+ if (at < 0) at = i;
8478
+ } else if (frame.passed !== true) break;
8479
+ }
8480
+ if (at < 0) return false;
8481
+ return asUnanchored || !stream.sourced || this.#gate.releaseUnanchored?.(stream.packetId, stream.catalogTrackName) === true || stream.buf.some(({ meta }, i) => i > at && meta.fecSbnFirst === void 0 && (meta.recovered !== true || meta.fecSbn !== void 0));
8482
+ }
8255
8483
  #release(stream, frame, decision) {
8484
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
8485
+ if (stale) this.#recordStat("droppedStale");
8256
8486
  if (decision) frame.meta.gapBefore = decision;
8257
8487
  stream.last = frame;
8258
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
8488
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
8489
+ stream.lastSbn = frame.meta.fecSbn;
8490
+ }
8491
+ if (frame.meta.recovered !== true) stream.sourced = true;
8259
8492
  this.#gate.onReleased?.(frame.data, frame.meta);
8260
- this.#emit(frame.data, frame.meta);
8493
+ if (!stale) this.#emit(frame.data, frame.meta);
8261
8494
  }
8262
8495
  };
8263
8496
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -8298,6 +8531,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
8298
8531
  this.#reclaimedTimingSamples = 0;
8299
8532
  this.#evictedTimingSamples = 0;
8300
8533
  this.#rejectedMovieFragments = 0;
8534
+ this.#recoveredHeadsAwaitingTiming = {
8535
+ held: 0,
8536
+ expired: 0,
8537
+ discarded: 0,
8538
+ superseded: 0
8539
+ };
8301
8540
  this.#sequencers = /* @__PURE__ */ new Map();
8302
8541
  this.#fecGate = null;
8303
8542
  this.#fecSequencer = null;
@@ -8406,6 +8645,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
8406
8645
  #reclaimedTimingSamples;
8407
8646
  #evictedTimingSamples;
8408
8647
  #rejectedMovieFragments;
8648
+ #recoveredHeadsAwaitingTiming;
8409
8649
  #sequencers;
8410
8650
  #fecGate;
8411
8651
  #fecSequencer;
@@ -8511,11 +8751,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
8511
8751
  /**
8512
8752
  * Typed view of the ISO-BMFF timing-sample budget.
8513
8753
  *
8514
- * This is the acceptance signal for the budget ratchet: `pending` walking
8515
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
8516
- * and it is observable here rather than only as media silently stopping.
8517
- * Per repo policy this is a producer-owned counter -- never infer budget
8518
- * state by parsing logs.
8754
+ * Each stream admits timing against its own window of `capacity` slots
8755
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
8756
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
8757
+ * timing a stream declared and never delivered shows up there. `pending`
8758
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
8759
+ * a producer-owned counter -- never infer budget state by parsing logs.
8519
8760
  */
8520
8761
  get timingBudgetStats() {
8521
8762
  return {
@@ -8526,6 +8767,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
8526
8767
  rejectedMovieFragments: this.#rejectedMovieFragments
8527
8768
  };
8528
8769
  }
8770
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
8771
+ get recoveredHeadsAwaitingTiming() {
8772
+ let pending = 0;
8773
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
8774
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
8775
+ }
8776
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
8777
+ }
8529
8778
  get reorderStats() {
8530
8779
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
8531
8780
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -8567,6 +8816,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
8567
8816
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
8568
8817
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
8569
8818
  }
8819
+ /** See FecReleaseSequencer.unsource. */
8820
+ unsourceFecRelease(packetId, catalogTrackName) {
8821
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
8822
+ }
8823
+ /** See FecReleaseSequencer.holdsRebuilt. */
8824
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
8825
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
8826
+ }
8570
8827
  /** Re-evaluate held gaps after FEC block state changed. */
8571
8828
  pokeFecRelease(packetId, catalogTrackName) {
8572
8829
  if (!this.#fecSequencer) return;
@@ -8699,7 +8956,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
8699
8956
  const now = Date.now();
8700
8957
  for (const { awaitingTiming } of this.#timingStreams.values()) {
8701
8958
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
8702
- awaitingTiming.shift();
8959
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
8703
8960
  }
8704
8961
  }
8705
8962
  }
@@ -8817,11 +9074,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
8817
9074
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
8818
9075
  return this.#drop("fragment-unexpected-fragmentation");
8819
9076
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
8820
- if (!resolver2) return this.#drop("fragment-no-resolver");
9077
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
8821
9078
  const pendingBefore = resolver2.pendingSampleCount;
8822
9079
  const evictedBefore = resolver2.evictedSampleCount;
8823
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
8824
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
9080
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
9081
+ const admitted = resolver2.addMovieFragment(
9082
+ mpu.mpuSequenceNumber,
9083
+ data,
9084
+ remaining,
9085
+ options?.recovered === true
9086
+ );
8825
9087
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
8826
9088
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
8827
9089
  if (!admitted) {
@@ -8841,7 +9103,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
8841
9103
  };
8842
9104
  }
8843
9105
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
8844
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
9106
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
8845
9107
  if (!resolver) return this.#drop("mfu-no-resolver");
8846
9108
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
8847
9109
  return this.#drop("mfu-empty-payload");
@@ -8862,6 +9124,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
8862
9124
  mpuSequenceNumber: mpu.mpuSequenceNumber,
8863
9125
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
8864
9126
  sampleNumber: mfuDuHeader.sampleNumber,
9127
+ sequenceNumber: info.sequenceNumber,
8865
9128
  arrivedAt: Date.now()
8866
9129
  });
8867
9130
  return this.#drop("mfu-sample-timing-missing");
@@ -8887,7 +9150,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
8887
9150
  info,
8888
9151
  resolver,
8889
9152
  options?.recovered === true,
8890
- options?.fecSbn
9153
+ options?.fecSbn,
9154
+ options?.fecSbnFirst
8891
9155
  );
8892
9156
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
8893
9157
  }
@@ -8980,7 +9244,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
8980
9244
  info,
8981
9245
  resolver,
8982
9246
  options?.recovered === true,
8983
- options?.fecSbn
9247
+ options?.fecSbn,
9248
+ options?.fecSbnFirst
8984
9249
  );
8985
9250
  if (outcome.record !== void 0) return outcome.record;
8986
9251
  return this.#drop(outcome.reason);
@@ -9000,7 +9265,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
9000
9265
  * attribution exists to keep readable. Leaving the choice at the call site
9001
9266
  * is what keeps both true.
9002
9267
  */
9003
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
9268
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
9004
9269
  const timing = resolver.sampleTiming(
9005
9270
  combined.mpuSequenceNumber,
9006
9271
  combined.movieFragmentSequenceNumber,
@@ -9017,6 +9282,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
9017
9282
  );
9018
9283
  if (!meta) return { reason: "combined-meta-build-failed" };
9019
9284
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
9285
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
9020
9286
  if (!resolver.consumeSample(
9021
9287
  combined.mpuSequenceNumber,
9022
9288
  combined.movieFragmentSequenceNumber,
@@ -9185,6 +9451,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
9185
9451
  }
9186
9452
  this.#emitFrame(data, meta);
9187
9453
  }
9454
+ /** Whether FT=1 metadata already names this sample, without claiming it. */
9455
+ hasAuthoredTimingFor(packetId, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber, catalogTrackName) {
9456
+ return this.#timingResolver(this.#streamKey(packetId, catalogTrackName), packetId, false)?.sampleTiming(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber) != null;
9457
+ }
9188
9458
  /**
9189
9459
  * Claim and return the authored timing for a recovered sample. Recovery does
9190
9460
  * not pass through the ordinary `feed()` completion path, so it must retire
@@ -9246,6 +9516,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
9246
9516
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
9247
9517
  this.#sequencers.clear();
9248
9518
  this.#fecSequencer?.discard();
9519
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
9520
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
9521
+ }
9249
9522
  this.#timingStreams.clear();
9250
9523
  this.#pendingTimingSamples = 0;
9251
9524
  this.#reliableMoqStartupGate.clear();
@@ -9264,10 +9537,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
9264
9537
  return resolver;
9265
9538
  }
9266
9539
  #awaitTiming(streamKey, head) {
9267
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
9268
- if (!awaitingTiming) return;
9540
+ const state = this.#timingStreams.get(streamKey);
9541
+ if (!state) return;
9542
+ if (!head.options?.recovered) {
9543
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
9544
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
9545
+ state.awaitingTiming = kept;
9546
+ }
9547
+ const awaitingTiming = state.awaitingTiming;
9269
9548
  awaitingTiming.push(head);
9270
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
9549
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
9550
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
9551
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
9552
+ }
9553
+ }
9554
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
9555
+ #leaveAwaitingTiming(head, outcome) {
9556
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
9271
9557
  }
9272
9558
  /**
9273
9559
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -9295,6 +9581,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
9295
9581
  const state = this.#timingStreams.get(streamKey);
9296
9582
  if (!state) return;
9297
9583
  this.#timingStreams.delete(streamKey);
9584
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
9298
9585
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
9299
9586
  if (this.#pendingTimingSamples < 0) {
9300
9587
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -9835,7 +10122,18 @@ function keyframeOverlaySsId(header) {
9835
10122
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
9836
10123
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
9837
10124
  }
10125
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
10126
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
10127
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
10128
+ }
10129
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
10130
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
10131
+ return headerPsn + offset >>> 0;
10132
+ }
10133
+ var OVERLAY_ROUTED_LIMIT = 1024;
10134
+ var OVERLAY_PENDING_LIMIT = 256;
9838
10135
  var OVERLAY_OFFSET_MPUS = 16;
10136
+ var OVERLAY_REBUILT_LIMIT = 256;
9839
10137
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
9840
10138
  function assertStreamIdentity(role, stream) {
9841
10139
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -9946,6 +10244,7 @@ var MmtpRouter = class {
9946
10244
  #provenance = /* @__PURE__ */ new Map();
9947
10245
  #onFlowProtected = null;
9948
10246
  #unadmittedListedDrops = 0;
10247
+ #admittedSourceDatagrams = 0;
9949
10248
  #unlistedRepairSetAside = 0;
9950
10249
  #assistBlocks = /* @__PURE__ */ new Map();
9951
10250
  #assistFailures = /* @__PURE__ */ new Map();
@@ -10002,6 +10301,26 @@ var MmtpRouter = class {
10002
10301
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
10003
10302
  */
10004
10303
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
10304
+ /**
10305
+ * Per stream, the SS_ID offset at which a base recovery last showed the
10306
+ * sender's own packet_sequence_number: a recovered packet's header psn
10307
+ * equal to its SS_ID minus that offset. While it equals the stream's
10308
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
10309
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
10310
+ * an MPU no member of which arrived).
10311
+ */
10312
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
10313
+ /**
10314
+ * The same, shown by the overlay alone, before any base recovery did: a
10315
+ * packet it rebuilt whose base copy carries its protected psn
10316
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
10317
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
10318
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
10319
+ * make the base drop a late base copy of a keyframe the overlay never
10320
+ * finished, and lift a block's late-source cut, which nothing before
10321
+ * this offset did.
10322
+ */
10323
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
10005
10324
  /**
10006
10325
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
10007
10326
  * not parsed, typically because its overlap copy was parsed first
@@ -10047,6 +10366,8 @@ var MmtpRouter = class {
10047
10366
  // end: a synchronous recovery completes its block BEFORE routing the
10048
10367
  // recovered frames, and releasing a held gap in between would strand them.
10049
10368
  #fecPokeDepth = 0;
10369
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
10370
+ #fecWakes = /* @__PURE__ */ new Map();
10050
10371
  #pendingFecPokes = /* @__PURE__ */ new Map();
10051
10372
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
10052
10373
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -10071,7 +10392,9 @@ var MmtpRouter = class {
10071
10392
  recovered: 0,
10072
10393
  restarts: 0,
10073
10394
  unsequencedDropped: 0,
10074
- protectedDropped: 0
10395
+ protectedDropped: 0,
10396
+ baseFed: 0,
10397
+ baseUndetermined: 0
10075
10398
  };
10076
10399
  /** Callback fired when a delta-track FEC block completes or fails. */
10077
10400
  #onDeltaBlockCompleteCb = null;
@@ -10244,7 +10567,7 @@ var MmtpRouter = class {
10244
10567
  const cb = this.#getFrameCallback(packetId);
10245
10568
  if (isVideo && !assembler) {
10246
10569
  if (frameMeta.recovered) {
10247
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
10570
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
10248
10571
  } else {
10249
10572
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
10250
10573
  }
@@ -10277,13 +10600,18 @@ var MmtpRouter = class {
10277
10600
  this.#onDeltaBlockCompleteCb?.(packetId, false);
10278
10601
  }
10279
10602
  };
10280
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
10603
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
10281
10604
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
10282
10605
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
10283
10606
  this.#onDeltaBlockCompleteCb?.(packetId, true);
10284
10607
  }
10285
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
10286
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
10608
+ if (span === void 0) {
10609
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
10610
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
10611
+ } else {
10612
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
10613
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
10614
+ }
10287
10615
  };
10288
10616
  }
10289
10617
  }
@@ -10328,8 +10656,9 @@ var MmtpRouter = class {
10328
10656
  }
10329
10657
  /**
10330
10658
  * FEC-recovered source symbols whose reconstructed header named a
10331
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
10332
- * a hop re-stamped the sequence after the sender protected the packet.
10659
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
10660
+ * or, rebuilt by the overlay, than their base copy carries: a hop
10661
+ * re-stamped the sequence after the sender protected the packet.
10333
10662
  */
10334
10663
  get restampedRecoveredSequenceCount() {
10335
10664
  return this.#restampedRecoveredSeqs;
@@ -10508,6 +10837,7 @@ var MmtpRouter = class {
10508
10837
  enableMseAssembler(packetId, config, catalogTrackName) {
10509
10838
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
10510
10839
  const previous = this.#mseAssemblers.get(assemblerKey);
10840
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
10511
10841
  if (previous) {
10512
10842
  previous.flush();
10513
10843
  previous.dispose();
@@ -10634,6 +10964,10 @@ var MmtpRouter = class {
10634
10964
  get keyframeOverlayStats() {
10635
10965
  return { ...this.#overlayStats };
10636
10966
  }
10967
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
10968
+ get recoveredHeadsAwaitingTiming() {
10969
+ return this.#parser.recoveredHeadsAwaitingTiming;
10970
+ }
10637
10971
  #isOverlayRepair(repairPacketId, repairTrackName) {
10638
10972
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
10639
10973
  }
@@ -10654,7 +10988,8 @@ var MmtpRouter = class {
10654
10988
  fec,
10655
10989
  k,
10656
10990
  offsets: /* @__PURE__ */ new Map(),
10657
- moqBlocks: /* @__PURE__ */ new Set()
10991
+ moqBlocks: /* @__PURE__ */ new Set(),
10992
+ rebuilt: /* @__PURE__ */ new Map()
10658
10993
  };
10659
10994
  this.#overlays.set(repairPacketId, inst);
10660
10995
  return () => {
@@ -10684,12 +11019,18 @@ var MmtpRouter = class {
10684
11019
  */
10685
11020
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
10686
11021
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
11022
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
11023
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
11024
+ stream.overlayToBase.routed.clear();
11025
+ stream.overlayToBase.pending.clear();
11026
+ }
10687
11027
  }
10688
11028
  #resetOverlay(inst) {
10689
11029
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
10690
11030
  inst.last = void 0;
10691
11031
  inst.offsets.clear();
10692
11032
  inst.moqBlocks.clear();
11033
+ inst.rebuilt.clear();
10693
11034
  }
10694
11035
  #overlaysForSource(sourcePacketId, catalogTrackName) {
10695
11036
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -10740,18 +11081,33 @@ var MmtpRouter = class {
10740
11081
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
10741
11082
  * every overlay installed for its source, at that SS_ID, with the bytes the
10742
11083
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
10743
- * included (7.1, 7.4.3).
10744
- */
10745
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
11084
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
11085
+ * FEC reads it.
11086
+ *
11087
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
11088
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
11089
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
11090
+ * the stream unstamped at the SS_ID offset it states, for the release gate
11091
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
11092
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
11093
+ */
11094
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
10746
11095
  if (this.#overlays.size === 0) return;
10747
11096
  const ssId = keyframeOverlaySsId(header);
10748
11097
  if (ssId === void 0) return;
11098
+ let rebuiltPsn;
10749
11099
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
10750
11100
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
11101
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
11102
+ inst.rebuilt.delete(ssId);
10751
11103
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
10752
11104
  if (identity !== null) {
10753
11105
  inst.offsets.delete(identity.mpuSequenceNumber);
10754
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
11106
+ inst.offsets.set(identity.mpuSequenceNumber, {
11107
+ psnOffset: ssId - sequenceNumber >>> 0,
11108
+ overlaySsId: ssId,
11109
+ ...baseSsId === void 0 ? {} : { baseSsId }
11110
+ });
10755
11111
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
10756
11112
  }
10757
11113
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -10773,6 +11129,14 @@ var MmtpRouter = class {
10773
11129
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
10774
11130
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
10775
11131
  }
11132
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
11133
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
11134
+ if (rebuiltPsn !== sequenceNumber) {
11135
+ this.#restampedRecoveredSeqs++;
11136
+ } else if (baseSsId !== void 0) {
11137
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
11138
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
11139
+ }
10776
11140
  }
10777
11141
  #noteOverlayMoqBlock(inst, blockStart) {
10778
11142
  inst.moqBlocks.add(blockStart);
@@ -10806,11 +11170,16 @@ var MmtpRouter = class {
10806
11170
  }
10807
11171
  /**
10808
11172
  * Route an overlay-recovered block's packets as source media of the
10809
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
10810
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
10811
- * base re-stamp, no block advance. Each packet's wire sequence is restored
10812
- * from its keyframe's own offset; without one, a stream the base never
10813
- * re-stamped keeps the header's sequence and any other drops the packet.
11173
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
11174
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
11175
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
11176
+ * base FEC recovered does, so it waits behind base frames still in flight,
11177
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
11178
+ * longer than unanchored; one whose base SS_ID is undetermined has no
11179
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
11180
+ * advance. Each packet's wire sequence is restored from its keyframe's own
11181
+ * offset; without one, a stream the base never re-stamped keeps the
11182
+ * header's sequence and any other drops the packet.
10814
11183
  */
10815
11184
  #routeOverlayRecovered(inst, blockStart, recovered) {
10816
11185
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -10830,22 +11199,139 @@ var MmtpRouter = class {
10830
11199
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
10831
11200
  const restamped = this.#restampedStreams.has(streamKey);
10832
11201
  const restored = /* @__PURE__ */ new Set();
11202
+ const baseSsIds = /* @__PURE__ */ new Map();
11203
+ const gateOnly = /* @__PURE__ */ new Set();
10833
11204
  const symbols = result.symbols.flatMap((sym) => {
10834
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
10835
- if (offset !== void 0) {
10836
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
11205
+ const overlaySsId = serial32Add(blockStart, sym.index);
11206
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
11207
+ if (anchor !== void 0) {
11208
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
10837
11209
  restored.add(packetSequenceNumber);
10838
- return [{ ...sym, packetSequenceNumber }];
11210
+ const out = { ...sym, packetSequenceNumber };
11211
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
11212
+ if (baseSsId !== void 0) {
11213
+ baseSsIds.set(sym.index, baseSsId);
11214
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
11215
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
11216
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
11217
+ }
11218
+ }
11219
+ return [out];
11220
+ }
11221
+ if (!restamped) {
11222
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
11223
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
11224
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
11225
+ if (baseSsId !== void 0) {
11226
+ baseSsIds.set(sym.index, baseSsId);
11227
+ if (fedSsId === void 0) gateOnly.add(sym.index);
11228
+ } else {
11229
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
11230
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
11231
+ }
11232
+ return [sym];
10839
11233
  }
10840
- if (!restamped) return [sym];
10841
11234
  this.#overlayStats.unsequencedDropped++;
10842
11235
  return [];
10843
11236
  });
10844
11237
  this.#overlayStats.recovered++;
11238
+ const mpuFirst = /* @__PURE__ */ new Map();
11239
+ for (const sym of symbols) {
11240
+ const ssId = baseSsIds.get(sym.index);
11241
+ const mpu = sym.fragment.mpuSequenceNumber;
11242
+ const first = mpuFirst.get(mpu);
11243
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
11244
+ }
11245
+ const firstSsIds = /* @__PURE__ */ new Map();
11246
+ for (const sym of symbols) {
11247
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
11248
+ }
10845
11249
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
10846
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
11250
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
11251
+ baseSsIds,
11252
+ firstSsIds
10847
11253
  });
10848
11254
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
11255
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
11256
+ }
11257
+ /**
11258
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
11259
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
11260
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
11261
+ * base recovery showed; `baseSsIds` holds no other),
11262
+ * so it is fed to the base decoder as a rebuilt source
11263
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
11264
+ * fewer to solve, and its repair can recover the block's other packets.
11265
+ * A base block no repair has stated yet takes it when one does
11266
+ * (#feedPendingRebuilt).
11267
+ *
11268
+ * The overlay route already handled each packet fed (delivered it, or
11269
+ * held an untimed head for its FT=1), so a base recovery routes none of
11270
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
11271
+ * held head would wait in the parser for timing its first copy consumed.
11272
+ * Only an overlay block decoded from multicast symbols alone is fed: with
11273
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
11274
+ * that crossed no multicast socket, which the provenance counted from the
11275
+ * block's own arrivals cannot show.
11276
+ */
11277
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
11278
+ const fec = this.#fecManager;
11279
+ const owner = inst.leg.sourcePacketId;
11280
+ const name = inst.leg.sourceCatalogTrackName;
11281
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
11282
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
11283
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
11284
+ const feeds = [];
11285
+ for (const sym of symbols) {
11286
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
11287
+ const ssId = baseSsIds.get(sym.index);
11288
+ if (ssId === void 0) {
11289
+ this.#overlayStats.baseUndetermined++;
11290
+ continue;
11291
+ }
11292
+ routed.delete(ssId);
11293
+ routed.add(ssId);
11294
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
11295
+ feeds.push([ssId, sym.rawSymbol]);
11296
+ }
11297
+ for (const [ssId, symbolData] of feeds) {
11298
+ if (this.#classifyPacketId(owner) === null) return;
11299
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
11300
+ }
11301
+ }
11302
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
11303
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
11304
+ const fec = this.#fecManager;
11305
+ if (!fec?.feedRebuiltSourceSymbol) return;
11306
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
11307
+ if (coords == null) {
11308
+ const pending = this.#stream(owner, name).overlayToBase.pending;
11309
+ pending.delete(ssId);
11310
+ pending.set(ssId, symbolData.slice());
11311
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
11312
+ return;
11313
+ }
11314
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
11315
+ if (!fed.taken) return;
11316
+ this.#overlayStats.baseFed++;
11317
+ if (fed.recovered === null) return;
11318
+ const sbn = coords.sbn;
11319
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
11320
+ fec.cancelBlockTimeout(sbn, owner, name);
11321
+ fec.countRecovery(owner, sbn, name);
11322
+ fec.markBlockCompleted(sbn, owner, name);
11323
+ });
11324
+ }
11325
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
11326
+ #feedPendingRebuilt(owner, name, block) {
11327
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
11328
+ if (pending === void 0 || pending.size === 0) return;
11329
+ for (const [ssId, symbolData] of [...pending]) {
11330
+ if (this.#classifyPacketId(owner) === null) return;
11331
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
11332
+ pending.delete(ssId);
11333
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
11334
+ }
10849
11335
  }
10850
11336
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
10851
11337
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -10985,6 +11471,10 @@ var MmtpRouter = class {
10985
11471
  get unadmittedListedDropCount() {
10986
11472
  return this.#unadmittedListedDrops;
10987
11473
  }
11474
+ /** 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. */
11475
+ get admittedSourceDatagramCount() {
11476
+ return this.#admittedSourceDatagrams;
11477
+ }
10988
11478
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
10989
11479
  get unlistedRepairSetAsideCount() {
10990
11480
  return this.#unlistedRepairSetAside;
@@ -11471,6 +11961,8 @@ var MmtpRouter = class {
11471
11961
  )) return;
11472
11962
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
11473
11963
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
11964
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
11965
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
11474
11966
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
11475
11967
  const recovered = fec.feedRepairSymbol(
11476
11968
  ownerPacketId,
@@ -11521,7 +12013,7 @@ var MmtpRouter = class {
11521
12013
  catalogTrackName
11522
12014
  )) continue;
11523
12015
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
11524
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
12016
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
11525
12017
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
11526
12018
  }
11527
12019
  if (payload.oversized) continue;
@@ -11608,6 +12100,8 @@ var MmtpRouter = class {
11608
12100
  this.#droppedPreSyncVideo.delete(streamKey);
11609
12101
  this.#latestVideoSeqByStream.delete(streamKey);
11610
12102
  this.#ssIdSeqOffsetByStream.delete(streamKey);
12103
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
12104
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
11611
12105
  this.#multicastRapTwinByStream.delete(streamKey);
11612
12106
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
11613
12107
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -11734,6 +12228,12 @@ var MmtpRouter = class {
11734
12228
  * the outgoing stream stops. The hold is bounded by the incoming stream's
11735
12229
  * own RAP cadence, so no timer is involved.
11736
12230
  *
12231
+ * While the switch is staged, the FEC release gate lets a keyframe the
12232
+ * overlay rebuilt reach it, on either side, when the keyframe did before
12233
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
12234
+ * decides on what each side delivered, and the commit discards the gate's
12235
+ * frames of the outgoing stream.
12236
+ *
11737
12237
  * The commit is one synchronous transition inside the frame path: the
11738
12238
  * outgoing stream's already-admitted frames are released (its queued FEC
11739
12239
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -11784,6 +12284,9 @@ var MmtpRouter = class {
11784
12284
  droppedIncomingFrames: 0
11785
12285
  };
11786
12286
  this.#staged = state;
12287
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
12288
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
12289
+ }
11787
12290
  return {
11788
12291
  cancel: () => {
11789
12292
  if (this.#staged !== state) return false;
@@ -11866,7 +12369,17 @@ var MmtpRouter = class {
11866
12369
  */
11867
12370
  #routeParsedFrame(data, meta) {
11868
12371
  if (this.#classifyPacketId(meta.packetId) === null) return;
11869
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
12372
+ if (this.#staged !== null) {
12373
+ let consumed = false;
12374
+ this.#fecPokeDepth++;
12375
+ try {
12376
+ consumed = this.#interceptSwitchFrame(data, meta);
12377
+ } finally {
12378
+ this.#fecPokeDepth--;
12379
+ this.#flushPendingFecPokes();
12380
+ }
12381
+ if (consumed) return;
12382
+ }
11870
12383
  this.#deliverParsedFrame(data, meta);
11871
12384
  }
11872
12385
  #commitStreamSwitch(state, rap, reason) {
@@ -11915,6 +12428,8 @@ var MmtpRouter = class {
11915
12428
  this.#disposed = true;
11916
12429
  this.#staged = null;
11917
12430
  this.cancelKeyframeLostTimer();
12431
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
12432
+ this.#fecWakes.clear();
11918
12433
  this.#parser.dispose();
11919
12434
  this.#streams.clear();
11920
12435
  this.#trackPacketCallbacks.clear();
@@ -12018,12 +12533,16 @@ var MmtpRouter = class {
12018
12533
  this.#parser.deferFecRelease(work);
12019
12534
  } finally {
12020
12535
  this.#fecPokeDepth--;
12021
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
12022
- const pokes = [...this.#pendingFecPokes.values()];
12023
- this.#pendingFecPokes.clear();
12024
- for (const poke of pokes) {
12025
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
12026
- }
12536
+ this.#flushPendingFecPokes();
12537
+ }
12538
+ }
12539
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
12540
+ #flushPendingFecPokes() {
12541
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
12542
+ const pokes = [...this.#pendingFecPokes.values()];
12543
+ this.#pendingFecPokes.clear();
12544
+ for (const poke of pokes) {
12545
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
12027
12546
  }
12028
12547
  }
12029
12548
  }
@@ -12092,6 +12611,31 @@ var MmtpRouter = class {
12092
12611
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
12093
12612
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
12094
12613
  },
12614
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
12615
+ // late source can), its frame waits the late-symbol allowance when the
12616
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
12617
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
12618
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
12619
+ // unless the gap holds a stated block's loss: the overlay may rebuild
12620
+ // that MPU's FT=0, and the block's group then complete it), or
12621
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
12622
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
12623
+ // overlay protects) waits for that overlay's repair too (BLO-52085
12624
+ // D4). The FEC check comes first: most held gaps are not behind such a
12625
+ // span, and deciding one scans both frames' bitstreams.
12626
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
12627
+ const fec = this.#fecManager;
12628
+ const { packetId, catalogTrackName } = after.meta;
12629
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
12630
+ if (!fec || allowanceMs === void 0) return void 0;
12631
+ const decision = this.#decideGap(before, after, [], false);
12632
+ const mpu = before.meta.mpuSequenceNumber;
12633
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
12634
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
12635
+ return fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true);
12636
+ }
12637
+ return decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true) : allowanceMs;
12638
+ },
12095
12639
  decide: (before, after, lostBlocks, discontinuity) => {
12096
12640
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
12097
12641
  this.#onFrameGap?.(decision);
@@ -12101,6 +12645,28 @@ var MmtpRouter = class {
12101
12645
  onRap: (packetId, catalogTrackName, ssId) => {
12102
12646
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
12103
12647
  },
12648
+ // One timer per stream, at the earliest wake asked: its drain re-arms
12649
+ // for the next frame still waiting.
12650
+ wakeAt: (packetId, catalogTrackName, atMs) => {
12651
+ if (this.#disposed) return;
12652
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
12653
+ const armed = this.#fecWakes.get(key);
12654
+ if (armed !== void 0 && armed.atMs <= atMs) return;
12655
+ if (armed !== void 0) clearTimeout(armed.timer);
12656
+ const timer = setTimeout(() => {
12657
+ this.#fecWakes.delete(key);
12658
+ this.#requestFecPoke(packetId, catalogTrackName);
12659
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
12660
+ this.#fecWakes.set(key, { atMs, timer });
12661
+ },
12662
+ // A staged switch commits on when each side's frames reach it
12663
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
12664
+ // they did unanchored.
12665
+ releaseUnanchored: (packetId, catalogTrackName) => {
12666
+ const staged = this.#staged;
12667
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
12668
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
12669
+ },
12104
12670
  onReleased: (data, meta) => {
12105
12671
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
12106
12672
  const timing = meta.authoredTiming;
@@ -12128,7 +12694,7 @@ var MmtpRouter = class {
12128
12694
  #decideGap(before, after, lostBlocks, discontinuity) {
12129
12695
  const { packetId, catalogTrackName } = after.meta;
12130
12696
  const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
12131
- const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying";
12697
+ const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying" && before.meta.movieFragmentSequenceNumber === after.meta.movieFragmentSequenceNumber;
12132
12698
  const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
12133
12699
  const evidence = (frame) => {
12134
12700
  const timing = frame.meta.authoredTiming;
@@ -12242,6 +12808,7 @@ var MmtpRouter = class {
12242
12808
  const parsed = this.#parser.parsePacket(packet);
12243
12809
  if (!parsed) return;
12244
12810
  const info = parsed.info;
12811
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
12245
12812
  if (source === "multicast" && !manifestAdmitted) {
12246
12813
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
12247
12814
  }
@@ -12523,7 +13090,8 @@ var MmtpRouter = class {
12523
13090
  parsed.header,
12524
13091
  info.sequenceNumber,
12525
13092
  info.rapFlag,
12526
- source
13093
+ source,
13094
+ fecPayloadId?.ssId
12527
13095
  );
12528
13096
  }
12529
13097
  }
@@ -12549,7 +13117,8 @@ var MmtpRouter = class {
12549
13117
  source: parserOptions?.source,
12550
13118
  deliveryProvenance: parserOptions?.deliveryProvenance,
12551
13119
  catalogTrackName: parserOptions?.catalogTrackName,
12552
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
13120
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
13121
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
12553
13122
  };
12554
13123
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
12555
13124
  else this.#parser.feed(packet, feedOptions);
@@ -12673,7 +13242,8 @@ var MmtpRouter = class {
12673
13242
  if (stream === void 0) {
12674
13243
  stream = {
12675
13244
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
12676
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
13245
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
13246
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
12677
13247
  };
12678
13248
  byName.set(catalogTrackName, stream);
12679
13249
  }
@@ -12788,8 +13358,16 @@ var MmtpRouter = class {
12788
13358
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
12789
13359
  this.#emitDirectVideo(packetId, data, meta, cb);
12790
13360
  }
12791
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
13361
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
12792
13362
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
13363
+ if (this.#isFecTrack(packetId)) {
13364
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
13365
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
13366
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
13367
+ this.#emitDirectVideo(packetId, data, meta, cb);
13368
+ return;
13369
+ }
13370
+ }
12793
13371
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
12794
13372
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
12795
13373
  this.#drainDirectRecoveredVideo(
@@ -12943,6 +13521,13 @@ var MmtpRouter = class {
12943
13521
  * frames by epoch only if pre-protection input ever matters.
12944
13522
  */
12945
13523
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
13524
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
13525
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
13526
+ result = {
13527
+ ...result,
13528
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
13529
+ };
13530
+ }
12946
13531
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
12947
13532
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
12948
13533
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -12999,7 +13584,12 @@ var MmtpRouter = class {
12999
13584
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
13000
13585
  if (ownerPacketId == null) return;
13001
13586
  if (this.#classifyPacketId(ownerPacketId) === null) return;
13002
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
13587
+ const fecSbnOf = (index) => {
13588
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
13589
+ const fecSbn = overlay.baseSsIds.get(index);
13590
+ const fecSbnFirst = overlay.firstSsIds.get(index);
13591
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
13592
+ };
13003
13593
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
13004
13594
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
13005
13595
  if (ssIdSeqOffset !== void 0) {
@@ -13007,7 +13597,10 @@ var MmtpRouter = class {
13007
13597
  ...result,
13008
13598
  symbols: result.symbols.map((sym) => {
13009
13599
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
13010
- if (wire === sym.packetSequenceNumber) return sym;
13600
+ if (wire === sym.packetSequenceNumber) {
13601
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
13602
+ return sym;
13603
+ }
13011
13604
  this.#restampedRecoveredSeqs++;
13012
13605
  this.#restampedStreams.add(streamKey);
13013
13606
  return { ...sym, packetSequenceNumber: wire };
@@ -13043,6 +13636,29 @@ var MmtpRouter = class {
13043
13636
  }
13044
13637
  );
13045
13638
  }
13639
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
13640
+ ownerPacketId,
13641
+ sym.fragment.mpuSequenceNumber,
13642
+ sym.fragment.movieFragmentSequenceNumber,
13643
+ sym.fragment.sampleNumber,
13644
+ catalogTrackName
13645
+ );
13646
+ for (const sym of result.symbols) {
13647
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
13648
+ this.#feedViaParser(
13649
+ sym.rawSymbol,
13650
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
13651
+ void 0,
13652
+ {
13653
+ skipFecPayloadId: true,
13654
+ recovered: true,
13655
+ deliveryProvenance,
13656
+ ...fecSbnOf(sym.index),
13657
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
13658
+ }
13659
+ );
13660
+ }
13661
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
13046
13662
  const gated = this.#isFecTrack(ownerPacketId);
13047
13663
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
13048
13664
  if (assembler) {