@blockcast/mmt-container 2.2.0-main.fb5c7dfbe2de → 2.2.0-main.fde7aee36726

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 (132) hide show
  1. package/README.md +5 -2
  2. package/dist/block-policy.d.ts +88 -16
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +164 -56
  5. package/dist/block-policy.js.map +3 -3
  6. package/dist/browser-runtime.js +1284 -174
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +40 -1
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +163 -10
  11. package/dist/carp-catalog.js.map +4 -4
  12. package/dist/catalog-fec-params.d.ts +1 -1
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +48 -1
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.js +34 -0
  17. package/dist/catalog-network-source.js.map +3 -3
  18. package/dist/cmaf-block-assembler.js +92 -1
  19. package/dist/cmaf-block-assembler.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 +68 -0
  24. package/dist/delivery-catalog.js.map +4 -4
  25. package/dist/delta-fallback-config.js +39 -1
  26. package/dist/delta-fallback-config.js.map +4 -4
  27. package/dist/fec-manager.d.ts +155 -10
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +596 -81
  30. package/dist/fec-manager.js.map +4 -4
  31. package/dist/fec-state.d.ts +17 -5
  32. package/dist/fec-state.d.ts.map +1 -1
  33. package/dist/fec-state.js +41 -1
  34. package/dist/fec-state.js.map +3 -3
  35. package/dist/fec-worker-setup.js +34 -0
  36. package/dist/fec-worker-setup.js.map +3 -3
  37. package/dist/held-layer-admission.js +34 -0
  38. package/dist/held-layer-admission.js.map +3 -3
  39. package/dist/index.d.ts +6 -5
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +9 -1
  42. package/dist/index.js.map +2 -2
  43. package/dist/iso-block-locator.d.ts +16 -0
  44. package/dist/iso-block-locator.d.ts.map +1 -1
  45. package/dist/iso-block-locator.js +62 -0
  46. package/dist/iso-block-locator.js.map +3 -3
  47. package/dist/mfu-reassembler.js +34 -0
  48. package/dist/mfu-reassembler.js.map +3 -3
  49. package/dist/mmtp-container-parser.d.ts +30 -2
  50. package/dist/mmtp-container-parser.d.ts.map +1 -1
  51. package/dist/mmtp-container-parser.js +140 -2
  52. package/dist/mmtp-container-parser.js.map +3 -3
  53. package/dist/mmtp-container-parser.no-modules.js +293 -18
  54. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  55. package/dist/mmtp-decode-pipeline.js +140 -2
  56. package/dist/mmtp-decode-pipeline.js.map +3 -3
  57. package/dist/mmtp-fec-session.js +34 -0
  58. package/dist/mmtp-fec-session.js.map +3 -3
  59. package/dist/mmtp-mode-selection.d.ts +48 -0
  60. package/dist/mmtp-mode-selection.d.ts.map +1 -0
  61. package/dist/mmtp-mode-selection.js +79 -0
  62. package/dist/mmtp-mode-selection.js.map +7 -0
  63. package/dist/mmtp-router.d.ts +66 -8
  64. package/dist/mmtp-router.d.ts.map +1 -1
  65. package/dist/mmtp-router.js +348 -27
  66. package/dist/mmtp-router.js.map +4 -4
  67. package/dist/multicast-auth-catalog.js +42 -2
  68. package/dist/multicast-auth-catalog.js.map +3 -3
  69. package/dist/multicast-input.js +42 -2
  70. package/dist/multicast-input.js.map +3 -3
  71. package/dist/multicast-manager.d.ts +108 -1
  72. package/dist/multicast-manager.d.ts.map +1 -1
  73. package/dist/multicast-manager.js +1067 -138
  74. package/dist/multicast-manager.js.map +4 -4
  75. package/dist/multicast-transport.js +68 -0
  76. package/dist/multicast-transport.js.map +4 -4
  77. package/dist/multicast-unwrap.js +34 -0
  78. package/dist/multicast-unwrap.js.map +3 -3
  79. package/dist/no-modules.d.ts +1 -0
  80. package/dist/no-modules.d.ts.map +1 -1
  81. package/dist/no-modules.js +295 -19
  82. package/dist/no-modules.js.map +4 -4
  83. package/dist/phase14-catalog-override.d.ts +2 -1
  84. package/dist/phase14-catalog-override.d.ts.map +1 -1
  85. package/dist/phase14-catalog-override.js +69 -2
  86. package/dist/phase14-catalog-override.js.map +3 -3
  87. package/dist/repair-fetch.d.ts +2 -0
  88. package/dist/repair-fetch.d.ts.map +1 -1
  89. package/dist/repair-fetch.js +52 -2
  90. package/dist/repair-fetch.js.map +3 -3
  91. package/dist/repair-layer-subscriptions.js +34 -0
  92. package/dist/repair-layer-subscriptions.js.map +3 -3
  93. package/dist/signaling.js +34 -0
  94. package/dist/signaling.js.map +3 -3
  95. package/dist/timestamp-codec.js +34 -0
  96. package/dist/timestamp-codec.js.map +3 -3
  97. package/dist/wasm-mfu-reassembler.js +34 -0
  98. package/dist/wasm-mfu-reassembler.js.map +3 -3
  99. package/dist/wasm-mmtp-container-parser.js +140 -2
  100. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  101. package/package.json +5 -5
  102. package/schemas/catalog.schema.json +2 -2
  103. package/src/block-policy.ts +324 -83
  104. package/src/carp-catalog.ts +165 -5
  105. package/src/catalog-fec-params.ts +1 -0
  106. package/src/codec-utils.ts +121 -1
  107. package/src/fec-manager.ts +534 -41
  108. package/src/fec-state.ts +21 -5
  109. package/src/index.ts +23 -0
  110. package/src/iso-block-locator.ts +34 -0
  111. package/src/mmtp-container-parser.ts +57 -11
  112. package/src/mmtp-mode-selection.ts +80 -0
  113. package/src/mmtp-router.ts +287 -42
  114. package/src/multicast-manager.ts +218 -10
  115. package/src/no-modules.ts +3 -0
  116. package/src/phase14-catalog-override.ts +14 -3
  117. package/src/repair-fetch.ts +27 -2
  118. package/test-vectors/catalog/README.md +36 -2
  119. package/test-vectors/catalog/mmtp-siblings/ambiguous-sibling.json +158 -0
  120. package/test-vectors/catalog/mmtp-siblings/ladder-bitrate-only.json +231 -0
  121. package/test-vectors/catalog/mmtp-siblings/ladder-four-rungs.json +405 -0
  122. package/test-vectors/catalog/mmtp-siblings/ladder-other-names.json +231 -0
  123. package/test-vectors/catalog/mmtp-siblings/mmtp-mode-unknown.json +143 -0
  124. package/test-vectors/catalog/mmtp-siblings/multicast-endpoint-lists-datagram-track.json +143 -0
  125. package/test-vectors/catalog/mmtp-siblings/no-sibling.json +79 -0
  126. package/test-vectors/catalog/mmtp-siblings/rendition-mismatch.json +143 -0
  127. package/test-vectors/catalog/mmtp-siblings/stream-delivery-mode.json +143 -0
  128. package/test-vectors/catalog/mmtp-siblings/timescale-mismatch.json +143 -0
  129. package/test-vectors/catalog/mmtp-siblings/valid-pair.json +142 -0
  130. package/test-vectors/catalog/section-codes.json +3 -3
  131. package/test-vectors/catalog-validation.json +266 -7
  132. package/test-vectors/moq/mmtp-mode-selection.json +259 -0
@@ -954,13 +954,17 @@ function fecCatalogTracks(catalog) {
954
954
  });
955
955
  return { tracks, pointers };
956
956
  }
957
- function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
957
+ function runtimeView(catalog, receiver) {
958
958
  const { tracks, pointers } = fecCatalogTracks(catalog);
959
959
  const report = validateFecCatalog({ tracks }, receiver);
960
960
  const at = (path) => {
961
961
  const m = /^\/tracks\/(\d+)(.*)$/.exec(path);
962
962
  return m ? pointers[Number(m[1])] + m[2] : path;
963
963
  };
964
+ return { tracks, pointers, report, at };
965
+ }
966
+ function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
967
+ const { tracks, pointers, report, at } = runtimeView(catalog, receiver);
964
968
  const trackAt = (i) => recordOf(tracks[i]) ?? {};
965
969
  const nameAt = (i) => i === null ? void 0 : trackAt(i)["name"];
966
970
  const why = (i) => Object.freeze({
@@ -1058,6 +1062,40 @@ function geometry(o, instanceId, symbolTrack) {
1058
1062
  });
1059
1063
  }
1060
1064
 
1065
+ // ../mmt-base/dist/mmtp-siblings.js
1066
+ var MMTP_MODES = Object.freeze(["mfu", "mfu-datagram"]);
1067
+ var MMTP_SIBLING_HARD_FIELDS = Object.freeze([
1068
+ "namespace",
1069
+ "timescale",
1070
+ "presentationAnchorTicks",
1071
+ "groupDuration"
1072
+ ]);
1073
+ var MMTP_SIBLING_RENDITION_FIELDS = Object.freeze([
1074
+ "codec",
1075
+ "width",
1076
+ "height",
1077
+ "framerate",
1078
+ "bitrate",
1079
+ "samplerate",
1080
+ "channelConfig",
1081
+ "lang"
1082
+ ]);
1083
+ var MMTP_SIBLING_SOFT_FIELDS = Object.freeze([
1084
+ "initRef",
1085
+ "keyframeIntervalMs",
1086
+ "keyframeIntervalTicks",
1087
+ "isLive",
1088
+ "altGroup"
1089
+ ]);
1090
+
1091
+ // ../mmt-base/dist/datagram-leg-size.js
1092
+ var DATAGRAM_LEG_UDP_FLOOR = 1200;
1093
+ var DATAGRAM_LEG_QUIC_WT_FRAMING = 48;
1094
+ var DATAGRAM_LEG_OBJECT_HEADER = 13;
1095
+ var DATAGRAM_LEG_RELAY_ROOM = 16;
1096
+ var DATAGRAM_LEG_DATAGRAM_MAX = DATAGRAM_LEG_UDP_FLOOR - DATAGRAM_LEG_QUIC_WT_FRAMING;
1097
+ var DATAGRAM_LEG_BODY_MAX = DATAGRAM_LEG_DATAGRAM_MAX - DATAGRAM_LEG_OBJECT_HEADER - DATAGRAM_LEG_RELAY_ROOM;
1098
+
1061
1099
  // src/track-session.ts
1062
1100
  import { fecBlockBudgetMs } from "@blockcast/mmt-fec";
1063
1101
  function computeFecDeliveryWindowMs(config) {
@@ -1368,6 +1406,34 @@ var IsoBlockLocator = class _IsoBlockLocator {
1368
1406
  isHeld(ssId) {
1369
1407
  return this.#held.has(ssId);
1370
1408
  }
1409
+ /** The payload held unplaced for `ssId`, if any. */
1410
+ heldSource(ssId) {
1411
+ return this.#held.get(ssId);
1412
+ }
1413
+ /**
1414
+ * The SS_IDs strictly between `a` and `b` that no repair has delimited a
1415
+ * block of yet: those from the coverage end on, or all of them before the
1416
+ * first repair. `missing` is the highest of them no source is held for;
1417
+ * absent, every one of them arrived (C.5.2: SS_IDs are consecutive). Null
1418
+ * when none lies past coverage. `flagged` is whether a source held among
1419
+ * them satisfies `flag` (a RAP fragment, say): the held packets read as
1420
+ * fec-multicast-00 Block Classification item 1 reads bounding packets.
1421
+ */
1422
+ undelimitedBetween(a, b, flag) {
1423
+ if (!serial32Precedes(a, b) || serial32Distance(a, b) <= 1) return null;
1424
+ const first = a + 1 >>> 0;
1425
+ const end = this.#coverageEnd;
1426
+ const start = end !== void 0 && serial32Precedes(first, end) ? end : first;
1427
+ if (!serial32Precedes(start, b)) return null;
1428
+ const length = serial32Distance(start, b);
1429
+ const missing = this.#highestMissing(start, length);
1430
+ let flagged = false;
1431
+ for (let i = 0; flag !== void 0 && !flagged && i < length; i++) {
1432
+ const payload = this.#held.get(serial32Add(start, i));
1433
+ flagged = payload !== void 0 && flag(payload);
1434
+ }
1435
+ return missing === void 0 ? { start, flagged } : { start, missing, flagged };
1436
+ }
1371
1437
  /**
1372
1438
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
1373
1439
  * block states its range and places every held source in it; later repair
@@ -1613,31 +1679,26 @@ function deriveBlockClassifierGeometry(input) {
1613
1679
  );
1614
1680
  }
1615
1681
  if (input.trackKind === "audio") return { trackKind: "audio" };
1616
- if (!isPositiveFinite(input.framerate)) {
1617
- return { trackKind: "video", mode: "all-protected", reason: "framerate-absent" };
1618
- }
1619
- const framerate = input.framerate;
1620
1682
  let keyframeInterval;
1621
1683
  if (isPositiveFinite(input.keyframeIntervalTicks) && isPositiveFinite(input.timescale)) {
1622
1684
  keyframeInterval = { ticks: input.keyframeIntervalTicks, timescale: input.timescale };
1623
1685
  } else if (isPositiveFinite(input.keyframeIntervalMs)) {
1624
1686
  keyframeInterval = { ticks: input.keyframeIntervalMs, timescale: 1e3 };
1625
- } else {
1626
- return { trackKind: "video", mode: "all-protected", reason: "keyframe-cadence-absent" };
1627
1687
  }
1688
+ const protect = (reason) => ({
1689
+ trackKind: "video",
1690
+ mode: "all-protected",
1691
+ reason,
1692
+ ...keyframeInterval === void 0 ? {} : { keyframeInterval }
1693
+ });
1694
+ if (!isPositiveFinite(input.framerate)) return protect("framerate-absent");
1695
+ const framerate = input.framerate;
1696
+ if (keyframeInterval === void 0) return protect("keyframe-cadence-absent");
1628
1697
  const gopFrames = exactInteger(keyframeInterval.ticks * framerate, keyframeInterval.timescale);
1629
- if (gopFrames === null) {
1630
- return {
1631
- trackKind: "video",
1632
- mode: "all-protected",
1633
- reason: "keyframe-interval-not-integral"
1634
- };
1635
- }
1698
+ if (gopFrames === null) return protect("keyframe-interval-not-integral");
1636
1699
  const frameDurationMs = 1e3 / framerate;
1637
1700
  const interleaveUnits = deriveFecInterleaveDepth(input.interleaveDepthMs, frameDurationMs);
1638
- if (interleaveUnits >= gopFrames) {
1639
- return { trackKind: "video", mode: "all-protected", reason: "block-spans-gop" };
1640
- }
1701
+ if (interleaveUnits >= gopFrames) return protect("block-spans-gop");
1641
1702
  return {
1642
1703
  trackKind: "video",
1643
1704
  mode: "classifying",
@@ -1648,7 +1709,7 @@ function deriveBlockClassifierGeometry(input) {
1648
1709
  };
1649
1710
  }
1650
1711
  function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
1651
- if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return null;
1712
+ if (geometry2.trackKind !== "video" || geometry2.keyframeInterval === void 0) return null;
1652
1713
  if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0) return null;
1653
1714
  const { ticks, timescale } = geometry2.keyframeInterval;
1654
1715
  if (!Number.isSafeInteger(ticks) || !Number.isSafeInteger(timescale)) return null;
@@ -1657,9 +1718,15 @@ function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
1657
1718
  if (scaled % divisor !== 0n) return null;
1658
1719
  return scaled / divisor;
1659
1720
  }
1721
+ function keyframeInstantBetween(start, interval, from, to) {
1722
+ const k = from >= start ? (from - start) / interval + 1n : 1n;
1723
+ return start + k * interval <= to;
1724
+ }
1660
1725
  function compareDataUnitStarts(a, b) {
1661
- return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset;
1726
+ return a.movieFragment - b.movieFragment | 0 || a.idx - b.idx || a.offset - b.offset;
1662
1727
  }
1728
+ var LATE_RAP_MAX_MPUS_BACK = 64;
1729
+ var UNPLACED = { rapNotMpuStart: false };
1663
1730
  var BlockClassifier = class {
1664
1731
  #geometry;
1665
1732
  #mode;
@@ -1682,8 +1749,24 @@ var BlockClassifier = class {
1682
1749
  #mpuSbnSpans = /* @__PURE__ */ new Map();
1683
1750
  #dataUnitStarts = /* @__PURE__ */ new Map();
1684
1751
  #highestMpu = null;
1685
- /** MPU → movie_fragment_sequence_number observed in it. */
1686
- #mpuFragments = /* @__PURE__ */ new Map();
1752
+ /**
1753
+ * P3 layout, kept for the MPUs within the classification horizon and valid
1754
+ * within one continuous SBN sequence (`noteSourceDiscontinuity`).
1755
+ */
1756
+ #mpus = /* @__PURE__ */ new Map();
1757
+ /** An MPU of this sequence showed two movie fragments: each frame is one. */
1758
+ #fragmentPerFrame = false;
1759
+ /** A DU header of this sequence stated sample_number above 1. */
1760
+ #multiSampleFragment = false;
1761
+ /**
1762
+ * The anchor received last, whether or not its MPU is still in the
1763
+ * horizon. Each new anchor, and the anchor of every DU header's MPU, is
1764
+ * checked against it.
1765
+ */
1766
+ #lastAnchor = null;
1767
+ /** Two anchors were exactly G fragments per MPU apart. */
1768
+ #fragmentsProven = false;
1769
+ /** The first RAP released of the latest MPU a RAP was released in, recorded in every mode. */
1687
1770
  #lastRap = null;
1688
1771
  constructor(geometry2) {
1689
1772
  this.#geometry = geometry2;
@@ -1713,7 +1796,7 @@ var BlockClassifier = class {
1713
1796
  this.#geometry = geometry2;
1714
1797
  this.#blocks.clear();
1715
1798
  this.#clearContiguityLedger();
1716
- this.#mpuFragments.clear();
1799
+ this.#clearMpuLayout();
1717
1800
  this.#lastRap = null;
1718
1801
  this.#mpuBoundsRaps = true;
1719
1802
  if (geometry2.trackKind === "video" && geometry2.mode === "all-protected") {
@@ -1747,11 +1830,14 @@ var BlockClassifier = class {
1747
1830
  /**
1748
1831
  * The stream's SBN sequence restarted (FECManager source discontinuity:
1749
1832
  * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
1750
- * order are comparable only within one continuous sequence, so the P1
1751
- * ledger starts again.
1833
+ * order are comparable only within one continuous sequence, and a
1834
+ * restarted publisher numbers MPUs and movie fragments again, so the P1
1835
+ * ledger and the P3 layout start again.
1752
1836
  */
1753
1837
  noteSourceDiscontinuity() {
1754
1838
  this.#clearContiguityLedger();
1839
+ this.#clearMpuLayout();
1840
+ this.#lastRap = null;
1755
1841
  }
1756
1842
  /** Register a block that exists without evidence (a vanished block). */
1757
1843
  touch(sbn) {
@@ -1770,16 +1856,16 @@ var BlockClassifier = class {
1770
1856
  if (this.#geometry.trackKind === "audio") return [];
1771
1857
  const changes = [];
1772
1858
  const block = this.#blockFor(sbn);
1859
+ const placement = this.#place(evidence);
1773
1860
  if (evidence.rap) block.rapSeen = true;
1774
1861
  if (evidence.mpu !== void 0) block.mpus.add(evidence.mpu);
1775
- if (evidence.idx !== void 0) {
1776
- block.idxMin = block.idxMin === void 0 ? evidence.idx : Math.min(block.idxMin, evidence.idx);
1777
- block.idxMax = block.idxMax === void 0 ? evidence.idx : Math.max(block.idxMax, evidence.idx);
1862
+ const { position } = placement;
1863
+ if (position !== void 0) {
1864
+ block.positionMin = block.positionMin === void 0 ? position : Math.min(block.positionMin, position);
1865
+ block.positionMax = block.positionMax === void 0 ? position : Math.max(block.positionMax, position);
1778
1866
  }
1779
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
1780
- this.#mpuBoundsRaps = false;
1781
- }
1782
- const violation = this.#checkInvariants(sbn, block, evidence);
1867
+ if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false;
1868
+ const violation = this.#checkInvariants(sbn, block, evidence, placement);
1783
1869
  if (violation !== null) changes.push(...this.#disable(violation));
1784
1870
  const next = this.#classify(block);
1785
1871
  if (next !== block.cls && this.#allowed(block.cls, next)) {
@@ -1804,18 +1890,35 @@ var BlockClassifier = class {
1804
1890
  * RAP-bearing block is the one a wrong G calls delta), because the next
1805
1891
  * released RAP then belongs to m+2. Every MPU is one interval long, so the
1806
1892
  * span to any later released RAP proves or refutes all MPUs in between.
1807
- */
1808
- noteReleasedRap(mpu, presentationTime, mediaTimescale) {
1809
- if (this.#geometry.trackKind === "audio" || this.#mode === "all-protected") {
1810
- return [];
1811
- }
1812
- const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
1813
- if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
1893
+ *
1894
+ * In every mode it keeps each MPU's first released RAP, with its decode
1895
+ * time, as the start keyframeFreeBetween measures the catalog interval
1896
+ * from, and a second RAP released inside one MPU refutes `mpuBoundsRaps`
1897
+ * when it lies off the catalog lattice (not a whole number of intervals
1898
+ * after the first; draft-ramadan-moq-mmt-02 4.4.3 binds every keyframe to
1899
+ * it): with no repair, released RAPs are the only evidence of where they
1900
+ * lie. Without a usable interval, or a decode time on either, any second
1901
+ * RAP with another presentation time refutes.
1902
+ */
1903
+ noteReleasedRap(mpu, presentationTime, mediaTimescale, decodeTime) {
1904
+ if (this.#geometry.trackKind === "audio") return [];
1814
1905
  const previous = this.#lastRap;
1815
1906
  if (previous !== null && previous.mpu === mpu && previous.mediaTimescale === mediaTimescale) {
1907
+ if (presentationTime === previous.presentationTime) return [];
1908
+ const interval2 = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
1909
+ if (interval2 === null || decodeTime === void 0 || previous.decodeTime === void 0 || (decodeTime - previous.decodeTime) % interval2 !== 0n) {
1910
+ this.#mpuBoundsRaps = false;
1911
+ }
1816
1912
  return [];
1817
1913
  }
1818
- this.#lastRap = { mpu, presentationTime, mediaTimescale };
1914
+ if (previous !== null && previous.mediaTimescale === mediaTimescale) {
1915
+ const back = previous.mpu - mpu >>> 0;
1916
+ if (back !== 0 && back <= LATE_RAP_MAX_MPUS_BACK && presentationTime < previous.presentationTime) return [];
1917
+ }
1918
+ this.#lastRap = { mpu, presentationTime, mediaTimescale, ...decodeTime === void 0 ? {} : { decodeTime } };
1919
+ if (this.#mode === "all-protected") return [];
1920
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
1921
+ if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
1819
1922
  if (previous === null || mpu < previous.mpu || previous.mediaTimescale !== mediaTimescale) {
1820
1923
  return [];
1821
1924
  }
@@ -1824,6 +1927,22 @@ var BlockClassifier = class {
1824
1927
  }
1825
1928
  return this.#disable("rap-spacing-mismatch");
1826
1929
  }
1930
+ /**
1931
+ * Whether a gap inside MPU `mpu`, between the decode times `from` and `to`
1932
+ * of the frames on either side, holds no keyframe: MPU boundaries still
1933
+ * bound RAPs, the catalog states an interval exact in this timescale, and
1934
+ * none of its instants after the MPU's first released RAP lies in
1935
+ * `(from, to]` (fec-multicast-00 Block Classification item 3). Anything
1936
+ * unknown counts as a keyframe.
1937
+ */
1938
+ keyframeFreeBetween(mpu, from, to, mediaTimescale) {
1939
+ const rap = this.#lastRap;
1940
+ if (!this.#mpuBoundsRaps || rap?.mpu !== mpu || rap.mediaTimescale !== mediaTimescale || rap.decodeTime === void 0) {
1941
+ return false;
1942
+ }
1943
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
1944
+ return interval !== null && !keyframeInstantBetween(rap.decodeTime, interval, from, to);
1945
+ }
1827
1946
  #blockFor(sbn) {
1828
1947
  let block = this.#blocks.get(sbn);
1829
1948
  if (!block) {
@@ -1832,35 +1951,89 @@ var BlockClassifier = class {
1832
1951
  }
1833
1952
  return block;
1834
1953
  }
1835
- #checkInvariants(sbn, block, evidence) {
1954
+ #checkInvariants(sbn, block, evidence, placement) {
1836
1955
  if (this.#mode === "all-protected" || this.#geometry.trackKind !== "video") return null;
1837
1956
  const geometry2 = this.#geometry;
1838
1957
  if (geometry2.mode !== "classifying") return null;
1839
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
1840
- return "rap-not-mpu-start";
1841
- }
1842
- if (evidence.idx !== void 0 && evidence.idx >= geometry2.gopFrames) {
1958
+ if (placement.rapNotMpuStart) return "rap-not-mpu-start";
1959
+ if (placement.position !== void 0 && placement.position >= geometry2.gopFrames) {
1843
1960
  return "mpu-longer-than-gop";
1844
1961
  }
1845
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0 && block.idxMax - block.idxMin >= geometry2.interleaveUnits) {
1962
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0 && block.positionMax - block.positionMin >= geometry2.interleaveUnits) {
1846
1963
  return "block-wider-than-interleave";
1847
1964
  }
1848
- if (evidence.mpu !== void 0 && evidence.movieFragment !== void 0) {
1849
- const fragment = this.#mpuFragments.get(evidence.mpu);
1850
- if (fragment === void 0) {
1851
- this.#mpuFragments.set(evidence.mpu, evidence.movieFragment);
1852
- for (const mpu of this.#mpuFragments.keys()) {
1853
- if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu);
1854
- }
1855
- } else if (fragment !== evidence.movieFragment) {
1856
- return "mpu-multiple-fragments";
1857
- }
1858
- }
1965
+ if (placement.violation !== void 0) return placement.violation;
1859
1966
  if (evidence.mpu !== void 0 && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
1860
1967
  return "block-not-contiguous";
1861
1968
  }
1862
1969
  return null;
1863
1970
  }
1971
+ /**
1972
+ * The MPU position a source symbol's DU header proves (P3), and what it
1973
+ * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.
1974
+ */
1975
+ #place(evidence) {
1976
+ const { mpu, idx, movieFragment: fragment } = evidence;
1977
+ if (idx === void 0) return UNPLACED;
1978
+ const bySample = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 };
1979
+ if (mpu === void 0 || fragment === void 0) {
1980
+ return this.#fragmentPerFrame && !this.#multiSampleFragment ? { rapNotMpuStart: bySample.rapNotMpuStart } : bySample;
1981
+ }
1982
+ let layout = this.#mpus.get(mpu);
1983
+ if (layout === void 0) {
1984
+ layout = { low: fragment };
1985
+ this.#mpus.set(mpu, layout);
1986
+ for (const other of this.#mpus.keys()) {
1987
+ if (other + 1 < mpu) this.#mpus.delete(other);
1988
+ }
1989
+ } else if (fragment !== layout.low) {
1990
+ this.#fragmentPerFrame = true;
1991
+ if ((fragment - layout.low | 0) < 0) layout.low = fragment;
1992
+ }
1993
+ if (idx !== 0) this.#multiSampleFragment = true;
1994
+ let arrival;
1995
+ if (evidence.rap && layout.anchor === void 0) {
1996
+ layout.anchor = fragment;
1997
+ arrival = this.#anchorDrift(mpu, fragment);
1998
+ if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true;
1999
+ this.#lastAnchor = { mpu, fragment };
2000
+ }
2001
+ if (!this.#fragmentPerFrame) return bySample;
2002
+ if (this.#multiSampleFragment) return { ...bySample, violation: "mpu-multiple-fragments" };
2003
+ const { anchor } = layout;
2004
+ if (anchor === void 0) return UNPLACED;
2005
+ const drift = arrival ?? this.#anchorDrift(mpu, anchor);
2006
+ const offset = fragment - anchor | 0;
2007
+ return {
2008
+ ...offset === 0 || offset > 0 && this.#fragmentsProven ? { position: offset } : {},
2009
+ rapNotMpuStart: evidence.rap && offset !== 0 || (layout.low - anchor | 0) < 0 || // Fragments count frames: an anchor arriving past the spacing is a
2010
+ // RAP inside its MPU, or an earlier MPU outran G.
2011
+ arrival !== void 0 && arrival > 0 && this.#fragmentsProven,
2012
+ ...drift === void 0 || drift === 0 ? {} : { violation: "rap-spacing-mismatch" }
2013
+ };
2014
+ }
2015
+ /**
2016
+ * How many fragments MPU m's anchor `fragment` lies past the start that
2017
+ * the anchor received last predicts for MPU m: one frame per fragment and
2018
+ * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')
2019
+ * fragments apart, modulo 2^32. Undefined without a last anchor, a
2020
+ * cadence, or this layout.
2021
+ */
2022
+ #anchorDrift(mpu, fragment) {
2023
+ const geometry2 = this.#geometry;
2024
+ const last = this.#lastAnchor;
2025
+ if (last === null || !this.#fragmentPerFrame || this.#multiSampleFragment || geometry2.trackKind !== "video" || geometry2.mode !== "classifying") {
2026
+ return void 0;
2027
+ }
2028
+ return fragment - last.fragment - geometry2.gopFrames * (mpu - last.mpu) | 0;
2029
+ }
2030
+ #clearMpuLayout() {
2031
+ this.#mpus.clear();
2032
+ this.#fragmentPerFrame = false;
2033
+ this.#multiSampleFragment = false;
2034
+ this.#lastAnchor = null;
2035
+ this.#fragmentsProven = false;
2036
+ }
1864
2037
  #clearContiguityLedger() {
1865
2038
  this.#mpuSbnSpans.clear();
1866
2039
  this.#dataUnitStarts.clear();
@@ -1960,9 +2133,9 @@ var BlockClassifier = class {
1960
2133
  if (this.#mode === "all-protected") return "unknown";
1961
2134
  const geometry2 = this.#geometry;
1962
2135
  if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return "unknown";
1963
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0) {
2136
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0) {
1964
2137
  const span = geometry2.interleaveUnits - 1;
1965
- if (block.idxMax - span >= 1 && block.idxMin + span <= geometry2.gopFrames - 1) {
2138
+ if (block.positionMax - span >= 1 && block.positionMin + span <= geometry2.gopFrames - 1) {
1966
2139
  return "delta";
1967
2140
  }
1968
2141
  }
@@ -2221,7 +2394,12 @@ var FECManager = class _FECManager {
2221
2394
  this.#repairHoldUntilMs = /* @__PURE__ */ new Map();
2222
2395
  // Receiver-measured multicast delivery gap: the late-symbol wait's jitter
2223
2396
  // term (see DeliveryGapEstimator for the statistic and why).
2224
- this.#deliveryGaps = new DeliveryGapEstimator();
2397
+ // One estimator per lossy path, so a hybrid session never lets one leg's
2398
+ // stall widen the other's wait; the wait reads the larger peak.
2399
+ this.#deliveryGaps = {
2400
+ multicast: new DeliveryGapEstimator(),
2401
+ "moq-datagram": new DeliveryGapEstimator()
2402
+ };
2225
2403
  this.#lifecycleTrace = [];
2226
2404
  // Worker-backed timeouts enqueue cleanup behind all prior symbol messages.
2227
2405
  // Failure remains pending until cleanupComplete acknowledges that queue drain.
@@ -2259,7 +2437,8 @@ var FECManager = class _FECManager {
2259
2437
  this.#ssbLengthConflictCount = 0;
2260
2438
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
2261
2439
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
2262
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
2440
+ // symbols its repair group carries; 0 for a repair-less span no repair can
2441
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
2263
2442
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
2264
2443
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
2265
2444
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -2412,6 +2591,14 @@ var FECManager = class _FECManager {
2412
2591
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
2413
2592
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
2414
2593
  this.#isoLocators = /* @__PURE__ */ new Map();
2594
+ // The ts of the run behind the gap the release gate last asked about, per
2595
+ // stream (isoRepairlessWaitMs), keyed on the frame before the gap: kept, as
2596
+ // the source it came from may retire before the run's deadline, and the
2597
+ // earliest found wins, so a late frame that becomes the head restarts
2598
+ // nothing. It stays until the next run gap: a source discontinuity drops
2599
+ // it, and one older than twice the hold ceiling is not this gap's.
2600
+ // `counted` once the deadline passed (onUndelimitedRunGap).
2601
+ this.#runAnchors = /* @__PURE__ */ new Map();
2415
2602
  this.#deferIsoGaps = false;
2416
2603
  this.#isoRepairRefusedCount = 0;
2417
2604
  this.#isoSourceOversizeCount = 0;
@@ -2447,6 +2634,8 @@ var FECManager = class _FECManager {
2447
2634
  this.#workerErrorCounts = /* @__PURE__ */ new Map();
2448
2635
  this.#decoderUnavailableEvents = 0;
2449
2636
  this.#repairSymbolSizeMismatchCount = 0;
2637
+ this.#unlistedRepairTrackRefusals = 0;
2638
+ this.#unresolvedRepairOwnerDrops = { unregistered: 0, ownerAbsent: 0, ownerAmbiguous: 0 };
2450
2639
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
2451
2640
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
2452
2641
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
@@ -2506,6 +2695,18 @@ var FECManager = class _FECManager {
2506
2695
  this.onBlockResolved = null;
2507
2696
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
2508
2697
  this.onSourceDiscontinuity = null;
2698
+ /** The FEC deadline of a run no repair delimited passed, releasing the gap behind it (once per gap). */
2699
+ this.onUndelimitedRunGap = null;
2700
+ /**
2701
+ * The span and tolerance the catalog states for a keyframe overlay
2702
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
2703
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
2704
+ * undefined while none is installed. A stated block only a late source
2705
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
2706
+ * late source can fill, also wait for that overlay's repair
2707
+ * (#overlayLateWaitMs).
2708
+ */
2709
+ this.keyframeOverlayTiming = null;
2509
2710
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
2510
2711
  /**
2511
2712
  * A recovered source symbol. Return false when admission refused the
@@ -2596,6 +2797,7 @@ var FECManager = class _FECManager {
2596
2797
  #highestSbn;
2597
2798
  #sourceFrontiers;
2598
2799
  #isoLocators;
2800
+ #runAnchors;
2599
2801
  #deferIsoGaps;
2600
2802
  #isoRepairRefusedCount;
2601
2803
  #isoSourceOversizeCount;
@@ -2610,6 +2812,8 @@ var FECManager = class _FECManager {
2610
2812
  #workerErrorCounts;
2611
2813
  #decoderUnavailableEvents;
2612
2814
  #repairSymbolSizeMismatchCount;
2815
+ #unlistedRepairTrackRefusals;
2816
+ #unresolvedRepairOwnerDrops;
2613
2817
  #onUndelimitedLoss;
2614
2818
  #onIsoHoleExpired;
2615
2819
  #encodeTrackName(catalogTrackName) {
@@ -3259,6 +3463,7 @@ var FECManager = class _FECManager {
3259
3463
  const discontinuity = () => {
3260
3464
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
3261
3465
  this.#noSpanRaps.delete(streamKey);
3466
+ this.#runAnchors.delete(streamKey);
3262
3467
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
3263
3468
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
3264
3469
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -3429,7 +3634,7 @@ var FECManager = class _FECManager {
3429
3634
  consider(geometry2, this.#parseStreamKey(streamKey).packetId);
3430
3635
  }
3431
3636
  for (const [packetId, config] of this.#trackConfigs) consider(config.geometry, packetId);
3432
- this.#deliveryGaps.setWindowMs(windowMs);
3637
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.setWindowMs(windowMs);
3433
3638
  }
3434
3639
  /**
3435
3640
  * The multicast late-symbol wait: the block span plus the larger of the
@@ -3442,14 +3647,14 @@ var FECManager = class _FECManager {
3442
3647
  * stream order and never feeds the estimator.
3443
3648
  */
3444
3649
  #multicastWaitMs(config) {
3445
- return this.#waitForGapMs(config, this.#deliveryGaps.peakGapMs(performance.now()));
3650
+ return this.#waitForGapMs(config, this.#peakDeliveryGapMs());
3446
3651
  }
3447
3652
  /**
3448
3653
  * The widest #multicastWaitMs can become: the estimator reports at most its
3449
3654
  * catalog window, so this is a catalog quantity that no measurement moves.
3450
3655
  */
3451
3656
  #maxMulticastWaitMs(config) {
3452
- return this.#waitForGapMs(config, this.#deliveryGaps.windowMs ?? 0);
3657
+ return this.#waitForGapMs(config, this.#deliveryGaps.multicast.windowMs ?? 0);
3453
3658
  }
3454
3659
  #waitForGapMs(config, gapMs) {
3455
3660
  if (!(gapMs > 0) || !(config.interleaveDepthMs > 0)) return config.timeoutMs;
@@ -3633,6 +3838,7 @@ var FECManager = class _FECManager {
3633
3838
  ...(config.trackKind ?? previous.trackKind) === void 0 ? {} : { trackKind: config.trackKind ?? previous.trackKind },
3634
3839
  ...(config.codec ?? previous.codec) === void 0 ? {} : { codec: config.codec ?? previous.codec },
3635
3840
  ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry },
3841
+ ...(config.groupDurationMs ?? previous.groupDurationMs) === void 0 ? {} : { groupDurationMs: config.groupDurationMs ?? previous.groupDurationMs },
3636
3842
  ...(config.repairLayers ?? previous.repairLayers) === void 0 ? {} : { repairLayers: config.repairLayers ?? previous.repairLayers },
3637
3843
  ...(config.heldLayers ?? previous.heldLayers) === void 0 ? {} : { heldLayers: config.heldLayers ?? previous.heldLayers }
3638
3844
  };
@@ -3739,6 +3945,10 @@ var FECManager = class _FECManager {
3739
3945
  lifecycleTrace: this.#lifecycleTrace.map((entry) => ({ ...entry }))
3740
3946
  };
3741
3947
  }
3948
+ /** Count a repair packet the router dropped for want of an owning track (BLO-55759). */
3949
+ countUnresolvedRepairOwner(reason) {
3950
+ this.#unresolvedRepairOwnerDrops[reason]++;
3951
+ }
3742
3952
  get fecStats() {
3743
3953
  const s = this.#fecStats;
3744
3954
  const affected = s.blocksRecovered + s.blocksFailed;
@@ -3778,6 +3988,8 @@ var FECManager = class _FECManager {
3778
3988
  packetId
3779
3989
  })),
3780
3990
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
3991
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
3992
+ unresolvedRepairOwnerDrops: { ...this.#unresolvedRepairOwnerDrops },
3781
3993
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
3782
3994
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
3783
3995
  };
@@ -3802,6 +4014,16 @@ var FECManager = class _FECManager {
3802
4014
  this.#startupRepairBoundaryCounts.clear();
3803
4015
  this.#startupRepairFailOpenPackets.clear();
3804
4016
  }
4017
+ /**
4018
+ * Start a new "mfu-datagram" leg (mmt-02 4.3.1) without discarding
4019
+ * track/decoder state: the same join-boundary rules as a multicast join,
4020
+ * since the leg starts at an arbitrary datagram too. It resets the whole
4021
+ * join boundary of this manager, a multicast ordered-relay frontier
4022
+ * included, so a host gives the leg a manager of its own.
4023
+ */
4024
+ beginLegJoin() {
4025
+ this.beginMulticastJoin();
4026
+ }
3805
4027
  /** How the multicast leg currently delivers symbols. */
3806
4028
  get multicastSymbolDelivery() {
3807
4029
  return this.#multicastSymbolDelivery;
@@ -3824,7 +4046,8 @@ var FECManager = class _FECManager {
3824
4046
  );
3825
4047
  }
3826
4048
  if (delivery === this.#multicastSymbolDelivery) return;
3827
- this.#deliveryGaps.reset();
4049
+ this.#deliveryGaps.multicast.reset();
4050
+ this.#runAnchors.clear();
3828
4051
  if (delivery === "ordered-relay") {
3829
4052
  for (const [packetId, config] of this.#trackConfigs) {
3830
4053
  this.#orderedHorizonBlocksFor(packetId, config);
@@ -3913,6 +4136,7 @@ var FECManager = class _FECManager {
3913
4136
  resetMap(this.#highestSbn);
3914
4137
  resetMap(this.#sourceFrontiers);
3915
4138
  resetMap(this.#isoLocators);
4139
+ resetMap(this.#runAnchors);
3916
4140
  resetMap(this.#sourceAnchors);
3917
4141
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
3918
4142
  this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
@@ -4022,6 +4246,7 @@ var FECManager = class _FECManager {
4022
4246
  dropMap(this.#highestSbn);
4023
4247
  dropMap(this.#sourceFrontiers);
4024
4248
  dropMap(this.#isoLocators);
4249
+ dropMap(this.#runAnchors);
4025
4250
  dropMap(this.#sourceAnchors);
4026
4251
  dropMap(this.#classifiers);
4027
4252
  dropMap(this.#noSpanRaps);
@@ -4089,8 +4314,8 @@ var FECManager = class _FECManager {
4089
4314
  const sourceSymbols = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? this.#trackConfig(packetId).k;
4090
4315
  const isSourceSymbol = esi >= 0 && esi < sourceSymbols;
4091
4316
  const isStartupPartial = this.#startupPartialBlocks.has(blockKey);
4092
- const isReadyMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
4093
- const awaitingMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !this.#startupRepairReadyPackets.has(streamKey) && !this.#startupRepairFailOpenPackets.has(streamKey);
4317
+ const isReadyMulticastRepair = this.#startupRequireRepairReady && source !== "moq" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
4318
+ const awaitingMulticastRepair = this.#startupRequireRepairReady && source !== "moq" && !this.#startupRepairReadyPackets.has(streamKey) && !this.#startupRepairFailOpenPackets.has(streamKey);
4094
4319
  if (awaitingMulticastRepair) {
4095
4320
  if (!isSourceSymbol) {
4096
4321
  this.#startupRepairReadyPackets.add(streamKey);
@@ -4144,12 +4369,14 @@ var FECManager = class _FECManager {
4144
4369
  ...catalogTrackName === void 0 ? {} : { catalogTrackName },
4145
4370
  multicastSymbols: 0,
4146
4371
  moqSymbols: 0,
4372
+ datagramSymbols: 0,
4147
4373
  complete: false
4148
4374
  };
4149
4375
  const receivedAtMs = this.#receiptNow();
4150
4376
  const anchorMs = this.#blockAnchorsMs.get(blockKey);
4151
4377
  if (anchorMs === void 0 || receivedAtMs < anchorMs) this.#blockAnchorsMs.set(blockKey, receivedAtMs);
4152
4378
  if (source === "multicast") counts.multicastSymbols++;
4379
+ else if (source === "moq-datagram") counts.datagramSymbols++;
4153
4380
  else counts.moqSymbols++;
4154
4381
  this.#blockPathCounts.set(blockKey, counts);
4155
4382
  this.#observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName);
@@ -4170,7 +4397,7 @@ var FECManager = class _FECManager {
4170
4397
  this.#unindexBlockKey(key);
4171
4398
  }
4172
4399
  }
4173
- if (isSourceSymbol && source === "multicast") {
4400
+ if (isSourceSymbol && source !== "moq") {
4174
4401
  this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
4175
4402
  }
4176
4403
  return true;
@@ -4259,8 +4486,22 @@ var FECManager = class _FECManager {
4259
4486
  * DeliveryGapEstimator). Datagram delivery only.
4260
4487
  */
4261
4488
  noteMulticastArrival(packetId, packetSequenceNumber) {
4262
- if (this.#multicastSymbolDelivery !== "datagram") return;
4263
- this.#deliveryGaps.noteArrival(performance.now(), packetId, packetSequenceNumber);
4489
+ this.noteArrival("multicast", packetId, packetSequenceNumber);
4490
+ }
4491
+ /**
4492
+ * Record one MMTP packet arrival on a lossy path for that path's
4493
+ * delivery-gap measurement: the multicast leg (datagram delivery only; an
4494
+ * ordered relay settles by stream order) or an "mfu-datagram" leg, whose
4495
+ * datagrams are always a lossy path (#lossyDatagramPath).
4496
+ */
4497
+ noteArrival(path, packetId, packetSequenceNumber) {
4498
+ if (!this.#lossyDatagramPath(path)) return;
4499
+ this.#deliveryGaps[path].noteArrival(performance.now(), packetId, packetSequenceNumber);
4500
+ }
4501
+ /** The largest delivery gap any lossy path measured over its window. */
4502
+ #peakDeliveryGapMs() {
4503
+ const now = performance.now();
4504
+ return Math.max(...Object.values(this.#deliveryGaps).map((estimator) => estimator.peakGapMs(now)));
4264
4505
  }
4265
4506
  /**
4266
4507
  * Resolved per-track multicast late-symbol wait in milliseconds: the span
@@ -4274,16 +4515,18 @@ var FECManager = class _FECManager {
4274
4515
  * Largest multicast delivery gap measured over the current window (ms), and
4275
4516
  * that window (undefined: held since the last reset). Diagnostics.
4276
4517
  */
4277
- multicastDeliveryGap() {
4518
+ multicastDeliveryGap(path = "multicast") {
4278
4519
  return {
4279
- peakGapMs: this.#deliveryGaps.peakGapMs(performance.now()),
4280
- windowMs: this.#deliveryGaps.windowMs
4520
+ peakGapMs: this.#deliveryGaps[path].peakGapMs(performance.now()),
4521
+ windowMs: this.#deliveryGaps[path].windowMs
4281
4522
  };
4282
4523
  }
4283
4524
  /**
4284
4525
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
4285
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
4286
- * Undefined for a block that is not open.
4526
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
4527
+ * repair-less span states its length, and RSB_length 0 when it is longer
4528
+ * than K, since no repair can reach it). Undefined for a block that is not
4529
+ * open.
4287
4530
  */
4288
4531
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
4289
4532
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4373,6 +4616,23 @@ var FECManager = class _FECManager {
4373
4616
  const config = this.#trackConfigs.get(packetId);
4374
4617
  return config === void 0 ? void 0 : this.#blockLifetimeMs(config);
4375
4618
  }
4619
+ /**
4620
+ * How long an "mfu-datagram" leg's duplicate ledgers must remember a packet
4621
+ * so a legal reorder never reads as a publisher restart: one block span,
4622
+ * the reorder tolerance (`timeoutMs` is span + tolerance) and one group,
4623
+ * since a datagram may trail the stream by a whole group behind a joining
4624
+ * FETCH (mmt-02 6.1 step 3). The group is the catalog group duration
4625
+ * (`groupDurationMs`), whatever the track kind; a video track configured
4626
+ * without one falls back to its keyframe interval (one GOP per group).
4627
+ * Undefined for an unconfigured packet id.
4628
+ */
4629
+ datagramLegLedgerRetentionMsForPacket(packetId) {
4630
+ const config = this.#trackConfigs.get(packetId);
4631
+ if (config === void 0) return void 0;
4632
+ const geometry2 = config.geometry;
4633
+ const groupMs = config.groupDurationMs ?? (geometry2?.trackKind === "video" && geometry2.mode === "classifying" ? geometry2.keyframeInterval.ticks / geometry2.keyframeInterval.timescale * 1e3 : 0);
4634
+ return config.timeoutMs + (Number.isFinite(groupMs) ? groupMs : 0);
4635
+ }
4376
4636
  /**
4377
4637
  * How long a terminal (clean, recovered or failed) block stays authoritative,
4378
4638
  * for late symbols and for the in-order release gate. It is also the gate's
@@ -4399,7 +4659,7 @@ var FECManager = class _FECManager {
4399
4659
  }
4400
4660
  const trackConfig = this.#trackConfigs.get(packetId);
4401
4661
  if (trackConfig === void 0) return void 0;
4402
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
4662
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
4403
4663
  }
4404
4664
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
4405
4665
  // -----------------------------------------------------------------------
@@ -4441,6 +4701,9 @@ var FECManager = class _FECManager {
4441
4701
  for (const key of [...this.#isoLocators.keys()]) {
4442
4702
  if (this.#belongsToPacket(key, packetId)) this.#isoLocators.delete(key);
4443
4703
  }
4704
+ for (const key of [...this.#runAnchors.keys()]) {
4705
+ if (this.#belongsToPacket(key, packetId)) this.#runAnchors.delete(key);
4706
+ }
4444
4707
  }
4445
4708
  /**
4446
4709
  * The iso-ssbg1-v1 locator horizon in blocks: every block the manager can
@@ -4490,9 +4753,9 @@ var FECManager = class _FECManager {
4490
4753
  holdIsoSource(packetId, catalogTrackName, ssId, source) {
4491
4754
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4492
4755
  const evictedBefore = locator.heldEvicted;
4493
- const held = locator.hold(ssId, source);
4756
+ const held = locator.hold(ssId, source.arrivedAtMs === void 0 ? { ...source, arrivedAtMs: this.#receiptNow() } : source);
4494
4757
  this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4495
- if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4758
+ if (held && source.source !== "moq") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4496
4759
  const evicted = locator.heldEvicted - evictedBefore;
4497
4760
  if (evicted > 0) {
4498
4761
  const before = this.#isoHeldEvictedCount;
@@ -4585,12 +4848,24 @@ var FECManager = class _FECManager {
4585
4848
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
4586
4849
  * SS_ID of which vanished resolves through its deadline like any vanished
4587
4850
  * block.
4851
+ *
4852
+ * A span longer than K holds more than one block (SSB_length <= K), and the
4853
+ * locator states no block inside a span, only one exactly its range
4854
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
4855
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
4856
+ * Group of it (group-cannot-complete). Every span still keeps its whole
4857
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
4858
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
4859
+ * gate lets those frames go once only a late source can fill the gap
4860
+ * before them, as long after they arrived as the gap's decision allows
4861
+ * (isoRepairlessWaitMs).
4588
4862
  */
4589
4863
  #openIsoSpan(span, packetId, catalogTrackName) {
4590
4864
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
4591
4865
  if (!this.#blockAuthoredLengths.has(key)) {
4592
4866
  this.#blockAuthoredLengths.set(key, span.block.length);
4593
4867
  this.#isoSpanKeys.add(key);
4868
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
4594
4869
  }
4595
4870
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
4596
4871
  }
@@ -4598,7 +4873,12 @@ var FECManager = class _FECManager {
4598
4873
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
4599
4874
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
4600
4875
  * that could hold them is pending or not yet stated by a repair, else the
4601
- * starts of the blocks that failed or vanished.
4876
+ * starts of the blocks that failed or vanished. SS_IDs no repair has
4877
+ * delimited yet that all arrived lost nothing and wait for no repair, only
4878
+ * the late-source allowance after the datagram of a lossy path that clocks
4879
+ * them arrived (#lossFreeRunReadyAtMs), and not even that when none of them
4880
+ * came as one; one missing makes a run that waits as one block
4881
+ * (isoRepairlessWaitMs).
4602
4882
  *
4603
4883
  * `untracked` reads as the release gate reads it (MmtpRouter
4604
4884
  * #createFecReleaseGate): a block holding either released frame's SS_ID
@@ -4611,7 +4891,16 @@ var FECManager = class _FECManager {
4611
4891
  isoSpanResolution(packetId, catalogTrackName, fromSsId, toSsId) {
4612
4892
  if (!serial32Precedes(fromSsId, toSsId) || serial32Distance(fromSsId, toSsId) <= 1) return [];
4613
4893
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
4614
- if (!locator || !locator.coversBetween(fromSsId, toSsId)) return null;
4894
+ if (!locator) return null;
4895
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
4896
+ if (run?.missing !== void 0) return null;
4897
+ if (run !== null) {
4898
+ const config = this.#trackConfigs.get(packetId);
4899
+ const readyAtMs = config === void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
4900
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) return null;
4901
+ }
4902
+ if (locator.coverageEnd === void 0) return [];
4903
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return null;
4615
4904
  const highest = this.highestSbn(packetId, catalogTrackName);
4616
4905
  const lost = [];
4617
4906
  for (const block of locator.blocksBetween(fromSsId, toSsId)) {
@@ -4629,6 +4918,162 @@ var FECManager = class _FECManager {
4629
4918
  }
4630
4919
  return lost;
4631
4920
  }
4921
+ /**
4922
+ * When undelimited SS_IDs from `runStart` up to `toSsId` that all arrived
4923
+ * stop holding its frame: the late-source allowance after the receipt of
4924
+ * a datagram of a lossy path (#lossyDatagramPath: a multicast datagram, or
4925
+ * one of an "mfu-datagram" leg). Until then a frame between them may still
4926
+ * complete from a packet with no SS_ID (an untagged FT=0/FT=1 reordered
4927
+ * behind the next frame), and a repair may delimit them. The receipt is
4928
+ * `toSsId`'s own when it is held from such a datagram. Otherwise (its
4929
+ * packet came only as an overlap copy or from a MoQ stream, or was evicted
4930
+ * or retired) it is the newest among those SS_IDs, every one of which is
4931
+ * held and states its path. So the time moves at most once, when the
4932
+ * head's own datagram copy arrives while its frame waits or its held
4933
+ * source is dropped, and never on a later ask.
4934
+ *
4935
+ * Undefined, so the range releases at once, when no SS_ID of it came as
4936
+ * such a datagram: a MoQ arrival, an ordered relay's and the frame's own
4937
+ * are no clock for datagram reordering (#lossyReceiptMs). Undefined too
4938
+ * on a track with no catalog span, which states no allowance: the local
4939
+ * timeout is a cleanup bound, and isoRepairlessWaitMs arms no wake there,
4940
+ * so a wait would hold the frame until the next packet. The cost, on
4941
+ * multicast and on the leg too: an untagged FT=0/FT=1 reordered behind
4942
+ * the next frame of such a track is dropped stale.
4943
+ */
4944
+ #lossFreeRunReadyAtMs(config, locator, runStart, toSsId) {
4945
+ if (!_FECManager.#hasCatalogTiming(config)) return void 0;
4946
+ let clockMs = this.#lossyReceiptMs(locator.heldSource(toSsId));
4947
+ if (clockMs === void 0) {
4948
+ for (let ssId = runStart; ssId !== toSsId; ssId = ssId + 1 >>> 0) {
4949
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
4950
+ if (atMs !== void 0 && (clockMs === void 0 || atMs > clockMs)) clockMs = atMs;
4951
+ }
4952
+ }
4953
+ if (clockMs === void 0) return void 0;
4954
+ return clockMs + Math.max(0, this.#multicastWaitMs(config) - config.interleaveDepthMs);
4955
+ }
4956
+ /**
4957
+ * Receipt time of a held source that came as a datagram of a lossy path
4958
+ * (#lossyDatagramPath), else undefined: a MoQ stream and an ordered relay
4959
+ * deliver in order, so their arrivals clock no reorder allowance and no
4960
+ * FEC deadline. The path is the one the feed stated (IsoHeldSource.source,
4961
+ * and MulticastSymbolDelivery for a multicast source), never a guess.
4962
+ */
4963
+ #lossyReceiptMs(held) {
4964
+ return held !== void 0 && this.#lossyDatagramPath(held.source) ? held.arrivedAtMs : void 0;
4965
+ }
4966
+ /**
4967
+ * The one path predicate of the loss gates: whether a symbol fed as
4968
+ * `source` reached this manager as a datagram of its own, on a path that
4969
+ * loses and reorders (mmt-02 Section 2, a datagram leg). A multicast
4970
+ * symbol does unless its provider declared an ordered relay. An
4971
+ * "mfu-datagram" object always does (4.3.1): MulticastSymbolDelivery is
4972
+ * the multicast provider's statement and is never read for the leg. A MoQ
4973
+ * stream object never does, a stream copy of the leg included.
4974
+ */
4975
+ #lossyDatagramPath(source) {
4976
+ return source === "moq-datagram" || source === "multicast" && this.#multicastSymbolDelivery === "datagram";
4977
+ }
4978
+ /**
4979
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
4980
+ * between two released frames' SS_IDs once only a late source can still
4981
+ * fill them, else undefined. That is when every one missing (neither
4982
+ * arrived nor held) lies in a repair-less span longer than K, which no
4983
+ * repair can state a block of (#openIsoSpan), or in a stated block its
4984
+ * own repair group cannot complete every SS_ID of which it misses lies
4985
+ * between them (so the gap's decision covers all it lost), and a source of
4986
+ * a lossy leg (multicast, or an "mfu-datagram" leg's datagram) at or past
4987
+ * `toSsId` arrived, so each is lost or reordered behind it (a MoQ source
4988
+ * shows nothing: MoQ streams overtake one another). The span or block
4989
+ * itself keeps its own wait.
4990
+ *
4991
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
4992
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
4993
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
4994
+ * Then the frame waits as a stated block its group cannot complete does
4995
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
4996
+ * overlay's span plus the larger of the allowance and its tolerance, or,
4997
+ * for an overlay that states no span, the span's whole wait (undefined).
4998
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
4999
+ * the gap holds a stated block's loss.
5000
+ *
5001
+ * A run of SS_IDs no repair has delimited yet, one of which never arrived,
5002
+ * is one block of its own instead (draft-ramadan-moq-fec-multicast-00,
5003
+ * Receiver Repair Policy; on an "mfu-datagram" leg fec-core-00 9.3 and
5004
+ * mmt-02 5.3.3): the frame then waits for that block's FEC deadline,
5005
+ * whatever the flags: ts plus the whole multicast wait (fec-core-00 9.3),
5006
+ * ts the receipt of the lowest held source above the run that came as a
5007
+ * datagram of a lossy path (#lossyDatagramPath), up to the newest
5008
+ * (fec-multicast-00, Deadline Anchoring; under reordering at or after the
5009
+ * draft's first signal, never before). The wait returned counts from
5010
+ * `arrivedAtMs`, the frame's arrival; without it, it is the whole wait.
5011
+ * With no such source held (never arrived, retired, or evicted, or every
5012
+ * one from a MoQ stream or an ordered relay) the frame keeps the hold
5013
+ * ceiling: a stream arrival is no clock for a datagram deadline.
5014
+ */
5015
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false, arrivedAtMs) {
5016
+ const config = this.#trackConfigs.get(packetId);
5017
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
5018
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
5019
+ const locator = this.#isoLocators.get(streamKey);
5020
+ if (locator === void 0) return void 0;
5021
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
5022
+ const readyAtMs = run === null || run.missing !== void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
5023
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) {
5024
+ return Math.max(0, readyAtMs - (arrivedAtMs ?? this.#receiptNow()));
5025
+ }
5026
+ const newestSource = locator.newestSource;
5027
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
5028
+ if (run?.missing !== void 0) {
5029
+ if (this.isoSpanResolution(packetId, catalogTrackName, fromSsId, run.start) === null) return void 0;
5030
+ const kept = this.#runAnchors.get(streamKey);
5031
+ const anchor = kept?.fromSsId === fromSsId && this.#receiptNow() - kept.tsMs <= 2 * (config.interleaveDepthMs + 2 * this.#blockLifetimeMs(config)) ? kept : void 0;
5032
+ let tsMs = anchor?.tsMs;
5033
+ for (let ssId = run.missing + 1 >>> 0; !serial32Precedes(newestSource, ssId); ssId = ssId + 1 >>> 0) {
5034
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
5035
+ if (atMs === void 0) continue;
5036
+ if (tsMs === void 0 || atMs < tsMs) tsMs = atMs;
5037
+ break;
5038
+ }
5039
+ if (tsMs === void 0) return void 0;
5040
+ const waitMs2 = this.#multicastWaitMs(config);
5041
+ let counted = anchor?.counted === true;
5042
+ if (!counted && tsMs + waitMs2 <= this.#receiptNow()) {
5043
+ counted = true;
5044
+ this.onUndelimitedRunGap?.(packetId, catalogTrackName);
5045
+ }
5046
+ this.#runAnchors.set(streamKey, { fromSsId, tsMs, counted });
5047
+ return arrivedAtMs === void 0 ? waitMs2 : Math.max(0, tsMs + waitMs2 - arrivedAtMs);
5048
+ }
5049
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return void 0;
5050
+ let repairless = false;
5051
+ let stated = false;
5052
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
5053
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
5054
+ if (this.#completedBlocks.has(key)) continue;
5055
+ if (block.span && block.length > locator.kMax) {
5056
+ repairless = true;
5057
+ continue;
5058
+ }
5059
+ const received = this.#blockSourceEsis.get(key);
5060
+ const rebuilt = this.#blockRebuiltEsis.get(key);
5061
+ let missesInGap = false;
5062
+ let missesOutside = false;
5063
+ for (let esi = 0; esi < block.length; esi++) {
5064
+ const ssId = serial32Add(block.start, esi);
5065
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
5066
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
5067
+ else if (!rebuilt?.has(esi)) missesOutside = true;
5068
+ }
5069
+ if (!missesInGap) continue;
5070
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
5071
+ repairless = stated = true;
5072
+ }
5073
+ if (!repairless) return void 0;
5074
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
5075
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
5076
+ }
4632
5077
  /**
4633
5078
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
4634
5079
  * the sources held now for a block no repair has stated yet, and the held
@@ -4682,11 +5127,31 @@ var FECManager = class _FECManager {
4682
5127
  * it does not. A stream with no classifier yet has shown nothing against it,
4683
5128
  * and neither has a stream without catalog timing until it releases two
4684
5129
  * RAPs inside one MPU.
4685
- */
4686
- mpuBoundsRapsFor(packetId, catalogTrackName) {
5130
+ *
5131
+ * With catalog timing and a `gap` inside one MPU, between the authored
5132
+ * timing of the frames on either side, it also takes the catalog keyframe
5133
+ * interval to rule a keyframe out of the gap
5134
+ * (`BlockClassifier.keyframeFreeBetween`, fec-multicast-00 Block
5135
+ * Classification item 3), and no source held between the frames' SS_IDs
5136
+ * may carry the RAP flag or another MPU's number (item 1 read on the held
5137
+ * packets: a RAP the loss cut in two is never released, so the frames
5138
+ * alone cannot show it); anything unknown counts as a keyframe.
5139
+ */
5140
+ mpuBoundsRapsFor(packetId, catalogTrackName, gap) {
4687
5141
  const streamKey = this.#streamKey(packetId, catalogTrackName);
4688
5142
  if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
4689
- return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true;
5143
+ const classifier = this.#classifiers.get(streamKey);
5144
+ if (gap === void 0) return classifier?.mpuBoundsRaps ?? true;
5145
+ const { mpu, from, to, fromSsId, toSsId } = gap;
5146
+ if (fromSsId !== void 0 && toSsId !== void 0) {
5147
+ const run = this.#isoLocators.get(streamKey)?.undelimitedBetween(
5148
+ fromSsId,
5149
+ toSsId,
5150
+ ({ evidence }) => evidence.rap || evidence.mpu !== void 0 && evidence.mpu !== mpu
5151
+ );
5152
+ if (run?.flagged) return false;
5153
+ }
5154
+ return classifier !== void 0 && from !== void 0 && to !== void 0 && from.mediaTimescale === to.mediaTimescale && classifier.keyframeFreeBetween(mpu, from.decodeTime, to.decodeTime, from.mediaTimescale);
4690
5155
  }
4691
5156
  /** A block's class now, or frozen at its resolution. */
4692
5157
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -4709,9 +5174,11 @@ var FECManager = class _FECManager {
4709
5174
  }
4710
5175
  /**
4711
5176
  * Record a RAP frame released in order, for the classifier's RAP-spacing
4712
- * invariant (consecutive MPUs exactly one keyframe interval apart).
5177
+ * invariant (consecutive MPUs exactly one keyframe interval apart) and,
5178
+ * with its decode time, as the MPU start gap decisions measure the catalog
5179
+ * keyframe interval from (mpuBoundsRapsFor).
4713
5180
  */
4714
- noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
5181
+ noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale, decodeTime) {
4715
5182
  if (!this.#trackConfigs.has(packetId)) return;
4716
5183
  if (!this.#hasCatalogTimingForPacket(packetId)) {
4717
5184
  const streamKey = this.#streamKey(packetId, catalogTrackName);
@@ -4726,7 +5193,8 @@ var FECManager = class _FECManager {
4726
5193
  this.#classifierFor(packetId, catalogTrackName).noteReleasedRap(
4727
5194
  mpu,
4728
5195
  presentationTime,
4729
- mediaTimescale
5196
+ mediaTimescale,
5197
+ decodeTime
4730
5198
  )
4731
5199
  );
4732
5200
  }
@@ -5277,7 +5745,10 @@ var FECManager = class _FECManager {
5277
5745
  this.#layerAnchorHorizon(packetId),
5278
5746
  this.#sourceFrontiers.get(streamKey)?.sbn
5279
5747
  );
5280
- if (verdict === "discard") return false;
5748
+ if (verdict === "discard") {
5749
+ this.#unlistedRepairTrackRefusals++;
5750
+ return false;
5751
+ }
5281
5752
  if (verdict !== void 0) {
5282
5753
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName);
5283
5754
  return false;
@@ -5426,15 +5897,17 @@ var FECManager = class _FECManager {
5426
5897
  * its sources in send order, so one that moves the stream's newest source
5427
5898
  * position past a block leaves the sources that block still misses
5428
5899
  * reordered behind it at best: it shortens the wait of every block it
5429
- * passed that only a late source can complete. MoQ is left out: its streams
5430
- * can overtake one another, so a MoQ source shows nothing about the sources
5431
- * sent before it.
5900
+ * passed that only a late source can complete. Reliable MoQ is left out:
5901
+ * its streams can overtake one another, so a MoQ source shows nothing
5902
+ * about the sources sent before it. An "mfu-datagram" leg is in: its
5903
+ * datagrams leave the publisher in send order and reorder only within the
5904
+ * path's tolerance, as multicast does.
5432
5905
  */
5433
5906
  #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
5434
5907
  const previous = locator.newestSource;
5435
5908
  if (!locator.noteSource(ssId) || previous === void 0) return;
5436
5909
  for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
5437
- if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5910
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5438
5911
  this.#shortenUnrecoverableWait(
5439
5912
  this.#blockKey(block.start, packetId, catalogTrackName),
5440
5913
  block.start,
@@ -5452,21 +5925,61 @@ var FECManager = class _FECManager {
5452
5925
  * covers repair symbols paced after its sources, buys it nothing: it waits
5453
5926
  * the late-symbol allowance alone, the multicast wait less the span (the
5454
5927
  * catalog tolerance or the measured delivery gap). Undefined for any other
5455
- * block.
5928
+ * block. While a keyframe overlay is installed, the block waits for its
5929
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
5930
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
5931
+ * resolution is what releases the frames behind it, and failing it early
5932
+ * released them past a keyframe the overlay was still rebuilding, which
5933
+ * then arrived stale. The release gate lets them go instead
5934
+ * (isoRepairlessWaitMs).
5456
5935
  */
5457
5936
  #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
5937
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
5458
5938
  const authoredLength = this.#blockAuthoredLengths.get(key);
5459
- const rsbLength = this.#blockRsbLengths.get(key);
5460
- if (authoredLength === void 0 || rsbLength === void 0) return void 0;
5461
- let present = this.#blockSourceCounts.get(key) ?? 0;
5462
- const received = this.#blockSourceEsis.get(key);
5463
- for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5464
- if (present + rsbLength >= authoredLength) return void 0;
5465
5939
  const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
5466
5940
  if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5467
5941
  return void 0;
5468
5942
  }
5469
- return this.#multicastWaitMs(config) - config.interleaveDepthMs;
5943
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
5944
+ }
5945
+ /**
5946
+ * A repair stated the block, and its sources plus every symbol its repair
5947
+ * group carries (RSB_length) are short of its SSB_length.
5948
+ */
5949
+ #groupCannotComplete(key) {
5950
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5951
+ const rsbLength = this.#blockRsbLengths.get(key);
5952
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
5953
+ let present = this.#blockSourceCounts.get(key) ?? 0;
5954
+ const received = this.#blockSourceEsis.get(key);
5955
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5956
+ return present + rsbLength < authoredLength;
5957
+ }
5958
+ /**
5959
+ * How long a loss only a late source or an installed keyframe overlay can
5960
+ * still fill waits once a later source passed it: the late-symbol
5961
+ * allowance alone (the multicast wait less the span) while no overlay is
5962
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
5963
+ * RAP packet the loss took: a second FEC instance over the same packets
5964
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
5965
+ * span, unrelated to the base's. That packet can complete a stated block
5966
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
5967
+ * first lets the release gate pass the keyframe, whose rebuild then lands
5968
+ * stale. The overlay repair of a packet the loss took goes out within the
5969
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
5970
+ * sent after it, so the loss waits that span plus the larger of the
5971
+ * allowance and the overlay's own tolerance. An overlay that states no
5972
+ * span (its block may then span keyframes), or one whose wait is not
5973
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
5974
+ */
5975
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
5976
+ const waitMs = this.#multicastWaitMs(config);
5977
+ const allowanceMs = waitMs - config.interleaveDepthMs;
5978
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
5979
+ if (overlay === void 0) return allowanceMs;
5980
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
5981
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
5982
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
5470
5983
  }
5471
5984
  /**
5472
5985
  * Bring an open block's wait in to its late-source wait, when it has one.
@@ -5855,7 +6368,7 @@ var FECManager = class _FECManager {
5855
6368
  blockDeliveryProvenance(sbn, packetId, catalogTrackName) {
5856
6369
  const counts = this.blockPathCount(sbn, packetId, catalogTrackName);
5857
6370
  if (!counts) return "unknown";
5858
- if (counts.moqSymbols > 0) return "mixed";
6371
+ if (counts.moqSymbols > 0 || counts.datagramSymbols > 0) return "mixed";
5859
6372
  if (counts.multicastSymbols > 0) return "multicast";
5860
6373
  return "unknown";
5861
6374
  }
@@ -5882,7 +6395,7 @@ var FECManager = class _FECManager {
5882
6395
  this.#activeBlockDeadlinesMs.clear();
5883
6396
  this.#blockWaitDeadlinesMs.clear();
5884
6397
  this.#repairHoldUntilMs.clear();
5885
- this.#deliveryGaps.reset();
6398
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.reset();
5886
6399
  this.#pendingWorkerCleanups.clear();
5887
6400
  this.#pendingWorkerCleanupClients.clear();
5888
6401
  for (const bound of this.#pendingWorkerCleanupBounds.values()) clearTimeout(bound.handle);
@@ -5933,6 +6446,7 @@ var FECManager = class _FECManager {
5933
6446
  this.#highestSbn.clear();
5934
6447
  this.#sourceFrontiers.clear();
5935
6448
  this.#isoLocators.clear();
6449
+ this.#runAnchors.clear();
5936
6450
  this.#sourceAnchors.clear();
5937
6451
  this.#trackConfigs.clear();
5938
6452
  this.#fecDecoders.clear();
@@ -6213,6 +6727,40 @@ var RUNTIME_FEC_RECEIVER2 = Object.freeze({
6213
6727
  overlays: true
6214
6728
  });
6215
6729
 
6730
+ // node_modules/@blockcast/mmt-base/dist/mmtp-siblings.js
6731
+ var MMTP_MODES2 = Object.freeze(["mfu", "mfu-datagram"]);
6732
+ var MMTP_SIBLING_HARD_FIELDS2 = Object.freeze([
6733
+ "namespace",
6734
+ "timescale",
6735
+ "presentationAnchorTicks",
6736
+ "groupDuration"
6737
+ ]);
6738
+ var MMTP_SIBLING_RENDITION_FIELDS2 = Object.freeze([
6739
+ "codec",
6740
+ "width",
6741
+ "height",
6742
+ "framerate",
6743
+ "bitrate",
6744
+ "samplerate",
6745
+ "channelConfig",
6746
+ "lang"
6747
+ ]);
6748
+ var MMTP_SIBLING_SOFT_FIELDS2 = Object.freeze([
6749
+ "initRef",
6750
+ "keyframeIntervalMs",
6751
+ "keyframeIntervalTicks",
6752
+ "isLive",
6753
+ "altGroup"
6754
+ ]);
6755
+
6756
+ // node_modules/@blockcast/mmt-base/dist/datagram-leg-size.js
6757
+ var DATAGRAM_LEG_UDP_FLOOR2 = 1200;
6758
+ var DATAGRAM_LEG_QUIC_WT_FRAMING2 = 48;
6759
+ var DATAGRAM_LEG_OBJECT_HEADER2 = 13;
6760
+ var DATAGRAM_LEG_RELAY_ROOM2 = 16;
6761
+ var DATAGRAM_LEG_DATAGRAM_MAX2 = DATAGRAM_LEG_UDP_FLOOR2 - DATAGRAM_LEG_QUIC_WT_FRAMING2;
6762
+ var DATAGRAM_LEG_BODY_MAX2 = DATAGRAM_LEG_DATAGRAM_MAX2 - DATAGRAM_LEG_OBJECT_HEADER2 - DATAGRAM_LEG_RELAY_ROOM2;
6763
+
6216
6764
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
6217
6765
  var DEFAULT_DWELL_MS = 3e3;
6218
6766
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -10616,9 +11164,10 @@ function isH264IntraSlice(nal) {
10616
11164
  const sliceType = readH264SliceType(nal);
10617
11165
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
10618
11166
  }
11167
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
10619
11168
  function readH264SliceType(nal) {
10620
11169
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10621
- const rbsp = removeEmulationPrevention(nal.subarray(1));
11170
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
10622
11171
  const state = { bitOffset: 0 };
10623
11172
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10624
11173
  return readUnsignedExpGolomb(rbsp, state);
@@ -10765,6 +11314,96 @@ if (void 0) {
10765
11314
  ]))).toBe(false);
10766
11315
  });
10767
11316
  });
11317
+ describe("readH264SliceType", () => {
11318
+ const wholeNalSliceType = (nal) => {
11319
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
11320
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
11321
+ const state = { bitOffset: 0 };
11322
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
11323
+ return readUnsignedExpGolomb(rbsp, state);
11324
+ };
11325
+ const hex2 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
11326
+ const ue = (value) => {
11327
+ const code = (value + 1).toString(2);
11328
+ return "0".repeat(code.length - 1) + code;
11329
+ };
11330
+ const sliceNal = (bits) => {
11331
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
11332
+ const nal = [1];
11333
+ let zeros = 0;
11334
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
11335
+ if (zeros >= 2 && byte <= 3) {
11336
+ nal.push(3);
11337
+ zeros = 0;
11338
+ }
11339
+ nal.push(byte);
11340
+ zeros = byte === 0 ? zeros + 1 : 0;
11341
+ }
11342
+ return Uint8Array.from(nal);
11343
+ };
11344
+ const x264Slices = [
11345
+ ["64x48 P", hex2("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
11346
+ ["64x48 B", hex2("419e414212fffeeade283707cb70f7"), 6, false],
11347
+ ["64x48 non-IDR I", hex2(
11348
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
11349
+ ), 7, true],
11350
+ ["1280x720 B, escape at byte 10", hex2(
11351
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
11352
+ ), 6, false],
11353
+ ["1280x720 P, escape at byte 15", hex2(
11354
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
11355
+ ), 5, false],
11356
+ ["1280x720 B, escape at byte 22", hex2("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
11357
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex2(
11358
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
11359
+ ), null, true],
11360
+ ["7680x4320 P, first_mb_in_slice 32640", hex2(
11361
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
11362
+ ), 5, false],
11363
+ ["7680x4320 P, first_mb_in_slice 97440", hex2(
11364
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
11365
+ ), 5, false]
11366
+ ];
11367
+ const syntheticSlices = [
11368
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
11369
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
11370
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
11371
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
11372
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
11373
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
11374
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
11375
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
11376
+ ];
11377
+ test("reads the slice_type of real and synthetic slices", () => {
11378
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
11379
+ expect(readH264SliceType(nal), name).toBe(sliceType);
11380
+ }
11381
+ });
11382
+ test("matches the whole-NAL unescape at every truncation", () => {
11383
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
11384
+ for (let end = 0; end <= nal.length; end++) {
11385
+ const cut = nal.subarray(0, end);
11386
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
11387
+ }
11388
+ }
11389
+ });
11390
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
11391
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
11392
+ let seed = 1;
11393
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
11394
+ for (let i = 0; i < 5e3; i++) {
11395
+ const nal = new Uint8Array(2 + next() % 63);
11396
+ nal[0] = 65;
11397
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
11398
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
11399
+ }
11400
+ });
11401
+ test("classifies the x264 slices as keyframes or not", () => {
11402
+ for (const [name, nal, , keyframe] of x264Slices) {
11403
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
11404
+ }
11405
+ });
11406
+ });
10768
11407
  describe("avccToAnnexB", () => {
10769
11408
  test("converts with SPS/PPS on keyframe", () => {
10770
11409
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -14118,7 +14757,7 @@ var FecReleaseSequencer = class {
14118
14757
  from
14119
14758
  );
14120
14759
  unresolved = resolved === null;
14121
- if (unresolved && !this.#cursorPassed(stream, asUnanchored)) {
14760
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
14122
14761
  const heldMs = performance.now() - head.arrivedAtMs;
14123
14762
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
14124
14763
  this.#recordStat("forcedWindowFlushes");
@@ -14136,6 +14775,19 @@ var FecReleaseSequencer = class {
14136
14775
  );
14137
14776
  }
14138
14777
  }
14778
+ /**
14779
+ * The head has waited out a gap only a late source can still fill
14780
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
14781
+ * the stream when it has (`wakeAt`), since no packet may come by then.
14782
+ */
14783
+ #unrepairableWaitOver(stream, last, head, from, to) {
14784
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
14785
+ if (waitMs === void 0) return false;
14786
+ const atMs = head.arrivedAtMs + waitMs;
14787
+ if (performance.now() >= atMs) return true;
14788
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
14789
+ return false;
14790
+ }
14139
14791
  /**
14140
14792
  * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
14141
14793
  * source cursor holds it unanchored, and neither does a later frame behind
@@ -18611,6 +19263,20 @@ var MmtpRouter = class {
18611
19263
  /** The flow whose receiver admitted a stream's source datagrams, by packetId then catalog track name: recovered packets answer to it. */
18612
19264
  #provenanceStreamFlow = /* @__PURE__ */ new Map();
18613
19265
  #unregisteredFlowDrops = 0;
19266
+ /** "mfu-datagram" leg packets of a packet id the ingress does not name (never the signaling flow). */
19267
+ #datagramLegIngressDrops = 0;
19268
+ /** "mfu-datagram" leg packets of the signaling flow (packet id 0): expected, one per group. */
19269
+ #datagramLegSignalingPackets = 0;
19270
+ /**
19271
+ * The streams a live "mfu-datagram" leg has fed, catalog track names by
19272
+ * packet id: their ledgers and release gate take the leg's bounds. A stream
19273
+ * leaves when its leg does: `endDatagramLeg`, `resetTrack`, `dispose`, or
19274
+ * the first multicast packet of its packet id (the ordered switch retires
19275
+ * the leg first). The "mfu" sibling shares the packet id, never the name.
19276
+ */
19277
+ #datagramLegStreams = /* @__PURE__ */ new Map();
19278
+ /** The leg's presentation budget (setDatagramLegPresentationBudget), or null: no presentation bound. */
19279
+ #datagramLegPresentationBudgetMs = null;
18614
19280
  #ambiguousRecoveredDrops = 0;
18615
19281
  // Temp state set by #processMMTP before calling parser.feed(),
18616
19282
  // read by the parser's onFrame callback for CMAF assembly + dedup.
@@ -18716,6 +19382,8 @@ var MmtpRouter = class {
18716
19382
  // end: a synchronous recovery completes its block BEFORE routing the
18717
19383
  // recovered frames, and releasing a held gap in between would strand them.
18718
19384
  #fecPokeDepth = 0;
19385
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
19386
+ #fecWakes = /* @__PURE__ */ new Map();
18719
19387
  #pendingFecPokes = /* @__PURE__ */ new Map();
18720
19388
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
18721
19389
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -18984,10 +19652,11 @@ var MmtpRouter = class {
18984
19652
  const blockLifetimeMs = fec.blockLifetimeMsForPacket(packetId);
18985
19653
  if (blockSpanMs === void 0 || blockLifetimeMs === void 0) return NO_FEC_GEOMETRY_HORIZON;
18986
19654
  if (blockSpanMs === 0) return NO_BLOCK_SPAN_HORIZON;
18987
- return {
18988
- kind: "fec-horizon",
18989
- retentionMs: duplicateRetentionMs({ blockSpanMs, blockLifetimeMs })
18990
- };
19655
+ let retentionMs = duplicateRetentionMs({ blockSpanMs, blockLifetimeMs });
19656
+ if (this.#datagramLegStreams.has(packetId)) {
19657
+ retentionMs = Math.max(retentionMs, fec.datagramLegLedgerRetentionMsForPacket?.(packetId) ?? 0);
19658
+ }
19659
+ return { kind: "fec-horizon", retentionMs };
18991
19660
  }
18992
19661
  /**
18993
19662
  * Init segments rejected since construction because their packetId had no
@@ -19410,7 +20079,7 @@ var MmtpRouter = class {
19410
20079
  const blockStart = placement.block.start;
19411
20080
  if (placement.span !== void 0) this.#replayOverlaySources(inst, placement.span.block.start, placement.span.placed);
19412
20081
  this.#replayOverlaySources(inst, blockStart, placement.placed);
19413
- if (source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
20082
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
19414
20083
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
19415
20084
  const recovered = fec.feedRepairSymbol(pid, repair.ssStart, repair.ssbLength, repair.rsId, repair.symbolData, name);
19416
20085
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, blockStart, recovered);
@@ -19418,7 +20087,7 @@ var MmtpRouter = class {
19418
20087
  #replayOverlaySources(inst, blockStart, placed) {
19419
20088
  const { fec, repairPacketId: pid, streamName: name } = inst;
19420
20089
  for (const { ssId, payload } of placed) {
19421
- if (payload.source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
20090
+ if (payload.source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
19422
20091
  if (payload.oversized) continue;
19423
20092
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
19424
20093
  const recovered = fec.feedSourceSymbol(pid, ssId, payload.symbolData, name);
@@ -19471,7 +20140,7 @@ var MmtpRouter = class {
19471
20140
  });
19472
20141
  continue;
19473
20142
  }
19474
- if (source === "moq") this.#noteOverlayMoqBlock(inst, coords.sbn);
20143
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, coords.sbn);
19475
20144
  if (oversized) continue;
19476
20145
  const alreadyCompleted = fec.isBlockCompleted(coords.sbn, pid, name);
19477
20146
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
@@ -20060,6 +20729,46 @@ var MmtpRouter = class {
20060
20729
  get unregisteredFlowDropCount() {
20061
20730
  return this.#unregisteredFlowDrops;
20062
20731
  }
20732
+ /** "mfu-datagram" leg packets dropped because the leg's ingress does not name their packet id (packet id 0 apart). */
20733
+ get datagramLegIngressDropCount() {
20734
+ return this.#datagramLegIngressDrops;
20735
+ }
20736
+ /** "mfu-datagram" leg packets of the MMTP signaling flow (packet id 0), which no track owns. */
20737
+ get datagramLegSignalingPacketCount() {
20738
+ return this.#datagramLegSignalingPackets;
20739
+ }
20740
+ /**
20741
+ * The "mfu-datagram" leg's presentation bound (mmt-02 6.1 step 6): how
20742
+ * long after a frame arrives it must leave the release gate when the gap
20743
+ * before it holds no RAP, FT=0 or FT=1 data (the player's presentation
20744
+ * delay less its decode lead). The gap is then decided at the earlier of
20745
+ * the FEC block deadline and this bound; a gap that may hold a RAP keeps
20746
+ * the block deadline. Null, or a value that is not finite and positive:
20747
+ * the block deadline alone, as on multicast.
20748
+ */
20749
+ setDatagramLegPresentationBudget(budgetMs) {
20750
+ this.#datagramLegPresentationBudgetMs = budgetMs;
20751
+ }
20752
+ /**
20753
+ * The "mfu-datagram" leg is over (unsubscribed, or switched to another
20754
+ * path): no stream keeps its presentation bound or its ledger retention.
20755
+ * Parser, FEC and ledger state stay, so the packet ids continue on the
20756
+ * next path without an epoch. A later leg datagram starts a leg again.
20757
+ */
20758
+ endDatagramLeg() {
20759
+ this.#datagramLegStreams.clear();
20760
+ this.#datagramLegPresentationBudgetMs = null;
20761
+ }
20762
+ #datagramLegPresentationWaitMs(packetId, catalogTrackName) {
20763
+ if (this.#datagramLegPresentationBudgetMs === null || this.#datagramLegStreams.get(packetId)?.has(catalogTrackName) !== true) return void 0;
20764
+ let budgetMs;
20765
+ try {
20766
+ budgetMs = this.#datagramLegPresentationBudgetMs(packetId, catalogTrackName);
20767
+ } catch {
20768
+ return void 0;
20769
+ }
20770
+ return Number.isFinite(budgetMs) && budgetMs > 0 ? budgetMs : void 0;
20771
+ }
20063
20772
  /** Recovered packets dropped because more than one protected flow could own their stream. */
20064
20773
  get ambiguousRecoveredDropCount() {
20065
20774
  return this.#ambiguousRecoveredDrops;
@@ -20077,6 +20786,10 @@ var MmtpRouter = class {
20077
20786
  * caller that forgot it silently attributed its bytes to a multicast socket
20078
20787
  * they may never have crossed — and that attribution is what the physical-
20079
20788
  * delivery evidence path is built on. Absence is not multicast; say which.
20789
+ * `"moq-datagram"` is an "mfu-datagram" subscription (MmtpIngestSource):
20790
+ * `ingress.tracks` MUST name the datagram catalog track for its packet id,
20791
+ * and a packet of a packet id it does not name is dropped and counted
20792
+ * (`datagramLegIngressDropCount`; the signaling flow, packet id 0, apart).
20080
20793
  */
20081
20794
  feedPacket(packet, source, ingress) {
20082
20795
  if (this.#disposed) return;
@@ -20126,15 +20839,18 @@ var MmtpRouter = class {
20126
20839
  }
20127
20840
  /**
20128
20841
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
20129
- * header and delegates to FECManager for FEC recovery.
20842
+ * header and delegates to FECManager for FEC recovery. `source` is
20843
+ * `"moq-datagram"` for a repair object of an "mfu-datagram" track's repair
20844
+ * track, which arrives as a datagram and so counts as an in-band symbol of
20845
+ * the leg; a FETCHed repair stays `"moq"` (RepairVia `quic`).
20130
20846
  */
20131
- feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
20847
+ feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source = "moq") {
20132
20848
  if (this.#disposed) return;
20133
20849
  this.#withDeferredFecPokes(() => {
20134
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
20850
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source);
20135
20851
  });
20136
20852
  }
20137
- #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, admitted = false) {
20853
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source, admitted = false) {
20138
20854
  let header;
20139
20855
  try {
20140
20856
  header = parseMMTPHeader(packet);
@@ -20144,7 +20860,7 @@ var MmtpRouter = class {
20144
20860
  const repairPacketId = header.packetId;
20145
20861
  const overlay = this.#overlayRepairTarget(repairPacketId, repairTrackName);
20146
20862
  if (overlay !== void 0) {
20147
- this.#routeOverlayRepair(overlay, repairPacketId, packet, header, "moq");
20863
+ this.#routeOverlayRepair(overlay, repairPacketId, packet, header, source);
20148
20864
  return;
20149
20865
  }
20150
20866
  const hintedOwner = ownerPacketIdHint != null && this.#classifyPacketId(ownerPacketIdHint) !== null ? ownerPacketIdHint : null;
@@ -20156,7 +20872,7 @@ var MmtpRouter = class {
20156
20872
  }
20157
20873
  let unlisted = false;
20158
20874
  if (ownerPacketId != null && !admitted) {
20159
- const admit = this.#admitUnicast(repairPacketId, packet, () => this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, true));
20875
+ const admit = this.#admitUnicast(repairPacketId, packet, () => this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source, true));
20160
20876
  if (admit === "held" || admit === "dropped") return;
20161
20877
  unlisted = admit === "unlisted";
20162
20878
  }
@@ -20177,7 +20893,7 @@ var MmtpRouter = class {
20177
20893
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
20178
20894
  return;
20179
20895
  }
20180
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
20896
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, source, repairTrackName);
20181
20897
  }
20182
20898
  }
20183
20899
  // ── Packet FEC geometry and block profile ───────────────────────
@@ -20382,6 +21098,7 @@ var MmtpRouter = class {
20382
21098
  debugRouter(
20383
21099
  `[MmtpRouter] Dropping repair packet pid=${packetId}: physical PID is unregistered`
20384
21100
  );
21101
+ this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
20385
21102
  return null;
20386
21103
  }
20387
21104
  const registeredOwners = this.#repairOwnersByPacketId.get(packetId) ?? /* @__PURE__ */ new Set();
@@ -20390,6 +21107,7 @@ var MmtpRouter = class {
20390
21107
  debugRouter(
20391
21108
  `[MmtpRouter] Dropping repair packet pid=${packetId}: catalog owner is ${owners.length === 0 ? "absent" : "ambiguous"}`
20392
21109
  );
21110
+ this.#fecManager?.countUnresolvedRepairOwner?.(owners.length === 0 ? "ownerAbsent" : "ownerAmbiguous");
20393
21111
  return null;
20394
21112
  }
20395
21113
  /** Route a recovered FEC block through the parser + dedup pipeline.
@@ -20439,6 +21157,8 @@ var MmtpRouter = class {
20439
21157
  }
20440
21158
  this.#parser.resetTrack(packetId, catalogTrackName);
20441
21159
  this.resetKeyframeOverlays(packetId, catalogTrackName);
21160
+ const legNames = this.#datagramLegStreams.get(packetId);
21161
+ if (legNames?.delete(catalogTrackName) && legNames.size === 0) this.#datagramLegStreams.delete(packetId);
20442
21162
  this.#restampedStreams.delete(this.#mediaStreamKey(packetId, catalogTrackName));
20443
21163
  const assistPrefix = assistKey(packetId, catalogTrackName, 0).slice(0, -1);
20444
21164
  for (const key of this.#assistBlocks.keys()) if (key.startsWith(assistPrefix)) this.#assistBlocks.delete(key);
@@ -20776,8 +21496,11 @@ var MmtpRouter = class {
20776
21496
  this.#disposed = true;
20777
21497
  this.#staged = null;
20778
21498
  this.cancelKeyframeLostTimer();
21499
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
21500
+ this.#fecWakes.clear();
20779
21501
  this.#parser.dispose();
20780
21502
  this.#streams.clear();
21503
+ this.endDatagramLeg();
20781
21504
  this.#trackPacketCallbacks.clear();
20782
21505
  this.#latestVideoSeqByStream.clear();
20783
21506
  this.#lastDirectSourceVideoTsByStream.clear();
@@ -20957,6 +21680,38 @@ var MmtpRouter = class {
20957
21680
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
20958
21681
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
20959
21682
  },
21683
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
21684
+ // late source can), its frame waits the late-symbol allowance when the
21685
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
21686
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
21687
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
21688
+ // unless the gap holds a stated block's loss: the overlay may rebuild
21689
+ // that MPU's FT=0, and the block's group then complete it), or
21690
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
21691
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
21692
+ // overlay protects) waits for that overlay's repair too (BLO-52085
21693
+ // D4). A run no repair has delimited instead waits for its FEC
21694
+ // deadline, whatever the decision (FECManager.isoRepairlessWaitMs). The
21695
+ // FEC check comes first: most held gaps are not behind such a span, and
21696
+ // deciding one scans both frames' bitstreams.
21697
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
21698
+ const fec = this.#fecManager;
21699
+ const { packetId, catalogTrackName } = after.meta;
21700
+ const arrivedAtMs = after.arrivedAtMs;
21701
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, false, arrivedAtMs);
21702
+ const presentationMs = this.#datagramLegPresentationWaitMs(packetId, catalogTrackName);
21703
+ if (!fec || allowanceMs === void 0 && presentationMs === void 0) return void 0;
21704
+ const decision = this.#decideGap(before, after, [], false);
21705
+ const mpu = before.meta.mpuSequenceNumber;
21706
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
21707
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
21708
+ return allowanceMs === void 0 ? void 0 : fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true, false, arrivedAtMs);
21709
+ }
21710
+ const waitMs = allowanceMs === void 0 ? void 0 : decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true, arrivedAtMs) : allowanceMs;
21711
+ if (decision.reason === "delta-lost" && !((fec.interleaveDepthMsForPacket?.(packetId) ?? 0) > 0)) return waitMs;
21712
+ if (presentationMs === void 0) return waitMs;
21713
+ return waitMs === void 0 ? presentationMs : Math.min(waitMs, presentationMs);
21714
+ },
20960
21715
  decide: (before, after, lostBlocks, discontinuity) => {
20961
21716
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
20962
21717
  this.#onFrameGap?.(decision);
@@ -20966,6 +21721,20 @@ var MmtpRouter = class {
20966
21721
  onRap: (packetId, catalogTrackName, ssId) => {
20967
21722
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
20968
21723
  },
21724
+ // One timer per stream, at the earliest wake asked: its drain re-arms
21725
+ // for the next frame still waiting.
21726
+ wakeAt: (packetId, catalogTrackName, atMs) => {
21727
+ if (this.#disposed) return;
21728
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
21729
+ const armed = this.#fecWakes.get(key);
21730
+ if (armed !== void 0 && armed.atMs <= atMs) return;
21731
+ if (armed !== void 0) clearTimeout(armed.timer);
21732
+ const timer = setTimeout(() => {
21733
+ this.#fecWakes.delete(key);
21734
+ this.#requestFecPoke(packetId, catalogTrackName);
21735
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
21736
+ this.#fecWakes.set(key, { atMs, timer });
21737
+ },
20969
21738
  // A staged switch commits on when each side's frames reach it
20970
21739
  // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
20971
21740
  // they did unanchored.
@@ -20983,7 +21752,8 @@ var MmtpRouter = class {
20983
21752
  meta.catalogTrackName,
20984
21753
  meta.mpuSequenceNumber,
20985
21754
  timing.presentationTime,
20986
- timing.mediaTimescale
21755
+ timing.mediaTimescale,
21756
+ timing.decodeTime
20987
21757
  );
20988
21758
  }
20989
21759
  };
@@ -21001,8 +21771,20 @@ var MmtpRouter = class {
21001
21771
  #decideGap(before, after, lostBlocks, discontinuity) {
21002
21772
  const { packetId, catalogTrackName } = after.meta;
21003
21773
  const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
21004
- const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying";
21005
- const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
21774
+ const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying" && before.meta.movieFragmentSequenceNumber === after.meta.movieFragmentSequenceNumber;
21775
+ const mpu = before.meta.mpuSequenceNumber;
21776
+ const sameMpu = trackKind === "video" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu;
21777
+ const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(
21778
+ packetId,
21779
+ catalogTrackName,
21780
+ sameMpu ? {
21781
+ mpu,
21782
+ from: before.meta.authoredTiming,
21783
+ to: after.meta.authoredTiming,
21784
+ fromSsId: before.meta.fecSbn,
21785
+ toSsId: after.meta.fecSbnFirst ?? after.meta.fecSbn
21786
+ } : void 0
21787
+ ) === true;
21006
21788
  const evidence = (frame) => {
21007
21789
  const timing = frame.meta.authoredTiming;
21008
21790
  const sampleNumber = frame.meta.sampleNumber;
@@ -21118,18 +21900,34 @@ var MmtpRouter = class {
21118
21900
  if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
21119
21901
  if (source === "multicast" && !manifestAdmitted) {
21120
21902
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
21903
+ } else if (source === "moq-datagram" && !manifestAdmitted) {
21904
+ this.#fecManager?.noteArrival?.("moq-datagram", info.packetId, info.sequenceNumber);
21121
21905
  }
21122
- if (source === "multicast" && !ingressHasPacketId(ingress, info.packetId)) {
21906
+ if (source !== "moq" && !ingressHasPacketId(ingress, info.packetId)) {
21907
+ if (source === "moq-datagram") {
21908
+ if (info.packetId === MMTP_SIGNALING_PACKET_ID) this.#datagramLegSignalingPackets++;
21909
+ else this.#datagramLegIngressDrops++;
21910
+ }
21123
21911
  debugRouter(
21124
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: absent from ingress tracks`
21912
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: absent from ingress tracks`
21125
21913
  );
21126
21914
  return;
21127
21915
  }
21916
+ if (source === "moq-datagram") {
21917
+ if (!info.isRepair) {
21918
+ let names = this.#datagramLegStreams.get(info.packetId);
21919
+ if (!names) this.#datagramLegStreams.set(info.packetId, names = /* @__PURE__ */ new Set());
21920
+ names.add(catalogTrackNameForPacket(ingress, info.packetId));
21921
+ }
21922
+ } else if (source === "multicast") {
21923
+ this.#datagramLegStreams.delete(info.packetId);
21924
+ }
21128
21925
  const packetRole = this.#packetIdRoles.get(info.packetId);
21129
- if (source === "multicast" && this.#classifyPacketId(info.packetId) === null && (!info.isRepair || packetRole !== "repair")) {
21926
+ if (source !== "moq" && this.#classifyPacketId(info.packetId) === null && (!info.isRepair || packetRole !== "repair")) {
21130
21927
  debugRouter(
21131
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: physical PID is unregistered`
21928
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: physical PID is unregistered`
21132
21929
  );
21930
+ if (info.isRepair) this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
21133
21931
  return;
21134
21932
  }
21135
21933
  if (!info.isRepair && hasAmbiguousCatalogTrackName(ingress, info.packetId)) {
@@ -21165,7 +21963,7 @@ var MmtpRouter = class {
21165
21963
  }
21166
21964
  return;
21167
21965
  }
21168
- if (source === "moq" && !manifestAdmitted) {
21966
+ if (source !== "multicast" && !manifestAdmitted) {
21169
21967
  const admit = this.#admitUnicast(info.packetId, packet, () => this.#processMMTP(packet, source, true, ingress, overlapCopy, true), overlapCopy);
21170
21968
  if (admit !== "unlisted") {
21171
21969
  if (admit === "admitted") this.#processMMTP(packet, source, true, ingress, overlapCopy);
@@ -21194,7 +21992,7 @@ var MmtpRouter = class {
21194
21992
  );
21195
21993
  if (!repair) return;
21196
21994
  if (ownerPacketId != null && this.#fecManager) {
21197
- if ((flowless && this.#userAgentGoverns(ownerPacketId) || source === "moq" && !manifestAdmitted) && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)) return;
21995
+ if ((flowless && this.#userAgentGoverns(ownerPacketId) || source !== "multicast" && !manifestAdmitted) && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)) return;
21198
21996
  this.#repairPidCounts[info.packetId] = (this.#repairPidCounts[info.packetId] || 0) + 1;
21199
21997
  const count = this.#repairPidCounts[info.packetId];
21200
21998
  if (count <= 2 || count % 500 === 0) {
@@ -21233,7 +22031,7 @@ var MmtpRouter = class {
21233
22031
  const fecSource = this.#fecManager !== null && fecPayloadId != null;
21234
22032
  const coords = fecSource && fecPayloadId ? this.#locateFecSource(info.packetId, catalogTrackName, fecPayloadId.ssId) ?? void 0 : void 0;
21235
22033
  duplicates.advance(coords?.sbn);
21236
- if (source === "multicast" && !overlapCopy && !releasedFromQuarantine && catalogTrackName !== void 0 && duplicates.predatesHorizon(info.sequenceNumber, fecPayloadId?.ssId)) {
22034
+ if (source !== "moq" && !overlapCopy && !releasedFromQuarantine && catalogTrackName !== void 0 && duplicates.predatesHorizon(info.sequenceNumber, fecPayloadId?.ssId)) {
21237
22035
  this.#publisherRestarts++;
21238
22036
  console.warn(
21239
22037
  `[MmtpRouter] publisher restart on pid=${info.packetId} track=${catalogTrackName}: packet_sequence_number=${info.sequenceNumber} predates the stream's FEC horizon; starting a new epoch`
@@ -21294,6 +22092,7 @@ var MmtpRouter = class {
21294
22092
  evidence: sourceSymbolEvidence(packet, parsed.header, info.rapFlag, info.sequenceNumber),
21295
22093
  oversized: !(this.#fecManager.isoSourceFits?.(info.packetId, rawSymbol.length) ?? false)
21296
22094
  }) ?? false;
22095
+ if (held) this.#requestFecPoke(info.packetId, catalogTrackName);
21297
22096
  parseSourceSymbol = held && !duplicates.parsedSymbols.has(ssId);
21298
22097
  }
21299
22098
  } else if (fecUnreadable && info.fecPayloadId) {
@@ -21421,7 +22220,9 @@ var MmtpRouter = class {
21421
22220
  const feedOptions = {
21422
22221
  skipFecPayloadId: parserOptions?.skipFecPayloadId,
21423
22222
  recovered: parserOptions?.recovered,
21424
- source: parserOptions?.source,
22223
+ // Frame attribution is the transport path: an "mfu-datagram" object
22224
+ // crossed QUIC, so its frames are 'moq' (provenance 'mixed').
22225
+ source: parserOptions?.source === "moq-datagram" ? "moq" : parserOptions?.source,
21425
22226
  deliveryProvenance: parserOptions?.deliveryProvenance,
21426
22227
  catalogTrackName: parserOptions?.catalogTrackName,
21427
22228
  ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
@@ -23336,6 +24137,7 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
23336
24137
  stalls: 0,
23337
24138
  concealedBlocks: 0,
23338
24139
  concealedGaps: 0,
24140
+ undelimitedRunGaps: 0,
23339
24141
  concealedFrames: 0,
23340
24142
  concealedAudioMs: 0,
23341
24143
  vanishedBlocks: 0
@@ -23679,6 +24481,8 @@ var MulticastManager = class {
23679
24481
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
23680
24482
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
23681
24483
  #repairReleases = /* @__PURE__ */ new Map();
24484
+ /** Protected repair flows owned by each live repair-endpoint release. */
24485
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
23682
24486
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
23683
24487
  #overlayBindings = /* @__PURE__ */ new Map();
23684
24488
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -23840,9 +24644,17 @@ var MulticastManager = class {
23840
24644
  reason
23841
24645
  });
23842
24646
  };
24647
+ this.#fec.onUndelimitedRunGap = (packetId, catalogTrackName) => {
24648
+ this.#statsFor(packetId, catalogTrackName).undelimitedRunGaps++;
24649
+ };
23843
24650
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
23844
24651
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
23845
24652
  };
24653
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
24654
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
24655
+ if (binding === void 0) return void 0;
24656
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
24657
+ };
23846
24658
  this.#fec.onDecoderUnavailable = (event) => {
23847
24659
  this.#emitRepairLifecycle({
23848
24660
  version: 2,
@@ -24139,6 +24951,7 @@ var MulticastManager = class {
24139
24951
  assertPositiveGeometry("timescale", config.timescale);
24140
24952
  assertPositiveGeometry("keyframeIntervalTicks", config.keyframeIntervalTicks);
24141
24953
  assertPositiveGeometry("keyframeIntervalMs", config.keyframeIntervalMs);
24954
+ assertPositiveGeometry("groupDurationMs", config.groupDurationMs);
24142
24955
  assertNonNegativeGeometry("fecRepairSymbols", config.fecRepairSymbols);
24143
24956
  assertNonNegativeGeometry(
24144
24957
  "fecReorderToleranceMs",
@@ -24171,7 +24984,8 @@ var MulticastManager = class {
24171
24984
  timeoutMs: deliveryWindowMs,
24172
24985
  ...trackKind === void 0 ? {} : { trackKind },
24173
24986
  ...config.codec === void 0 ? {} : { codec: config.codec },
24174
- ...geometry2 === void 0 ? {} : { geometry: geometry2 }
24987
+ ...geometry2 === void 0 ? {} : { geometry: geometry2 },
24988
+ ...config.groupDurationMs === void 0 ? {} : { groupDurationMs: config.groupDurationMs }
24175
24989
  };
24176
24990
  this.#fec.configureTrack(packetId, fecConfig, catalogTrackName);
24177
24991
  this.#configureTrackMapper(packetId, fecConfig);
@@ -24345,6 +25159,9 @@ var MulticastManager = class {
24345
25159
  this.#transport.onFailback((reason) => {
24346
25160
  const joined = this.#provenanceJoin;
24347
25161
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
25162
+ for (const flows of this.#repairProvenanceFlows.values()) {
25163
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
25164
+ }
24348
25165
  this.#onFailback?.(reason);
24349
25166
  });
24350
25167
  }
@@ -24379,6 +25196,12 @@ var MulticastManager = class {
24379
25196
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
24380
25197
  );
24381
25198
  }
25199
+ if (provenanceFlow !== void 0) {
25200
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
25201
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
25202
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
25203
+ }
25204
+ }
24382
25205
  const staged = this.#renditionSwitch;
24383
25206
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
24384
25207
  this.configureFec(config);
@@ -24386,8 +25209,8 @@ var MulticastManager = class {
24386
25209
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
24387
25210
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
24388
25211
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
24389
- this.#releaseProvenanceJoin();
24390
25212
  const provenance = config.provenance;
25213
+ this.#releaseProvenanceJoin();
24391
25214
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
24392
25215
  const ingress = protectedTracks === void 0 ? void 0 : {
24393
25216
  tracks: Object.freeze(
@@ -24440,8 +25263,13 @@ var MulticastManager = class {
24440
25263
  * feeds the flow's receiver; media datagrams are held until one admits them.
24441
25264
  */
24442
25265
  #joinProvenance(provenance, ingress) {
25266
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
25267
+ this.#hookFailback();
25268
+ this.#provenanceJoin = { flow: ingress.flow };
25269
+ }
25270
+ #provenanceReceiver(provenance) {
24443
25271
  const { flow, auth } = provenance;
24444
- const receiver = new BcProvenanceV2Receiver({
25272
+ return new BcProvenanceV2Receiver({
24445
25273
  ...provenance.receiver,
24446
25274
  // The caller's ctx when it passes one, else the catalog's: an explicit
24447
25275
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -24458,9 +25286,6 @@ var MulticastManager = class {
24458
25286
  maxAuthDelayMs: flow.maxAuthDelayMs,
24459
25287
  manifestTimerMs: flow.manifestTimerMs
24460
25288
  });
24461
- this.#router.registerProvenanceFlow(ingress, receiver);
24462
- this.#hookFailback();
24463
- this.#provenanceJoin = { flow: ingress.flow };
24464
25289
  }
24465
25290
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
24466
25291
  #releaseProvenanceJoin() {
@@ -24491,8 +25316,25 @@ var MulticastManager = class {
24491
25316
  * callback delivers must come from a subscription opened on
24492
25317
  * `options.gateway`. A callback that also merges another source (a MoQ or
24493
25318
  * WebSocket repair feed) must not name a native provider here.
25319
+ *
25320
+ * An endpoint's `provenance` makes its group a protected flow of its own
25321
+ * (multicast-02 7.2.7), registered here and released with the group; its
25322
+ * records ride in band on the group's port. On the user-agent path a
25323
+ * flow-less repair group of a protected track is set aside, never read, so
25324
+ * a player joining a protected catalog's repair groups passes it.
24494
25325
  */
24495
25326
  joinRepairEndpoints(endpoints, provider, options) {
25327
+ for (const { provenance, flow, source, group, port } of endpoints) {
25328
+ if (provenance === void 0) continue;
25329
+ if (flow !== void 0) {
25330
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
25331
+ }
25332
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port !== provenance.flow.port) {
25333
+ throw new RangeError(
25334
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
25335
+ );
25336
+ }
25337
+ }
24496
25338
  const releases = [];
24497
25339
  let released = false;
24498
25340
  const safely = (each) => {
@@ -24502,17 +25344,36 @@ var MulticastManager = class {
24502
25344
  console.warn("[MulticastManager] repair group release failed", error);
24503
25345
  }
24504
25346
  };
25347
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
25348
+ const preparedProvenance = endpoints.map((endpoint) => {
25349
+ if (endpoint.provenance === void 0) return void 0;
25350
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
25351
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
25352
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
25353
+ }
25354
+ usedFlows.add(flow);
25355
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
25356
+ });
25357
+ const provenanceFlows = [];
24505
25358
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
24506
25359
  ...owner,
24507
25360
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
24508
25361
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
24509
25362
  }));
24510
25363
  this.#applyRepairOwners(repairOwners);
24511
- for (const endpoint of endpoints) {
25364
+ for (const [index, endpoint] of endpoints.entries()) {
25365
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
24512
25366
  const ingress = {
24513
25367
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
24514
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
25368
+ ...flow === void 0 ? {} : { flow }
24515
25369
  };
25370
+ if (endpoint.provenance !== void 0) {
25371
+ const prepared = preparedProvenance[index];
25372
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
25373
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
25374
+ provenanceFlows.push(prepared.flow);
25375
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
25376
+ }
24516
25377
  let sender;
24517
25378
  const feed = (packet, sourceAddress, ingressToFeed) => {
24518
25379
  if (released) return;
@@ -24542,7 +25403,7 @@ var MulticastManager = class {
24542
25403
  packetIds: endpoint.packetIds,
24543
25404
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
24544
25405
  // A protected repair group's records ride in band on its port (7.2.3).
24545
- ...endpoint.flow === void 0 ? {} : { protected: true }
25406
+ ...flow === void 0 ? {} : { protected: true }
24546
25407
  }, ingress).then((joined) => {
24547
25408
  if (!joined && !released) fail(transport.lastJoinOutcome);
24548
25409
  });
@@ -24551,9 +25412,12 @@ var MulticastManager = class {
24551
25412
  if (released) return;
24552
25413
  released = true;
24553
25414
  this.#repairReleases.delete(release);
25415
+ this.#repairProvenanceFlows.delete(release);
24554
25416
  for (const each of releases.splice(0)) safely(each);
24555
25417
  };
24556
25418
  this.#repairReleases.set(release, repairOwners);
25419
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
25420
+ if (provenanceFlows.length) this.#hookFailback();
24557
25421
  return release;
24558
25422
  }
24559
25423
  #applyRepairOwners(owners) {
@@ -24822,6 +25686,70 @@ var MulticastManager = class {
24822
25686
  feedPacket(data, ingress, sourceAddress) {
24823
25687
  this.#transport.feedPacket(data, ingress, sourceAddress);
24824
25688
  }
25689
+ /**
25690
+ * Start an "mfu-datagram" leg (draft-ramadan-moq-mmt-02 4.3.1): a
25691
+ * subscription whose objects arrive as datagrams, a lossy unicast path.
25692
+ * Arms the join-boundary rules exactly as a multicast join does (the leg
25693
+ * starts at an arbitrary datagram), keeping configured tracks, decoders
25694
+ * and diagnostics. No MulticastTransport is involved: no takeover, no
25695
+ * failback watchdog, no bridge. While the leg is up the player publishes
25696
+ * `datagramLegDiagnostics(...)` in its FEC stats (`DatagramLegDiagnostics`:
25697
+ * `datagramLegJoined`, `datagramLegIngressDrops`,
25698
+ * `datagramLegRepairBeforePacketId`, `datagramUnknownAlias`,
25699
+ * `transport.maxDatagramSize`), the same keys in every player.
25700
+ */
25701
+ startDatagramLeg(options = {}) {
25702
+ this.#router.setDatagramLegPresentationBudget(options.presentationBudgetMs ?? null);
25703
+ this.#fec.beginLegJoin();
25704
+ }
25705
+ /**
25706
+ * Feed one object of an "mfu-datagram" subscription (one MMTP packet) in
25707
+ * arrival order. `ingress.tracks` names the datagram catalog track for the
25708
+ * packet id; the router restores serial order, holds FEC sources until a
25709
+ * repair states their block, and declares loss at the block deadline
25710
+ * (mmt-02 5.3.3). Bypasses MulticastTransport, unlike `feedPacket`.
25711
+ */
25712
+ feedDatagramLegPacket(packet, ingress) {
25713
+ this.#router.feedPacket(packet, "moq-datagram", ingress);
25714
+ }
25715
+ /**
25716
+ * Feed one repair object of an "mfu-datagram" track's repair track (sent
25717
+ * as datagrams, mmt-02 4.3.1): the repair track's own packet id names no
25718
+ * owner, so the subscription supplies it, as `router.feedRepairPacket`
25719
+ * does for a MoQ repair; the symbol counts as in-band (`RepairVia`
25720
+ * `inband`), unlike a FETCHed repair.
25721
+ */
25722
+ feedDatagramLegRepair(packet, ownerPacketId, catalogTrackName, repairTrackName) {
25723
+ this.#router.feedRepairPacket(packet, ownerPacketId, catalogTrackName, repairTrackName, "moq-datagram");
25724
+ }
25725
+ /**
25726
+ * End the "mfu-datagram" leg: call it when the subscription is dropped and
25727
+ * before the first packet of the path that replaces it (the ordered switch
25728
+ * to multicast, a fallback to the "mfu" track). The leg's presentation
25729
+ * bound and ledger retention stop applying; tracks, decoders, FEC state
25730
+ * and diagnostics stay, so the next path continues without a new epoch.
25731
+ */
25732
+ stopDatagramLeg() {
25733
+ this.#router.endDatagramLeg();
25734
+ }
25735
+ /** "mfu-datagram" leg packets dropped because their packet id is not the leg's (`MmtpRouter.datagramLegIngressDropCount`). */
25736
+ get datagramLegIngressDropCount() {
25737
+ return this.#router.datagramLegIngressDropCount;
25738
+ }
25739
+ /**
25740
+ * The leg's diagnostics as one object with the shared names
25741
+ * (`DatagramLegDiagnostics`): the player supplies what it alone counts and
25742
+ * spreads the result into its published FEC stats while a leg is up.
25743
+ */
25744
+ datagramLegDiagnostics(player) {
25745
+ return {
25746
+ datagramLegJoined: player.joined,
25747
+ datagramLegIngressDrops: this.#router.datagramLegIngressDropCount,
25748
+ datagramLegRepairBeforePacketId: player.repairBeforePacketId,
25749
+ datagramUnknownAlias: player.unknownAlias,
25750
+ transport: { maxDatagramSize: player.maxDatagramSize ?? null }
25751
+ };
25752
+ }
24825
25753
  /**
24826
25754
  * Declare how packets given to feedPacket() reach this manager. A consumer
24827
25755
  * that owns the multicast socket itself declares its own leg; join()
@@ -25039,7 +25967,8 @@ var MulticastManager = class {
25039
25967
  blockProfile: parseFecBlockProfile(
25040
25968
  geometry2.blockProfile,
25041
25969
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
25042
- )
25970
+ ),
25971
+ geometry: geometry2
25043
25972
  });
25044
25973
  }
25045
25974
  }
@@ -25078,7 +26007,7 @@ var MulticastManager = class {
25078
26007
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
25079
26008
  const before = this.#overlayBindings.get(sourcePacketId);
25080
26009
  const after = overlayBindings.get(sourcePacketId);
25081
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
26010
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
25082
26011
  if (!same) install.dispose();
25083
26012
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
25084
26013
  else install.reattach();