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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +29 -17
  2. package/dist/browser-runtime.js +1540 -317
  3. package/dist/browser-runtime.js.map +3 -3
  4. package/dist/catalog-fec-params.d.ts +17 -1
  5. package/dist/catalog-fec-params.d.ts.map +1 -1
  6. package/dist/catalog-fec-params.js +15 -0
  7. package/dist/catalog-fec-params.js.map +2 -2
  8. package/dist/cmaf-block-assembler.js +92 -1
  9. package/dist/cmaf-block-assembler.js.map +2 -2
  10. package/dist/cmcd-producer.d.ts +60 -47
  11. package/dist/cmcd-producer.d.ts.map +1 -1
  12. package/dist/cmcd-producer.js +138 -109
  13. package/dist/cmcd-producer.js.map +2 -2
  14. package/dist/codec-utils.d.ts.map +1 -1
  15. package/dist/codec-utils.js +92 -1
  16. package/dist/codec-utils.js.map +2 -2
  17. package/dist/delivery-catalog.js +26 -16
  18. package/dist/delivery-catalog.js.map +2 -2
  19. package/dist/delta-fallback-config.js.map +1 -1
  20. package/dist/fec-manager.d.ts +83 -15
  21. package/dist/fec-manager.d.ts.map +1 -1
  22. package/dist/fec-manager.js +446 -61
  23. package/dist/fec-manager.js.map +2 -2
  24. package/dist/fec-worker-setup.d.ts +1 -1
  25. package/dist/fec-worker-setup.js +1 -1
  26. package/dist/fec-worker-setup.js.map +1 -1
  27. package/dist/index.d.ts +4 -4
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +5 -1
  30. package/dist/index.js.map +2 -2
  31. package/dist/iso-block-locator.d.ts +48 -13
  32. package/dist/iso-block-locator.d.ts.map +1 -1
  33. package/dist/iso-block-locator.js +97 -25
  34. package/dist/iso-block-locator.js.map +2 -2
  35. package/dist/iso-bmff-timing.d.ts +10 -1
  36. package/dist/iso-bmff-timing.d.ts.map +1 -1
  37. package/dist/iso-bmff-timing.js +36 -2
  38. package/dist/iso-bmff-timing.js.map +2 -2
  39. package/dist/media-router.js.map +1 -1
  40. package/dist/mmtp-container-parser.d.ts +79 -10
  41. package/dist/mmtp-container-parser.d.ts.map +1 -1
  42. package/dist/mmtp-container-parser.js +299 -27
  43. package/dist/mmtp-container-parser.js.map +2 -2
  44. package/dist/mmtp-container-parser.no-modules.js +301 -30
  45. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  46. package/dist/mmtp-decode-pipeline.js +298 -27
  47. package/dist/mmtp-decode-pipeline.js.map +2 -2
  48. package/dist/mmtp-router.d.ts +34 -8
  49. package/dist/mmtp-router.d.ts.map +1 -1
  50. package/dist/mmtp-router.js +647 -80
  51. package/dist/mmtp-router.js.map +3 -3
  52. package/dist/multicast-manager.d.ts +26 -3
  53. package/dist/multicast-manager.d.ts.map +1 -1
  54. package/dist/multicast-manager.js +1183 -160
  55. package/dist/multicast-manager.js.map +3 -3
  56. package/dist/multicast-transport.js +28 -18
  57. package/dist/multicast-transport.js.map +2 -2
  58. package/dist/no-modules.js +298 -27
  59. package/dist/no-modules.js.map +3 -3
  60. package/dist/repair-fetch.d.ts +38 -8
  61. package/dist/repair-fetch.d.ts.map +1 -1
  62. package/dist/repair-fetch.js +286 -27
  63. package/dist/repair-fetch.js.map +3 -3
  64. package/dist/repair-layer-subscriptions.d.ts +6 -2
  65. package/dist/repair-layer-subscriptions.d.ts.map +1 -1
  66. package/dist/repair-layer-subscriptions.js +6 -3
  67. package/dist/repair-layer-subscriptions.js.map +2 -2
  68. package/dist/track-session.d.ts +1 -1
  69. package/dist/track-session.d.ts.map +1 -1
  70. package/dist/track-session.js +1 -0
  71. package/dist/track-session.js.map +2 -2
  72. package/dist/wasm-mmtp-container-parser.js +298 -27
  73. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  74. package/package.json +8 -5
  75. package/schemas/catalog.schema.json +4 -0
  76. package/src/catalog-fec-params.ts +36 -1
  77. package/src/cmcd-producer.ts +189 -179
  78. package/src/codec-utils.ts +121 -1
  79. package/src/fec-manager.ts +487 -35
  80. package/src/fec-worker-setup.ts +2 -2
  81. package/src/index.ts +9 -2
  82. package/src/iso-block-locator.ts +133 -31
  83. package/src/iso-bmff-timing.ts +40 -1
  84. package/src/mmtp-container-parser.ts +306 -29
  85. package/src/mmtp-router.ts +548 -38
  86. package/src/multicast-manager.ts +134 -16
  87. package/src/repair-fetch.ts +366 -50
  88. package/src/repair-layer-subscriptions.ts +13 -5
  89. package/src/track-session.ts +4 -1
@@ -1610,14 +1610,15 @@ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
1610
1610
  });
1611
1611
 
1612
1612
  // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
1613
+ var MAX_PENDING_PACKETS = 256;
1613
1614
  var AMTGatewayManager = class {
1614
1615
  subscriptions = /* @__PURE__ */ new Map();
1615
1616
  messageHandler;
1617
+ messageListenerRegistered = false;
1616
1618
  pendingPackets = /* @__PURE__ */ new Map();
1617
1619
  constructor() {
1618
1620
  this.messageHandler = (event) => {
1619
1621
  const data = event.data;
1620
- console.log(`[AMT] SW message received:`, data.type);
1621
1622
  if (data.type === "UDP_PACKET") {
1622
1623
  this.handlePacket(data);
1623
1624
  } else if (data.type === "SOCKET_ERROR") {
@@ -1626,12 +1627,22 @@ var AMTGatewayManager = class {
1626
1627
  console.log(`[AMT SW Debug] ${data.message}`);
1627
1628
  }
1628
1629
  };
1629
- if (typeof navigator !== "undefined" && navigator.serviceWorker) {
1630
- navigator.serviceWorker.addEventListener("message", this.messageHandler);
1631
- console.log("[AMT] Registered service worker message handler");
1632
- } else {
1633
- console.warn("[AMT] Service worker not available");
1630
+ }
1631
+ ensureMessageListener() {
1632
+ if (this.messageListenerRegistered || typeof navigator === "undefined" || !navigator.serviceWorker || !this.messageHandler) {
1633
+ return;
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);
1634
1644
  }
1645
+ this.messageListenerRegistered = false;
1635
1646
  }
1636
1647
  /**
1637
1648
  * Subscribe via AMT tunnel
@@ -1641,6 +1652,7 @@ var AMTGatewayManager = class {
1641
1652
  if (config.protected) {
1642
1653
  throw new Error("AMTGatewayManager refuses a protected join: it reports no per-datagram sender (multicast-02 7.2.7)");
1643
1654
  }
1655
+ this.ensureMessageListener();
1644
1656
  const keyStr = this.getKeyString(key);
1645
1657
  if (this.subscriptions.has(keyStr)) {
1646
1658
  console.log(`[AMT] Reusing existing subscription to ${keyStr}`);
@@ -1676,6 +1688,8 @@ var AMTGatewayManager = class {
1676
1688
  this.subscriptions.delete(keyStr);
1677
1689
  this.pendingPackets.delete(subscription.subscriptionId);
1678
1690
  }
1691
+ if (this.subscriptions.size === 0)
1692
+ this.removeMessageListener();
1679
1693
  throw new Error(`Failed to subscribe via AMT: ${error instanceof Error ? error.message : String(error)}`);
1680
1694
  }
1681
1695
  }
@@ -1697,6 +1711,8 @@ var AMTGatewayManager = class {
1697
1711
  } finally {
1698
1712
  this.subscriptions.delete(handle);
1699
1713
  this.pendingPackets.delete(subscription.subscriptionId);
1714
+ if (this.subscriptions.size === 0)
1715
+ this.removeMessageListener();
1700
1716
  }
1701
1717
  }
1702
1718
  /**
@@ -1713,14 +1729,12 @@ var AMTGatewayManager = class {
1713
1729
  if (!subscriptionId)
1714
1730
  return;
1715
1731
  const subscription = this.subscriptions.get(subscriptionId);
1716
- if (!subscription) {
1717
- console.warn(`[AMT] Received packet for unknown subscription: ${subscriptionId}`);
1732
+ if (!subscription)
1718
1733
  return;
1719
- }
1720
1734
  if (!subscription.handshakeComplete) {
1721
1735
  const queue = this.pendingPackets.get(subscriptionId);
1722
1736
  const packetData2 = data;
1723
- if (queue) {
1737
+ if (queue && queue.length < MAX_PENDING_PACKETS) {
1724
1738
  queue.push({
1725
1739
  data: packetData2.data,
1726
1740
  remoteAddress: packetData2.remoteAddress,
@@ -1746,19 +1760,15 @@ var AMTGatewayManager = class {
1746
1760
  if (!subscriptionId)
1747
1761
  return;
1748
1762
  const subscription = this.subscriptions.get(subscriptionId);
1749
- if (!subscription) {
1750
- console.warn(`[AMT] Received error for unknown subscription: ${subscriptionId}`);
1763
+ if (!subscription)
1751
1764
  return;
1752
- }
1753
1765
  subscription.config.onError(new Error(error || "Unknown error"));
1754
1766
  }
1755
1767
  /**
1756
1768
  * Cleanup on destroy
1757
1769
  */
1758
1770
  destroy() {
1759
- if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
1760
- navigator.serviceWorker.removeEventListener("message", this.messageHandler);
1761
- }
1771
+ this.removeMessageListener();
1762
1772
  const handles = Array.from(this.subscriptions.keys());
1763
1773
  for (const handle of handles) {
1764
1774
  this.unsubscribe(handle).catch((err) => {
@@ -4817,9 +4827,10 @@ function isH264IntraSlice(nal) {
4817
4827
  const sliceType = readH264SliceType(nal);
4818
4828
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
4819
4829
  }
4830
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
4820
4831
  function readH264SliceType(nal) {
4821
4832
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
4822
- const rbsp = removeEmulationPrevention(nal.subarray(1));
4833
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
4823
4834
  const state = { bitOffset: 0 };
4824
4835
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
4825
4836
  return readUnsignedExpGolomb(rbsp, state);
@@ -4966,6 +4977,96 @@ if (void 0) {
4966
4977
  ]))).toBe(false);
4967
4978
  });
4968
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
+ });
4969
5070
  describe("avccToAnnexB", () => {
4970
5071
  test("converts with SPS/PPS on keyframe", () => {
4971
5072
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -7667,9 +7768,21 @@ var IsoBmffTimingResolver = class {
7667
7768
  }
7668
7769
  #track = null;
7669
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();
7670
7779
  #pendingSamples = 0;
7671
7780
  #evictedSamples = 0;
7672
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
+ }
7673
7786
  get pendingSampleCount() {
7674
7787
  return this.#pendingSamples;
7675
7788
  }
@@ -7693,7 +7806,14 @@ var IsoBmffTimingResolver = class {
7693
7806
  this.#track = timing;
7694
7807
  return true;
7695
7808
  }
7696
- 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) {
7697
7817
  this.#lastMovieFragmentRejection = null;
7698
7818
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
7699
7819
  this.#lastMovieFragmentRejection = "invalid";
@@ -7719,6 +7839,8 @@ var IsoBmffTimingResolver = class {
7719
7839
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
7720
7840
  );
7721
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;
7722
7844
  let freed = 0;
7723
7845
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
7724
7846
  freed += this.#evictOldestFragment();
@@ -7732,6 +7854,7 @@ var IsoBmffTimingResolver = class {
7732
7854
  return false;
7733
7855
  }
7734
7856
  this.#fragments.set(key, [...parsed.samples]);
7857
+ this.#firstSamples.set(key, parsed.samples[0]);
7735
7858
  this.#pendingSamples += parsed.samples.length;
7736
7859
  return true;
7737
7860
  }
@@ -7789,6 +7912,7 @@ var IsoBmffTimingResolver = class {
7789
7912
  let live = 0;
7790
7913
  for (const sample of samples) if (sample !== null) live++;
7791
7914
  this.#fragments.delete(oldest);
7915
+ this.#firstSamples.delete(oldest);
7792
7916
  this.#pendingSamples -= live;
7793
7917
  this.#evictedSamples += live;
7794
7918
  return live;
@@ -7804,12 +7928,23 @@ var IsoBmffTimingResolver = class {
7804
7928
  if (!samples || !samples[index]) return false;
7805
7929
  samples[index] = null;
7806
7930
  this.#pendingSamples--;
7807
- 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
+ }
7808
7941
  return true;
7809
7942
  }
7810
7943
  reset() {
7811
7944
  this.#track = null;
7812
7945
  this.#fragments.clear();
7946
+ this.#firstSamples.clear();
7947
+ this.#delivered.clear();
7813
7948
  this.#pendingSamples = 0;
7814
7949
  }
7815
7950
  };
@@ -7979,6 +8114,9 @@ function authoredGap(before, after) {
7979
8114
  function ssIdAfter(a, b) {
7980
8115
  return (a - b | 0) > 0;
7981
8116
  }
8117
+ function holdsRebuilt(stream) {
8118
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
8119
+ }
7982
8120
  var FecReleaseSequencer = class {
7983
8121
  #streams = /* @__PURE__ */ new Map();
7984
8122
  #gate;
@@ -8041,6 +8179,7 @@ var FecReleaseSequencer = class {
8041
8179
  stream.lastSbn = void 0;
8042
8180
  stream.discontinuity = false;
8043
8181
  stream.rapSsId = void 0;
8182
+ stream.sourced = false;
8044
8183
  }
8045
8184
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
8046
8185
  this.#recordStat("droppedStale");
@@ -8067,6 +8206,7 @@ var FecReleaseSequencer = class {
8067
8206
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
8068
8207
  else hi = mid;
8069
8208
  }
8209
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
8070
8210
  stream.buf.splice(lo, 0, frame);
8071
8211
  this.#drainUnlessDeferred(stream);
8072
8212
  }
@@ -8102,6 +8242,41 @@ var FecReleaseSequencer = class {
8102
8242
  }
8103
8243
  return false;
8104
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
+ }
8105
8280
  /** Re-evaluate held gaps after FEC state changed. */
8106
8281
  poke(streamKey) {
8107
8282
  if (streamKey !== void 0) {
@@ -8193,16 +8368,32 @@ var FecReleaseSequencer = class {
8193
8368
  last: null,
8194
8369
  lastSbn: void 0,
8195
8370
  discontinuity: false,
8196
- rapSsId: void 0
8371
+ rapSsId: void 0,
8372
+ sourced: false,
8373
+ draining: 0
8197
8374
  };
8198
8375
  this.#streams.set(streamKey, stream);
8199
8376
  }
8200
8377
  return stream;
8201
8378
  }
8202
- #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) {
8203
8389
  while (stream.buf.length > 0 && stream.last !== null) {
8204
8390
  const head = stream.buf[0];
8205
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
+ }
8206
8397
  if (stream.discontinuity) {
8207
8398
  stream.discontinuity = false;
8208
8399
  stream.buf.shift();
@@ -8216,9 +8407,10 @@ var FecReleaseSequencer = class {
8216
8407
  }
8217
8408
  const headSbn = head.meta.fecSbn;
8218
8409
  const from = stream.lastSbn ?? headSbn;
8219
- const to = headSbn ?? stream.lastSbn;
8410
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
8220
8411
  let lost = [];
8221
8412
  const unanchored = from === void 0 && to === void 0;
8413
+ let unresolved = false;
8222
8414
  if (from !== void 0 && to !== void 0) {
8223
8415
  const resolved = this.#gate.resolvedLoss(
8224
8416
  stream.packetId,
@@ -8227,7 +8419,8 @@ var FecReleaseSequencer = class {
8227
8419
  Math.max(from, to),
8228
8420
  from
8229
8421
  );
8230
- if (resolved === null) {
8422
+ unresolved = resolved === null;
8423
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored)) {
8231
8424
  const heldMs = performance.now() - head.arrivedAtMs;
8232
8425
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
8233
8426
  this.#recordStat("forcedWindowFlushes");
@@ -8235,22 +8428,56 @@ var FecReleaseSequencer = class {
8235
8428
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
8236
8429
  continue;
8237
8430
  }
8238
- lost = resolved;
8431
+ lost = resolved ?? [];
8239
8432
  }
8240
8433
  stream.buf.shift();
8241
8434
  this.#release(
8242
8435
  stream,
8243
8436
  head,
8244
- 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
8245
8438
  );
8246
8439
  }
8247
8440
  }
8441
+ /**
8442
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
8443
+ * source cursor holds it unanchored, and neither does a later frame behind
8444
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
8445
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
8446
+ * like each frame that arrived in front of it since (stale there). The head
8447
+ * then goes, decided as it would be unanchored, once a frame the base path
8448
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
8449
+ * marked one: the base path has passed that one, so a frame still missing
8450
+ * before it can only come from a repair. It also goes while no source frame
8451
+ * has been released, when the direct path shows a recovered frame at once.
8452
+ * And it goes at once while a staged switch decides on when frames arrive
8453
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
8454
+ * sink being replaced: unanchored, it had already reached the sink.
8455
+ * The scan also writes: the `passed` marks it sets stay on the frames,
8456
+ * and push marks a frame it inserts in front of a marked one from them.
8457
+ */
8458
+ #cursorPassed(stream, asUnanchored) {
8459
+ let at = -1;
8460
+ for (let i = 0; i < stream.buf.length; i++) {
8461
+ const frame = stream.buf[i];
8462
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
8463
+ frame.passed = true;
8464
+ if (at < 0) at = i;
8465
+ } else if (frame.passed !== true) break;
8466
+ }
8467
+ if (at < 0) return false;
8468
+ 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));
8469
+ }
8248
8470
  #release(stream, frame, decision) {
8471
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
8472
+ if (stale) this.#recordStat("droppedStale");
8249
8473
  if (decision) frame.meta.gapBefore = decision;
8250
8474
  stream.last = frame;
8251
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
8475
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
8476
+ stream.lastSbn = frame.meta.fecSbn;
8477
+ }
8478
+ if (frame.meta.recovered !== true) stream.sourced = true;
8252
8479
  this.#gate.onReleased?.(frame.data, frame.meta);
8253
- this.#emit(frame.data, frame.meta);
8480
+ if (!stale) this.#emit(frame.data, frame.meta);
8254
8481
  }
8255
8482
  };
8256
8483
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -8291,6 +8518,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
8291
8518
  this.#reclaimedTimingSamples = 0;
8292
8519
  this.#evictedTimingSamples = 0;
8293
8520
  this.#rejectedMovieFragments = 0;
8521
+ this.#recoveredHeadsAwaitingTiming = {
8522
+ held: 0,
8523
+ expired: 0,
8524
+ discarded: 0,
8525
+ superseded: 0
8526
+ };
8294
8527
  this.#sequencers = /* @__PURE__ */ new Map();
8295
8528
  this.#fecGate = null;
8296
8529
  this.#fecSequencer = null;
@@ -8399,6 +8632,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
8399
8632
  #reclaimedTimingSamples;
8400
8633
  #evictedTimingSamples;
8401
8634
  #rejectedMovieFragments;
8635
+ #recoveredHeadsAwaitingTiming;
8402
8636
  #sequencers;
8403
8637
  #fecGate;
8404
8638
  #fecSequencer;
@@ -8504,11 +8738,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
8504
8738
  /**
8505
8739
  * Typed view of the ISO-BMFF timing-sample budget.
8506
8740
  *
8507
- * This is the acceptance signal for the budget ratchet: `pending` walking
8508
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
8509
- * and it is observable here rather than only as media silently stopping.
8510
- * Per repo policy this is a producer-owned counter -- never infer budget
8511
- * state by parsing logs.
8741
+ * Each stream admits timing against its own window of `capacity` slots
8742
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
8743
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
8744
+ * timing a stream declared and never delivered shows up there. `pending`
8745
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
8746
+ * a producer-owned counter -- never infer budget state by parsing logs.
8512
8747
  */
8513
8748
  get timingBudgetStats() {
8514
8749
  return {
@@ -8519,6 +8754,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
8519
8754
  rejectedMovieFragments: this.#rejectedMovieFragments
8520
8755
  };
8521
8756
  }
8757
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
8758
+ get recoveredHeadsAwaitingTiming() {
8759
+ let pending = 0;
8760
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
8761
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
8762
+ }
8763
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
8764
+ }
8522
8765
  get reorderStats() {
8523
8766
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
8524
8767
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -8560,6 +8803,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
8560
8803
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
8561
8804
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
8562
8805
  }
8806
+ /** See FecReleaseSequencer.unsource. */
8807
+ unsourceFecRelease(packetId, catalogTrackName) {
8808
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
8809
+ }
8810
+ /** See FecReleaseSequencer.holdsRebuilt. */
8811
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
8812
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
8813
+ }
8563
8814
  /** Re-evaluate held gaps after FEC block state changed. */
8564
8815
  pokeFecRelease(packetId, catalogTrackName) {
8565
8816
  if (!this.#fecSequencer) return;
@@ -8692,7 +8943,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
8692
8943
  const now = Date.now();
8693
8944
  for (const { awaitingTiming } of this.#timingStreams.values()) {
8694
8945
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
8695
- awaitingTiming.shift();
8946
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
8696
8947
  }
8697
8948
  }
8698
8949
  }
@@ -8810,11 +9061,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
8810
9061
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
8811
9062
  return this.#drop("fragment-unexpected-fragmentation");
8812
9063
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
8813
- if (!resolver2) return this.#drop("fragment-no-resolver");
9064
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
8814
9065
  const pendingBefore = resolver2.pendingSampleCount;
8815
9066
  const evictedBefore = resolver2.evictedSampleCount;
8816
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
8817
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
9067
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
9068
+ const admitted = resolver2.addMovieFragment(
9069
+ mpu.mpuSequenceNumber,
9070
+ data,
9071
+ remaining,
9072
+ options?.recovered === true
9073
+ );
8818
9074
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
8819
9075
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
8820
9076
  if (!admitted) {
@@ -8834,7 +9090,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
8834
9090
  };
8835
9091
  }
8836
9092
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
8837
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
9093
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
8838
9094
  if (!resolver) return this.#drop("mfu-no-resolver");
8839
9095
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
8840
9096
  return this.#drop("mfu-empty-payload");
@@ -8855,6 +9111,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
8855
9111
  mpuSequenceNumber: mpu.mpuSequenceNumber,
8856
9112
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
8857
9113
  sampleNumber: mfuDuHeader.sampleNumber,
9114
+ sequenceNumber: info.sequenceNumber,
8858
9115
  arrivedAt: Date.now()
8859
9116
  });
8860
9117
  return this.#drop("mfu-sample-timing-missing");
@@ -8880,7 +9137,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
8880
9137
  info,
8881
9138
  resolver,
8882
9139
  options?.recovered === true,
8883
- options?.fecSbn
9140
+ options?.fecSbn,
9141
+ options?.fecSbnFirst
8884
9142
  );
8885
9143
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
8886
9144
  }
@@ -8973,7 +9231,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
8973
9231
  info,
8974
9232
  resolver,
8975
9233
  options?.recovered === true,
8976
- options?.fecSbn
9234
+ options?.fecSbn,
9235
+ options?.fecSbnFirst
8977
9236
  );
8978
9237
  if (outcome.record !== void 0) return outcome.record;
8979
9238
  return this.#drop(outcome.reason);
@@ -8993,7 +9252,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
8993
9252
  * attribution exists to keep readable. Leaving the choice at the call site
8994
9253
  * is what keeps both true.
8995
9254
  */
8996
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
9255
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
8997
9256
  const timing = resolver.sampleTiming(
8998
9257
  combined.mpuSequenceNumber,
8999
9258
  combined.movieFragmentSequenceNumber,
@@ -9010,6 +9269,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
9010
9269
  );
9011
9270
  if (!meta) return { reason: "combined-meta-build-failed" };
9012
9271
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
9272
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
9013
9273
  if (!resolver.consumeSample(
9014
9274
  combined.mpuSequenceNumber,
9015
9275
  combined.movieFragmentSequenceNumber,
@@ -9178,6 +9438,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
9178
9438
  }
9179
9439
  this.#emitFrame(data, meta);
9180
9440
  }
9441
+ /** Whether FT=1 metadata already names this sample, without claiming it. */
9442
+ hasAuthoredTimingFor(packetId, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber, catalogTrackName) {
9443
+ return this.#timingResolver(this.#streamKey(packetId, catalogTrackName), packetId, false)?.sampleTiming(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber) != null;
9444
+ }
9181
9445
  /**
9182
9446
  * Claim and return the authored timing for a recovered sample. Recovery does
9183
9447
  * not pass through the ordinary `feed()` completion path, so it must retire
@@ -9239,6 +9503,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
9239
9503
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
9240
9504
  this.#sequencers.clear();
9241
9505
  this.#fecSequencer?.discard();
9506
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
9507
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
9508
+ }
9242
9509
  this.#timingStreams.clear();
9243
9510
  this.#pendingTimingSamples = 0;
9244
9511
  this.#reliableMoqStartupGate.clear();
@@ -9257,10 +9524,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
9257
9524
  return resolver;
9258
9525
  }
9259
9526
  #awaitTiming(streamKey, head) {
9260
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
9261
- if (!awaitingTiming) return;
9527
+ const state = this.#timingStreams.get(streamKey);
9528
+ if (!state) return;
9529
+ if (!head.options?.recovered) {
9530
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
9531
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
9532
+ state.awaitingTiming = kept;
9533
+ }
9534
+ const awaitingTiming = state.awaitingTiming;
9262
9535
  awaitingTiming.push(head);
9263
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
9536
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
9537
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
9538
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
9539
+ }
9540
+ }
9541
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
9542
+ #leaveAwaitingTiming(head, outcome) {
9543
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
9264
9544
  }
9265
9545
  /**
9266
9546
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -9288,6 +9568,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
9288
9568
  const state = this.#timingStreams.get(streamKey);
9289
9569
  if (!state) return;
9290
9570
  this.#timingStreams.delete(streamKey);
9571
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
9291
9572
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
9292
9573
  if (this.#pendingTimingSamples < 0) {
9293
9574
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -9828,7 +10109,18 @@ function keyframeOverlaySsId(header) {
9828
10109
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
9829
10110
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
9830
10111
  }
10112
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
10113
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
10114
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
10115
+ }
10116
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
10117
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
10118
+ return headerPsn + offset >>> 0;
10119
+ }
10120
+ var OVERLAY_ROUTED_LIMIT = 1024;
10121
+ var OVERLAY_PENDING_LIMIT = 256;
9831
10122
  var OVERLAY_OFFSET_MPUS = 16;
10123
+ var OVERLAY_REBUILT_LIMIT = 256;
9832
10124
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
9833
10125
  function assertStreamIdentity(role, stream) {
9834
10126
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -9939,6 +10231,7 @@ var MmtpRouter = class {
9939
10231
  #provenance = /* @__PURE__ */ new Map();
9940
10232
  #onFlowProtected = null;
9941
10233
  #unadmittedListedDrops = 0;
10234
+ #admittedSourceDatagrams = 0;
9942
10235
  #unlistedRepairSetAside = 0;
9943
10236
  #assistBlocks = /* @__PURE__ */ new Map();
9944
10237
  #assistFailures = /* @__PURE__ */ new Map();
@@ -9995,6 +10288,26 @@ var MmtpRouter = class {
9995
10288
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
9996
10289
  */
9997
10290
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
10291
+ /**
10292
+ * Per stream, the SS_ID offset at which a base recovery last showed the
10293
+ * sender's own packet_sequence_number: a recovered packet's header psn
10294
+ * equal to its SS_ID minus that offset. While it equals the stream's
10295
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
10296
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
10297
+ * an MPU no member of which arrived).
10298
+ */
10299
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
10300
+ /**
10301
+ * The same, shown by the overlay alone, before any base recovery did: a
10302
+ * packet it rebuilt whose base copy carries its protected psn
10303
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
10304
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
10305
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
10306
+ * make the base drop a late base copy of a keyframe the overlay never
10307
+ * finished, and lift a block's late-source cut, which nothing before
10308
+ * this offset did.
10309
+ */
10310
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
9998
10311
  /**
9999
10312
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
10000
10313
  * not parsed, typically because its overlap copy was parsed first
@@ -10064,7 +10377,9 @@ var MmtpRouter = class {
10064
10377
  recovered: 0,
10065
10378
  restarts: 0,
10066
10379
  unsequencedDropped: 0,
10067
- protectedDropped: 0
10380
+ protectedDropped: 0,
10381
+ baseFed: 0,
10382
+ baseUndetermined: 0
10068
10383
  };
10069
10384
  /** Callback fired when a delta-track FEC block completes or fails. */
10070
10385
  #onDeltaBlockCompleteCb = null;
@@ -10237,7 +10552,7 @@ var MmtpRouter = class {
10237
10552
  const cb = this.#getFrameCallback(packetId);
10238
10553
  if (isVideo && !assembler) {
10239
10554
  if (frameMeta.recovered) {
10240
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
10555
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
10241
10556
  } else {
10242
10557
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
10243
10558
  }
@@ -10270,13 +10585,18 @@ var MmtpRouter = class {
10270
10585
  this.#onDeltaBlockCompleteCb?.(packetId, false);
10271
10586
  }
10272
10587
  };
10273
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
10588
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
10274
10589
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
10275
10590
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
10276
10591
  this.#onDeltaBlockCompleteCb?.(packetId, true);
10277
10592
  }
10278
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
10279
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
10593
+ if (span === void 0) {
10594
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
10595
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
10596
+ } else {
10597
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
10598
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
10599
+ }
10280
10600
  };
10281
10601
  }
10282
10602
  }
@@ -10321,8 +10641,9 @@ var MmtpRouter = class {
10321
10641
  }
10322
10642
  /**
10323
10643
  * FEC-recovered source symbols whose reconstructed header named a
10324
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
10325
- * a hop re-stamped the sequence after the sender protected the packet.
10644
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
10645
+ * or, rebuilt by the overlay, than their base copy carries: a hop
10646
+ * re-stamped the sequence after the sender protected the packet.
10326
10647
  */
10327
10648
  get restampedRecoveredSequenceCount() {
10328
10649
  return this.#restampedRecoveredSeqs;
@@ -10501,6 +10822,7 @@ var MmtpRouter = class {
10501
10822
  enableMseAssembler(packetId, config, catalogTrackName) {
10502
10823
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
10503
10824
  const previous = this.#mseAssemblers.get(assemblerKey);
10825
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
10504
10826
  if (previous) {
10505
10827
  previous.flush();
10506
10828
  previous.dispose();
@@ -10627,6 +10949,10 @@ var MmtpRouter = class {
10627
10949
  get keyframeOverlayStats() {
10628
10950
  return { ...this.#overlayStats };
10629
10951
  }
10952
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
10953
+ get recoveredHeadsAwaitingTiming() {
10954
+ return this.#parser.recoveredHeadsAwaitingTiming;
10955
+ }
10630
10956
  #isOverlayRepair(repairPacketId, repairTrackName) {
10631
10957
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
10632
10958
  }
@@ -10647,7 +10973,8 @@ var MmtpRouter = class {
10647
10973
  fec,
10648
10974
  k,
10649
10975
  offsets: /* @__PURE__ */ new Map(),
10650
- moqBlocks: /* @__PURE__ */ new Set()
10976
+ moqBlocks: /* @__PURE__ */ new Set(),
10977
+ rebuilt: /* @__PURE__ */ new Map()
10651
10978
  };
10652
10979
  this.#overlays.set(repairPacketId, inst);
10653
10980
  return () => {
@@ -10677,12 +11004,18 @@ var MmtpRouter = class {
10677
11004
  */
10678
11005
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
10679
11006
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
11007
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
11008
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
11009
+ stream.overlayToBase.routed.clear();
11010
+ stream.overlayToBase.pending.clear();
11011
+ }
10680
11012
  }
10681
11013
  #resetOverlay(inst) {
10682
11014
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
10683
11015
  inst.last = void 0;
10684
11016
  inst.offsets.clear();
10685
11017
  inst.moqBlocks.clear();
11018
+ inst.rebuilt.clear();
10686
11019
  }
10687
11020
  #overlaysForSource(sourcePacketId, catalogTrackName) {
10688
11021
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -10733,18 +11066,33 @@ var MmtpRouter = class {
10733
11066
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
10734
11067
  * every overlay installed for its source, at that SS_ID, with the bytes the
10735
11068
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
10736
- * included (7.1, 7.4.3).
10737
- */
10738
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
11069
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
11070
+ * FEC reads it.
11071
+ *
11072
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
11073
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
11074
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
11075
+ * the stream unstamped at the SS_ID offset it states, for the release gate
11076
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
11077
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
11078
+ */
11079
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
10739
11080
  if (this.#overlays.size === 0) return;
10740
11081
  const ssId = keyframeOverlaySsId(header);
10741
11082
  if (ssId === void 0) return;
11083
+ let rebuiltPsn;
10742
11084
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
10743
11085
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
11086
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
11087
+ inst.rebuilt.delete(ssId);
10744
11088
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
10745
11089
  if (identity !== null) {
10746
11090
  inst.offsets.delete(identity.mpuSequenceNumber);
10747
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
11091
+ inst.offsets.set(identity.mpuSequenceNumber, {
11092
+ psnOffset: ssId - sequenceNumber >>> 0,
11093
+ overlaySsId: ssId,
11094
+ ...baseSsId === void 0 ? {} : { baseSsId }
11095
+ });
10748
11096
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
10749
11097
  }
10750
11098
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -10766,6 +11114,14 @@ var MmtpRouter = class {
10766
11114
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
10767
11115
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
10768
11116
  }
11117
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
11118
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
11119
+ if (rebuiltPsn !== sequenceNumber) {
11120
+ this.#restampedRecoveredSeqs++;
11121
+ } else if (baseSsId !== void 0) {
11122
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
11123
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
11124
+ }
10769
11125
  }
10770
11126
  #noteOverlayMoqBlock(inst, blockStart) {
10771
11127
  inst.moqBlocks.add(blockStart);
@@ -10799,11 +11155,16 @@ var MmtpRouter = class {
10799
11155
  }
10800
11156
  /**
10801
11157
  * Route an overlay-recovered block's packets as source media of the
10802
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
10803
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
10804
- * base re-stamp, no block advance. Each packet's wire sequence is restored
10805
- * from its keyframe's own offset; without one, a stream the base never
10806
- * re-stamped keeps the header's sequence and any other drops the packet.
11158
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
11159
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
11160
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
11161
+ * base FEC recovered does, so it waits behind base frames still in flight,
11162
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
11163
+ * longer than unanchored; one whose base SS_ID is undetermined has no
11164
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
11165
+ * advance. Each packet's wire sequence is restored from its keyframe's own
11166
+ * offset; without one, a stream the base never re-stamped keeps the
11167
+ * header's sequence and any other drops the packet.
10807
11168
  */
10808
11169
  #routeOverlayRecovered(inst, blockStart, recovered) {
10809
11170
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -10823,22 +11184,139 @@ var MmtpRouter = class {
10823
11184
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
10824
11185
  const restamped = this.#restampedStreams.has(streamKey);
10825
11186
  const restored = /* @__PURE__ */ new Set();
11187
+ const baseSsIds = /* @__PURE__ */ new Map();
11188
+ const gateOnly = /* @__PURE__ */ new Set();
10826
11189
  const symbols = result.symbols.flatMap((sym) => {
10827
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
10828
- if (offset !== void 0) {
10829
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
11190
+ const overlaySsId = serial32Add(blockStart, sym.index);
11191
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
11192
+ if (anchor !== void 0) {
11193
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
10830
11194
  restored.add(packetSequenceNumber);
10831
- return [{ ...sym, packetSequenceNumber }];
11195
+ const out = { ...sym, packetSequenceNumber };
11196
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
11197
+ if (baseSsId !== void 0) {
11198
+ baseSsIds.set(sym.index, baseSsId);
11199
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
11200
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
11201
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
11202
+ }
11203
+ }
11204
+ return [out];
11205
+ }
11206
+ if (!restamped) {
11207
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
11208
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
11209
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
11210
+ if (baseSsId !== void 0) {
11211
+ baseSsIds.set(sym.index, baseSsId);
11212
+ if (fedSsId === void 0) gateOnly.add(sym.index);
11213
+ } else {
11214
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
11215
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
11216
+ }
11217
+ return [sym];
10832
11218
  }
10833
- if (!restamped) return [sym];
10834
11219
  this.#overlayStats.unsequencedDropped++;
10835
11220
  return [];
10836
11221
  });
10837
11222
  this.#overlayStats.recovered++;
11223
+ const mpuFirst = /* @__PURE__ */ new Map();
11224
+ for (const sym of symbols) {
11225
+ const ssId = baseSsIds.get(sym.index);
11226
+ const mpu = sym.fragment.mpuSequenceNumber;
11227
+ const first = mpuFirst.get(mpu);
11228
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
11229
+ }
11230
+ const firstSsIds = /* @__PURE__ */ new Map();
11231
+ for (const sym of symbols) {
11232
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
11233
+ }
10838
11234
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
10839
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
11235
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
11236
+ baseSsIds,
11237
+ firstSsIds
10840
11238
  });
10841
11239
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
11240
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
11241
+ }
11242
+ /**
11243
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
11244
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
11245
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
11246
+ * base recovery showed; `baseSsIds` holds no other),
11247
+ * so it is fed to the base decoder as a rebuilt source
11248
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
11249
+ * fewer to solve, and its repair can recover the block's other packets.
11250
+ * A base block no repair has stated yet takes it when one does
11251
+ * (#feedPendingRebuilt).
11252
+ *
11253
+ * The overlay route already handled each packet fed (delivered it, or
11254
+ * held an untimed head for its FT=1), so a base recovery routes none of
11255
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
11256
+ * held head would wait in the parser for timing its first copy consumed.
11257
+ * Only an overlay block decoded from multicast symbols alone is fed: with
11258
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
11259
+ * that crossed no multicast socket, which the provenance counted from the
11260
+ * block's own arrivals cannot show.
11261
+ */
11262
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
11263
+ const fec = this.#fecManager;
11264
+ const owner = inst.leg.sourcePacketId;
11265
+ const name = inst.leg.sourceCatalogTrackName;
11266
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
11267
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
11268
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
11269
+ const feeds = [];
11270
+ for (const sym of symbols) {
11271
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
11272
+ const ssId = baseSsIds.get(sym.index);
11273
+ if (ssId === void 0) {
11274
+ this.#overlayStats.baseUndetermined++;
11275
+ continue;
11276
+ }
11277
+ routed.delete(ssId);
11278
+ routed.add(ssId);
11279
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
11280
+ feeds.push([ssId, sym.rawSymbol]);
11281
+ }
11282
+ for (const [ssId, symbolData] of feeds) {
11283
+ if (this.#classifyPacketId(owner) === null) return;
11284
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
11285
+ }
11286
+ }
11287
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
11288
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
11289
+ const fec = this.#fecManager;
11290
+ if (!fec?.feedRebuiltSourceSymbol) return;
11291
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
11292
+ if (coords == null) {
11293
+ const pending = this.#stream(owner, name).overlayToBase.pending;
11294
+ pending.delete(ssId);
11295
+ pending.set(ssId, symbolData.slice());
11296
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
11297
+ return;
11298
+ }
11299
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
11300
+ if (!fed.taken) return;
11301
+ this.#overlayStats.baseFed++;
11302
+ if (fed.recovered === null) return;
11303
+ const sbn = coords.sbn;
11304
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
11305
+ fec.cancelBlockTimeout(sbn, owner, name);
11306
+ fec.countRecovery(owner, sbn, name);
11307
+ fec.markBlockCompleted(sbn, owner, name);
11308
+ });
11309
+ }
11310
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
11311
+ #feedPendingRebuilt(owner, name, block) {
11312
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
11313
+ if (pending === void 0 || pending.size === 0) return;
11314
+ for (const [ssId, symbolData] of [...pending]) {
11315
+ if (this.#classifyPacketId(owner) === null) return;
11316
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
11317
+ pending.delete(ssId);
11318
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
11319
+ }
10842
11320
  }
10843
11321
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
10844
11322
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -10978,6 +11456,10 @@ var MmtpRouter = class {
10978
11456
  get unadmittedListedDropCount() {
10979
11457
  return this.#unadmittedListedDrops;
10980
11458
  }
11459
+ /** 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. */
11460
+ get admittedSourceDatagramCount() {
11461
+ return this.#admittedSourceDatagrams;
11462
+ }
10981
11463
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
10982
11464
  get unlistedRepairSetAsideCount() {
10983
11465
  return this.#unlistedRepairSetAside;
@@ -11464,6 +11946,8 @@ var MmtpRouter = class {
11464
11946
  )) return;
11465
11947
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
11466
11948
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
11949
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
11950
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
11467
11951
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
11468
11952
  const recovered = fec.feedRepairSymbol(
11469
11953
  ownerPacketId,
@@ -11514,7 +11998,7 @@ var MmtpRouter = class {
11514
11998
  catalogTrackName
11515
11999
  )) continue;
11516
12000
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
11517
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
12001
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
11518
12002
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
11519
12003
  }
11520
12004
  if (payload.oversized) continue;
@@ -11601,6 +12085,8 @@ var MmtpRouter = class {
11601
12085
  this.#droppedPreSyncVideo.delete(streamKey);
11602
12086
  this.#latestVideoSeqByStream.delete(streamKey);
11603
12087
  this.#ssIdSeqOffsetByStream.delete(streamKey);
12088
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
12089
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
11604
12090
  this.#multicastRapTwinByStream.delete(streamKey);
11605
12091
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
11606
12092
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -11727,6 +12213,12 @@ var MmtpRouter = class {
11727
12213
  * the outgoing stream stops. The hold is bounded by the incoming stream's
11728
12214
  * own RAP cadence, so no timer is involved.
11729
12215
  *
12216
+ * While the switch is staged, the FEC release gate lets a keyframe the
12217
+ * overlay rebuilt reach it, on either side, when the keyframe did before
12218
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
12219
+ * decides on what each side delivered, and the commit discards the gate's
12220
+ * frames of the outgoing stream.
12221
+ *
11730
12222
  * The commit is one synchronous transition inside the frame path: the
11731
12223
  * outgoing stream's already-admitted frames are released (its queued FEC
11732
12224
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -11777,6 +12269,9 @@ var MmtpRouter = class {
11777
12269
  droppedIncomingFrames: 0
11778
12270
  };
11779
12271
  this.#staged = state;
12272
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
12273
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
12274
+ }
11780
12275
  return {
11781
12276
  cancel: () => {
11782
12277
  if (this.#staged !== state) return false;
@@ -11859,7 +12354,17 @@ var MmtpRouter = class {
11859
12354
  */
11860
12355
  #routeParsedFrame(data, meta) {
11861
12356
  if (this.#classifyPacketId(meta.packetId) === null) return;
11862
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
12357
+ if (this.#staged !== null) {
12358
+ let consumed = false;
12359
+ this.#fecPokeDepth++;
12360
+ try {
12361
+ consumed = this.#interceptSwitchFrame(data, meta);
12362
+ } finally {
12363
+ this.#fecPokeDepth--;
12364
+ this.#flushPendingFecPokes();
12365
+ }
12366
+ if (consumed) return;
12367
+ }
11863
12368
  this.#deliverParsedFrame(data, meta);
11864
12369
  }
11865
12370
  #commitStreamSwitch(state, rap, reason) {
@@ -12011,12 +12516,16 @@ var MmtpRouter = class {
12011
12516
  this.#parser.deferFecRelease(work);
12012
12517
  } finally {
12013
12518
  this.#fecPokeDepth--;
12014
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
12015
- const pokes = [...this.#pendingFecPokes.values()];
12016
- this.#pendingFecPokes.clear();
12017
- for (const poke of pokes) {
12018
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
12019
- }
12519
+ this.#flushPendingFecPokes();
12520
+ }
12521
+ }
12522
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
12523
+ #flushPendingFecPokes() {
12524
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
12525
+ const pokes = [...this.#pendingFecPokes.values()];
12526
+ this.#pendingFecPokes.clear();
12527
+ for (const poke of pokes) {
12528
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
12020
12529
  }
12021
12530
  }
12022
12531
  }
@@ -12094,6 +12603,14 @@ var MmtpRouter = class {
12094
12603
  onRap: (packetId, catalogTrackName, ssId) => {
12095
12604
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
12096
12605
  },
12606
+ // A staged switch commits on when each side's frames reach it
12607
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
12608
+ // they did unanchored.
12609
+ releaseUnanchored: (packetId, catalogTrackName) => {
12610
+ const staged = this.#staged;
12611
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
12612
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
12613
+ },
12097
12614
  onReleased: (data, meta) => {
12098
12615
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
12099
12616
  const timing = meta.authoredTiming;
@@ -12235,6 +12752,7 @@ var MmtpRouter = class {
12235
12752
  const parsed = this.#parser.parsePacket(packet);
12236
12753
  if (!parsed) return;
12237
12754
  const info = parsed.info;
12755
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
12238
12756
  if (source === "multicast" && !manifestAdmitted) {
12239
12757
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
12240
12758
  }
@@ -12516,7 +13034,8 @@ var MmtpRouter = class {
12516
13034
  parsed.header,
12517
13035
  info.sequenceNumber,
12518
13036
  info.rapFlag,
12519
- source
13037
+ source,
13038
+ fecPayloadId?.ssId
12520
13039
  );
12521
13040
  }
12522
13041
  }
@@ -12542,7 +13061,8 @@ var MmtpRouter = class {
12542
13061
  source: parserOptions?.source,
12543
13062
  deliveryProvenance: parserOptions?.deliveryProvenance,
12544
13063
  catalogTrackName: parserOptions?.catalogTrackName,
12545
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
13064
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
13065
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
12546
13066
  };
12547
13067
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
12548
13068
  else this.#parser.feed(packet, feedOptions);
@@ -12666,7 +13186,8 @@ var MmtpRouter = class {
12666
13186
  if (stream === void 0) {
12667
13187
  stream = {
12668
13188
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
12669
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
13189
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
13190
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
12670
13191
  };
12671
13192
  byName.set(catalogTrackName, stream);
12672
13193
  }
@@ -12781,8 +13302,16 @@ var MmtpRouter = class {
12781
13302
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
12782
13303
  this.#emitDirectVideo(packetId, data, meta, cb);
12783
13304
  }
12784
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
13305
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
12785
13306
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
13307
+ if (this.#isFecTrack(packetId)) {
13308
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
13309
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
13310
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
13311
+ this.#emitDirectVideo(packetId, data, meta, cb);
13312
+ return;
13313
+ }
13314
+ }
12786
13315
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
12787
13316
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
12788
13317
  this.#drainDirectRecoveredVideo(
@@ -12936,6 +13465,13 @@ var MmtpRouter = class {
12936
13465
  * frames by epoch only if pre-protection input ever matters.
12937
13466
  */
12938
13467
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
13468
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
13469
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
13470
+ result = {
13471
+ ...result,
13472
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
13473
+ };
13474
+ }
12939
13475
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
12940
13476
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
12941
13477
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -12992,7 +13528,12 @@ var MmtpRouter = class {
12992
13528
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
12993
13529
  if (ownerPacketId == null) return;
12994
13530
  if (this.#classifyPacketId(ownerPacketId) === null) return;
12995
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
13531
+ const fecSbnOf = (index) => {
13532
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
13533
+ const fecSbn = overlay.baseSsIds.get(index);
13534
+ const fecSbnFirst = overlay.firstSsIds.get(index);
13535
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
13536
+ };
12996
13537
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
12997
13538
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
12998
13539
  if (ssIdSeqOffset !== void 0) {
@@ -13000,7 +13541,10 @@ var MmtpRouter = class {
13000
13541
  ...result,
13001
13542
  symbols: result.symbols.map((sym) => {
13002
13543
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
13003
- if (wire === sym.packetSequenceNumber) return sym;
13544
+ if (wire === sym.packetSequenceNumber) {
13545
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
13546
+ return sym;
13547
+ }
13004
13548
  this.#restampedRecoveredSeqs++;
13005
13549
  this.#restampedStreams.add(streamKey);
13006
13550
  return { ...sym, packetSequenceNumber: wire };
@@ -13036,6 +13580,29 @@ var MmtpRouter = class {
13036
13580
  }
13037
13581
  );
13038
13582
  }
13583
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
13584
+ ownerPacketId,
13585
+ sym.fragment.mpuSequenceNumber,
13586
+ sym.fragment.movieFragmentSequenceNumber,
13587
+ sym.fragment.sampleNumber,
13588
+ catalogTrackName
13589
+ );
13590
+ for (const sym of result.symbols) {
13591
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
13592
+ this.#feedViaParser(
13593
+ sym.rawSymbol,
13594
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
13595
+ void 0,
13596
+ {
13597
+ skipFecPayloadId: true,
13598
+ recovered: true,
13599
+ deliveryProvenance,
13600
+ ...fecSbnOf(sym.index),
13601
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
13602
+ }
13603
+ );
13604
+ }
13605
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
13039
13606
  const gated = this.#isFecTrack(ownerPacketId);
13040
13607
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
13041
13608
  if (assembler) {