@blockcast/mmt-container 2.2.0-main.cc080e5a56f2 → 2.2.0-main.cc3fe0684403

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 (137) 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 +1485 -172
  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/datagram-leg-deadline.d.ts +118 -0
  24. package/dist/datagram-leg-deadline.d.ts.map +1 -0
  25. package/dist/datagram-leg-deadline.js +217 -0
  26. package/dist/datagram-leg-deadline.js.map +7 -0
  27. package/dist/delivery-catalog.js +68 -0
  28. package/dist/delivery-catalog.js.map +4 -4
  29. package/dist/delta-fallback-config.js +39 -1
  30. package/dist/delta-fallback-config.js.map +4 -4
  31. package/dist/fec-manager.d.ts +155 -10
  32. package/dist/fec-manager.d.ts.map +1 -1
  33. package/dist/fec-manager.js +596 -81
  34. package/dist/fec-manager.js.map +4 -4
  35. package/dist/fec-state.d.ts +17 -5
  36. package/dist/fec-state.d.ts.map +1 -1
  37. package/dist/fec-state.js +41 -1
  38. package/dist/fec-state.js.map +3 -3
  39. package/dist/fec-worker-setup.js +34 -0
  40. package/dist/fec-worker-setup.js.map +3 -3
  41. package/dist/held-layer-admission.js +34 -0
  42. package/dist/held-layer-admission.js.map +3 -3
  43. package/dist/index.d.ts +7 -5
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +15 -1
  46. package/dist/index.js.map +2 -2
  47. package/dist/iso-block-locator.d.ts +16 -0
  48. package/dist/iso-block-locator.d.ts.map +1 -1
  49. package/dist/iso-block-locator.js +62 -0
  50. package/dist/iso-block-locator.js.map +3 -3
  51. package/dist/mfu-reassembler.js +34 -0
  52. package/dist/mfu-reassembler.js.map +3 -3
  53. package/dist/mmtp-container-parser.d.ts +30 -2
  54. package/dist/mmtp-container-parser.d.ts.map +1 -1
  55. package/dist/mmtp-container-parser.js +140 -2
  56. package/dist/mmtp-container-parser.js.map +3 -3
  57. package/dist/mmtp-container-parser.no-modules.js +293 -18
  58. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  59. package/dist/mmtp-decode-pipeline.js +140 -2
  60. package/dist/mmtp-decode-pipeline.js.map +3 -3
  61. package/dist/mmtp-fec-session.js +34 -0
  62. package/dist/mmtp-fec-session.js.map +3 -3
  63. package/dist/mmtp-mode-selection.d.ts +48 -0
  64. package/dist/mmtp-mode-selection.d.ts.map +1 -0
  65. package/dist/mmtp-mode-selection.js +79 -0
  66. package/dist/mmtp-mode-selection.js.map +7 -0
  67. package/dist/mmtp-router.d.ts +66 -8
  68. package/dist/mmtp-router.d.ts.map +1 -1
  69. package/dist/mmtp-router.js +348 -27
  70. package/dist/mmtp-router.js.map +4 -4
  71. package/dist/multicast-auth-catalog.js +42 -2
  72. package/dist/multicast-auth-catalog.js.map +3 -3
  73. package/dist/multicast-input.js +42 -2
  74. package/dist/multicast-input.js.map +3 -3
  75. package/dist/multicast-manager.d.ts +108 -1
  76. package/dist/multicast-manager.d.ts.map +1 -1
  77. package/dist/multicast-manager.js +1067 -138
  78. package/dist/multicast-manager.js.map +4 -4
  79. package/dist/multicast-transport.js +68 -0
  80. package/dist/multicast-transport.js.map +4 -4
  81. package/dist/multicast-unwrap.js +34 -0
  82. package/dist/multicast-unwrap.js.map +3 -3
  83. package/dist/no-modules.d.ts +1 -0
  84. package/dist/no-modules.d.ts.map +1 -1
  85. package/dist/no-modules.js +295 -19
  86. package/dist/no-modules.js.map +4 -4
  87. package/dist/phase14-catalog-override.d.ts +2 -1
  88. package/dist/phase14-catalog-override.d.ts.map +1 -1
  89. package/dist/phase14-catalog-override.js +69 -2
  90. package/dist/phase14-catalog-override.js.map +3 -3
  91. package/dist/repair-fetch.d.ts.map +1 -1
  92. package/dist/repair-fetch.js +50 -0
  93. package/dist/repair-fetch.js.map +3 -3
  94. package/dist/repair-layer-subscriptions.js +34 -0
  95. package/dist/repair-layer-subscriptions.js.map +3 -3
  96. package/dist/signaling.js +34 -0
  97. package/dist/signaling.js.map +3 -3
  98. package/dist/timestamp-codec.js +34 -0
  99. package/dist/timestamp-codec.js.map +3 -3
  100. package/dist/wasm-mfu-reassembler.js +34 -0
  101. package/dist/wasm-mfu-reassembler.js.map +3 -3
  102. package/dist/wasm-mmtp-container-parser.js +140 -2
  103. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  104. package/package.json +5 -5
  105. package/schemas/catalog.schema.json +2 -2
  106. package/src/block-policy.ts +324 -83
  107. package/src/carp-catalog.ts +165 -5
  108. package/src/catalog-fec-params.ts +1 -0
  109. package/src/codec-utils.ts +121 -1
  110. package/src/datagram-leg-deadline.ts +342 -0
  111. package/src/fec-manager.ts +534 -41
  112. package/src/fec-state.ts +21 -5
  113. package/src/index.ts +38 -0
  114. package/src/iso-block-locator.ts +34 -0
  115. package/src/mmtp-container-parser.ts +57 -11
  116. package/src/mmtp-mode-selection.ts +80 -0
  117. package/src/mmtp-router.ts +287 -42
  118. package/src/multicast-manager.ts +218 -10
  119. package/src/no-modules.ts +3 -0
  120. package/src/phase14-catalog-override.ts +14 -3
  121. package/src/repair-fetch.ts +23 -0
  122. package/test-vectors/catalog/README.md +36 -2
  123. package/test-vectors/catalog/mmtp-siblings/ambiguous-sibling.json +158 -0
  124. package/test-vectors/catalog/mmtp-siblings/ladder-bitrate-only.json +231 -0
  125. package/test-vectors/catalog/mmtp-siblings/ladder-four-rungs.json +405 -0
  126. package/test-vectors/catalog/mmtp-siblings/ladder-other-names.json +231 -0
  127. package/test-vectors/catalog/mmtp-siblings/mmtp-mode-unknown.json +143 -0
  128. package/test-vectors/catalog/mmtp-siblings/multicast-endpoint-lists-datagram-track.json +143 -0
  129. package/test-vectors/catalog/mmtp-siblings/no-sibling.json +79 -0
  130. package/test-vectors/catalog/mmtp-siblings/rendition-mismatch.json +143 -0
  131. package/test-vectors/catalog/mmtp-siblings/stream-delivery-mode.json +143 -0
  132. package/test-vectors/catalog/mmtp-siblings/timescale-mismatch.json +143 -0
  133. package/test-vectors/catalog/mmtp-siblings/valid-pair.json +142 -0
  134. package/test-vectors/catalog/section-codes.json +3 -3
  135. package/test-vectors/catalog-timing.json +559 -1
  136. package/test-vectors/catalog-validation.json +266 -7
  137. package/test-vectors/moq/mmtp-mode-selection.json +259 -0
@@ -852,14 +852,14 @@ function readRepairFecPayloadIdFields(mmtpPacket, parsedHeader) {
852
852
  };
853
853
  }
854
854
  function extractRepairFecPayloadId(mmtpPacket) {
855
- const fields = readRepairFecPayloadIdFields(mmtpPacket);
856
- if (!fields)
855
+ const fields2 = readRepairFecPayloadIdFields(mmtpPacket);
856
+ if (!fields2)
857
857
  return null;
858
858
  return {
859
- ssStart: fields.ssStart,
860
- rsbLength: fields.rsbLength,
861
- rsId: fields.rsId,
862
- ssbLength: fields.ssbLength
859
+ ssStart: fields2.ssStart,
860
+ rsbLength: fields2.rsbLength,
861
+ rsId: fields2.rsId,
862
+ ssbLength: fields2.ssbLength
863
863
  };
864
864
  }
865
865
  function parseMoqRepairFrame(frame) {
@@ -1028,11 +1028,11 @@ function isoBlocksBehindLowerBound(a, b, kMax) {
1028
1028
  var DEC_OCTET = /^(?:0|[1-9]\d{0,2})$/;
1029
1029
  var H16 = /^[0-9A-Fa-f]{1,4}$/;
1030
1030
  function parseIpv4(text2) {
1031
- const fields = text2.split(".");
1032
- if (fields.length !== 4)
1031
+ const fields2 = text2.split(".");
1032
+ if (fields2.length !== 4)
1033
1033
  return void 0;
1034
1034
  const octets = [];
1035
- for (const field of fields) {
1035
+ for (const field of fields2) {
1036
1036
  if (!DEC_OCTET.test(field))
1037
1037
  return void 0;
1038
1038
  const value = Number(field);
@@ -1266,9 +1266,12 @@ function multicastCatalogIssues(catalog, options = {}) {
1266
1266
  return issues;
1267
1267
  const tracks = Array.isArray(catalog["tracks"]) ? catalog["tracks"] : [];
1268
1268
  const namespaceOf = /* @__PURE__ */ new Map();
1269
+ const modeOf = /* @__PURE__ */ new Map();
1269
1270
  for (const track of tracks) {
1270
- if (isObject(track) && typeof track["name"] === "string")
1271
- namespaceOf.set(track["name"], track["namespace"]);
1271
+ if (!isObject(track) || typeof track["name"] !== "string")
1272
+ continue;
1273
+ namespaceOf.set(track["name"], track["namespace"]);
1274
+ modeOf.set(track["name"], track["mmtpMode"]);
1272
1275
  }
1273
1276
  const tagged = catalog[CATALOG_NAMESPACE];
1274
1277
  let referenceNamespace = options.catalogNamespace ?? (typeof tagged === "string" ? tagged : void 0);
@@ -1338,6 +1341,9 @@ function multicastCatalogIssues(catalog, options = {}) {
1338
1341
  const name = isObject(ref) ? ref["name"] : ref;
1339
1342
  if (typeof name !== "string")
1340
1343
  continue;
1344
+ if (modeOf.get(name) === "mfu-datagram") {
1345
+ fail("multicast_track", `${at2}.tracks[${refIndex}].name`, `track ${JSON.stringify(name)} is an "mfu-datagram" track, which rides no multicast endpoint; list its "mfu" sibling (draft-ramadan-moq-mmt-02 4.3.1)`);
1346
+ }
1341
1347
  const namespace = namespaceOf.get(name);
1342
1348
  if (typeof namespace !== "string")
1343
1349
  continue;
@@ -1797,13 +1803,25 @@ function fecCatalogTracks(catalog) {
1797
1803
  });
1798
1804
  return { tracks, pointers };
1799
1805
  }
1800
- function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1806
+ function runtimeView(catalog, receiver) {
1801
1807
  const { tracks, pointers } = fecCatalogTracks(catalog);
1802
1808
  const report = validateFecCatalog({ tracks }, receiver);
1803
1809
  const at2 = (path) => {
1804
1810
  const m = /^\/tracks\/(\d+)(.*)$/.exec(path);
1805
1811
  return m ? pointers[Number(m[1])] + m[2] : path;
1806
1812
  };
1813
+ return { tracks, pointers, report, at: at2 };
1814
+ }
1815
+ function runtimeFecCatalogReport(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1816
+ const { report, at: at2 } = runtimeView(catalog, receiver);
1817
+ const issue = (i) => Object.freeze({ code: i.code, path: at2(i.path) });
1818
+ return Object.freeze({
1819
+ instances: Object.freeze(report.instances.map((i) => Object.freeze({ ...i, path: at2(i.path), issues: Object.freeze(i.issues.map(issue)) }))),
1820
+ issues: Object.freeze(report.issues.map(issue))
1821
+ });
1822
+ }
1823
+ function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1824
+ const { tracks, pointers, report, at: at2 } = runtimeView(catalog, receiver);
1807
1825
  const trackAt = (i) => recordOf(tracks[i]) ?? {};
1808
1826
  const nameAt = (i) => i === null ? void 0 : trackAt(i)["name"];
1809
1827
  const why = (i) => Object.freeze({
@@ -1901,6 +1919,70 @@ function geometry(o, instanceId, symbolTrack) {
1901
1919
  });
1902
1920
  }
1903
1921
 
1922
+ // ../mmt-base/dist/mmtp-siblings.js
1923
+ var MMTP_MODES = Object.freeze(["mfu", "mfu-datagram"]);
1924
+ function isMmtpMode(value) {
1925
+ return typeof value === "string" && MMTP_MODES.includes(value);
1926
+ }
1927
+ var MMTP_SIBLING_HARD_FIELDS = Object.freeze([
1928
+ "namespace",
1929
+ "timescale",
1930
+ "presentationAnchorTicks",
1931
+ "groupDuration"
1932
+ ]);
1933
+ var MMTP_SIBLING_RENDITION_FIELDS = Object.freeze([
1934
+ "codec",
1935
+ "width",
1936
+ "height",
1937
+ "framerate",
1938
+ "bitrate",
1939
+ "samplerate",
1940
+ "channelConfig",
1941
+ "lang"
1942
+ ]);
1943
+ var MMTP_SIBLING_SOFT_FIELDS = Object.freeze([
1944
+ "initRef",
1945
+ "keyframeIntervalMs",
1946
+ "keyframeIntervalTicks",
1947
+ "isLive",
1948
+ "altGroup"
1949
+ ]);
1950
+ function fields(track) {
1951
+ return track;
1952
+ }
1953
+ function groupDurationTicks(track) {
1954
+ const ticks = track["groupDurationTicks"];
1955
+ if (Number.isSafeInteger(ticks))
1956
+ return BigInt(ticks);
1957
+ const ms = track["groupDurationMs"];
1958
+ const timescale = track["timescale"];
1959
+ if (!Number.isSafeInteger(ms) || !Number.isSafeInteger(timescale))
1960
+ return void 0;
1961
+ return BigInt(ms) * BigInt(timescale) / 1000n;
1962
+ }
1963
+ function identityEqual(a, b) {
1964
+ return a["namespace"] === b["namespace"] && a["timescale"] === b["timescale"] && a["presentationAnchorTicks"] === b["presentationAnchorTicks"] && groupDurationTicks(a) === groupDurationTicks(b) && MMTP_SIBLING_RENDITION_FIELDS.every((field) => a[field] === b[field]);
1965
+ }
1966
+ function isMmtpTrack(track, mode) {
1967
+ return typeof track === "object" && track !== null && !Array.isArray(track) && fields(track)["packaging"] === "mmtp" && fields(track)["mmtpMode"] === mode;
1968
+ }
1969
+ function mmtpSiblingCandidates(tracks, datagram) {
1970
+ const own = fields(datagram);
1971
+ return tracks.filter((track) => isMmtpTrack(track, "mfu") && identityEqual(fields(track), own));
1972
+ }
1973
+
1974
+ // ../mmt-base/dist/datagram-leg-size.js
1975
+ var DATAGRAM_LEG_UDP_FLOOR = 1200;
1976
+ var DATAGRAM_LEG_QUIC_WT_FRAMING = 48;
1977
+ var DATAGRAM_LEG_OBJECT_HEADER = 13;
1978
+ var DATAGRAM_LEG_RELAY_ROOM = 16;
1979
+ var DATAGRAM_LEG_REPAIR_OVERHEAD = 25;
1980
+ var DATAGRAM_LEG_DATAGRAM_MAX = DATAGRAM_LEG_UDP_FLOOR - DATAGRAM_LEG_QUIC_WT_FRAMING;
1981
+ var DATAGRAM_LEG_BODY_MAX = DATAGRAM_LEG_DATAGRAM_MAX - DATAGRAM_LEG_OBJECT_HEADER - DATAGRAM_LEG_RELAY_ROOM;
1982
+ function datagramLegObjectMax(symbolSize) {
1983
+ return DATAGRAM_LEG_OBJECT_HEADER + DATAGRAM_LEG_REPAIR_OVERHEAD + symbolSize;
1984
+ }
1985
+
1904
1986
  // src/mfu-reassembler.ts
1905
1987
  function fragmentProvenance(fragment) {
1906
1988
  if (fragment.deliveryProvenance !== void 0) return fragment.deliveryProvenance;
@@ -6099,9 +6181,10 @@ function isH264IntraSlice(nal) {
6099
6181
  const sliceType = readH264SliceType(nal);
6100
6182
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
6101
6183
  }
6184
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
6102
6185
  function readH264SliceType(nal) {
6103
6186
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6104
- const rbsp = removeEmulationPrevention(nal.subarray(1));
6187
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
6105
6188
  const state = { bitOffset: 0 };
6106
6189
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6107
6190
  return readUnsignedExpGolomb(rbsp, state);
@@ -6470,6 +6553,96 @@ if (void 0) {
6470
6553
  ]))).toBe(false);
6471
6554
  });
6472
6555
  });
6556
+ describe("readH264SliceType", () => {
6557
+ const wholeNalSliceType = (nal) => {
6558
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6559
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
6560
+ const state = { bitOffset: 0 };
6561
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6562
+ return readUnsignedExpGolomb(rbsp, state);
6563
+ };
6564
+ const hex3 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
6565
+ const ue = (value) => {
6566
+ const code = (value + 1).toString(2);
6567
+ return "0".repeat(code.length - 1) + code;
6568
+ };
6569
+ const sliceNal = (bits) => {
6570
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
6571
+ const nal = [1];
6572
+ let zeros = 0;
6573
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
6574
+ if (zeros >= 2 && byte <= 3) {
6575
+ nal.push(3);
6576
+ zeros = 0;
6577
+ }
6578
+ nal.push(byte);
6579
+ zeros = byte === 0 ? zeros + 1 : 0;
6580
+ }
6581
+ return Uint8Array.from(nal);
6582
+ };
6583
+ const x264Slices = [
6584
+ ["64x48 P", hex3("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
6585
+ ["64x48 B", hex3("419e414212fffeeade283707cb70f7"), 6, false],
6586
+ ["64x48 non-IDR I", hex3(
6587
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
6588
+ ), 7, true],
6589
+ ["1280x720 B, escape at byte 10", hex3(
6590
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
6591
+ ), 6, false],
6592
+ ["1280x720 P, escape at byte 15", hex3(
6593
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
6594
+ ), 5, false],
6595
+ ["1280x720 B, escape at byte 22", hex3("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
6596
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex3(
6597
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
6598
+ ), null, true],
6599
+ ["7680x4320 P, first_mb_in_slice 32640", hex3(
6600
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
6601
+ ), 5, false],
6602
+ ["7680x4320 P, first_mb_in_slice 97440", hex3(
6603
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
6604
+ ), 5, false]
6605
+ ];
6606
+ const syntheticSlices = [
6607
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
6608
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
6609
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
6610
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
6611
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
6612
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
6613
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
6614
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
6615
+ ];
6616
+ test("reads the slice_type of real and synthetic slices", () => {
6617
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
6618
+ expect(readH264SliceType(nal), name).toBe(sliceType);
6619
+ }
6620
+ });
6621
+ test("matches the whole-NAL unescape at every truncation", () => {
6622
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
6623
+ for (let end = 0; end <= nal.length; end++) {
6624
+ const cut = nal.subarray(0, end);
6625
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
6626
+ }
6627
+ }
6628
+ });
6629
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
6630
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
6631
+ let seed = 1;
6632
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
6633
+ for (let i = 0; i < 5e3; i++) {
6634
+ const nal = new Uint8Array(2 + next() % 63);
6635
+ nal[0] = 65;
6636
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
6637
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
6638
+ }
6639
+ });
6640
+ test("classifies the x264 slices as keyframes or not", () => {
6641
+ for (const [name, nal, , keyframe] of x264Slices) {
6642
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
6643
+ }
6644
+ });
6645
+ });
6473
6646
  describe("avccToAnnexB", () => {
6474
6647
  test("converts with SPS/PPS on keyframe", () => {
6475
6648
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -7138,13 +7311,13 @@ function validateCmsfMmtpCatalog(value, _options = {}) {
7138
7311
  }
7139
7312
  const timescale = track["timescale"];
7140
7313
  const groupDurationMs = track["groupDurationMs"];
7141
- const groupDurationTicks = track["groupDurationTicks"];
7314
+ const groupDurationTicks2 = track["groupDurationTicks"];
7142
7315
  const keyframeIntervalMs = track["keyframeIntervalMs"];
7143
7316
  const keyframeIntervalTicks = track["keyframeIntervalTicks"];
7144
7317
  if (groupDurationMs !== void 0 && !positiveInteger2(groupDurationMs)) {
7145
7318
  catalogError("track_group_duration_ms", `${path}.groupDurationMs`, "must be a positive integer");
7146
7319
  }
7147
- if (groupDurationTicks !== void 0 && !positiveInteger2(groupDurationTicks)) {
7320
+ if (groupDurationTicks2 !== void 0 && !positiveInteger2(groupDurationTicks2)) {
7148
7321
  catalogError("track_group_duration_ticks", `${path}.groupDurationTicks`, "must be a positive integer");
7149
7322
  }
7150
7323
  if (keyframeIntervalMs !== void 0 && !positiveNumber2(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger2(keyframeIntervalTicks)) {
@@ -7159,20 +7332,17 @@ function validateCmsfMmtpCatalog(value, _options = {}) {
7159
7332
  catalogError("track_init_ref", `${path}.initRef`, "must be a non-empty string");
7160
7333
  }
7161
7334
  if (packaging === "mmtp") {
7162
- if (track["mmtpMode"] !== "mfu") {
7163
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
7164
- }
7165
7335
  if (!positiveInteger2(timescale)) {
7166
7336
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
7167
7337
  }
7168
- if (groupDurationMs === void 0 && groupDurationTicks === void 0) {
7338
+ if (groupDurationMs === void 0 && groupDurationTicks2 === void 0) {
7169
7339
  catalogError(
7170
7340
  "track_group_duration_ms",
7171
7341
  path,
7172
7342
  "groupDurationMs or groupDurationTicks must be a positive integer"
7173
7343
  );
7174
7344
  }
7175
- if (groupDurationTicks === void 0 && BigInt(groupDurationMs) * BigInt(timescale) % 1000n !== 0n) {
7345
+ if (groupDurationTicks2 === void 0 && BigInt(groupDurationMs) * BigInt(timescale) % 1000n !== 0n) {
7176
7346
  catalogError("track_group_duration_exact", `${path}.groupDurationMs`, "does not resolve to an exact integer tick count");
7177
7347
  }
7178
7348
  }
@@ -7254,8 +7424,103 @@ function validateCmsfMmtpCatalog(value, _options = {}) {
7254
7424
  }
7255
7425
  }
7256
7426
  validateArchive(catalog);
7427
+ dropRejectedMmtpTracks(catalog);
7257
7428
  return catalog;
7258
7429
  }
7430
+ function dropRejectedMmtpTracks(catalog) {
7431
+ const rejected = mmtpTrackIssues(catalog);
7432
+ if (rejected.length === 0) return;
7433
+ const tracks = catalog["tracks"];
7434
+ const rejectedIndexes = new Set(rejected.map((issue) => issue.index));
7435
+ const nameOf = (track) => track?.["name"];
7436
+ const mediaNames = new Set(tracks.filter((_, index) => !rejectedIndexes.has(index)).map(nameOf));
7437
+ const kept = tracks.filter((track, index) => {
7438
+ if (rejectedIndexes.has(index)) return false;
7439
+ const t = track;
7440
+ return !(t?.["packaging"] === "fec-repair" && typeof t["source"] === "string" && !mediaNames.has(t["source"]) && rejected.some((issue) => issue.name === t["source"]));
7441
+ });
7442
+ catalog["tracks"] = kept;
7443
+ const keptNames = new Set(kept.map(nameOf));
7444
+ const endpoints = catalog["multicast"]?.["endpoints"];
7445
+ if (Array.isArray(endpoints)) {
7446
+ for (const endpoint of endpoints) {
7447
+ const refs = endpoint?.["tracks"];
7448
+ if (!endpoint || !Array.isArray(refs)) continue;
7449
+ endpoint["tracks"] = refs.filter((ref) => keptNames.has(typeof ref === "object" ? nameOf(ref) : ref));
7450
+ }
7451
+ }
7452
+ Object.defineProperty(catalog, "rejectedTracks", { value: rejected, enumerable: false, configurable: true, writable: true });
7453
+ }
7454
+ function mmtpTrackIssues(catalog) {
7455
+ if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) return [];
7456
+ const tracks = catalog["tracks"];
7457
+ if (!Array.isArray(tracks)) return [];
7458
+ const records = tracks.filter(
7459
+ (track) => typeof track === "object" && track !== null && !Array.isArray(track)
7460
+ );
7461
+ const issues = [];
7462
+ const streamPaths = (track) => {
7463
+ const name = typeof track["name"] === "string" ? track["name"] : "";
7464
+ return [track, ...records.filter((repair) => repair["packaging"] === "fec-repair" && repair["source"] === name)].filter((declaring) => declaring["deliveryMode"] === "stream").map((declaring) => `$.tracks[${tracks.indexOf(declaring)}]`);
7465
+ };
7466
+ const candidatesOf = /* @__PURE__ */ new Map();
7467
+ const mirrorsOf = /* @__PURE__ */ new Map();
7468
+ for (const track of records) {
7469
+ if (track["packaging"] !== "mmtp" || track["mmtpMode"] !== "mfu-datagram") continue;
7470
+ const candidates = mmtpSiblingCandidates(records, track);
7471
+ candidatesOf.set(track, candidates);
7472
+ if (candidates.length === 1 && streamPaths(track).length === 0) {
7473
+ mirrorsOf.set(candidates[0], [...mirrorsOf.get(candidates[0]) ?? [], track]);
7474
+ }
7475
+ }
7476
+ for (const track of records) {
7477
+ const index = tracks.indexOf(track);
7478
+ const path = `$.tracks[${index}]`;
7479
+ const name = typeof track["name"] === "string" ? track["name"] : "";
7480
+ if (track["packaging"] !== "mmtp") continue;
7481
+ const mode = track["mmtpMode"];
7482
+ if (!isMmtpMode(mode)) {
7483
+ issues.push({
7484
+ code: "track_mmtp_mode",
7485
+ path: `${path}.mmtpMode`,
7486
+ message: `mmtpMode must be "mfu" or "mfu-datagram", got ${JSON.stringify(mode)}; a subscriber rejects the track (draft-ramadan-moq-mmt-02 13.1)`,
7487
+ name,
7488
+ index
7489
+ });
7490
+ continue;
7491
+ }
7492
+ if (mode !== "mfu-datagram") continue;
7493
+ const conflict = (at2) => issues.push({
7494
+ code: "track_delivery_mode_conflict",
7495
+ path: `${at2}.deliveryMode`,
7496
+ message: `"mfu-datagram" track ${JSON.stringify(name)} and its repair tracks are sent as datagrams; deliveryMode "stream" would subscribe no repair (draft-ramadan-moq-mmt-02 4.3.1)`,
7497
+ name,
7498
+ index
7499
+ });
7500
+ const streams = streamPaths(track);
7501
+ for (const at2 of streams) conflict(at2);
7502
+ const candidates = candidatesOf.get(track) ?? [];
7503
+ const rivals = candidates.length === 1 && streams.length === 0 ? (mirrorsOf.get(candidates[0]) ?? []).filter((other) => other !== track) : [];
7504
+ if (rivals.length > 0) {
7505
+ issues.push({
7506
+ code: "track_mmtp_sibling",
7507
+ path,
7508
+ message: `"mfu-datagram" track ${JSON.stringify(name)} mirrors "mfu" track ${JSON.stringify(candidates[0]["name"])}, and so ${rivals.length === 1 ? "does" : "do"} ${rivals.map((rival) => JSON.stringify(rival["name"])).join(", ")}; the catalog does not say which one mirrors it, so a subscriber pairs none (draft-ramadan-moq-mmt-02 4.3.1)`,
7509
+ name,
7510
+ index
7511
+ });
7512
+ } else if (candidates.length !== 1) {
7513
+ issues.push({
7514
+ code: "track_mmtp_sibling",
7515
+ path,
7516
+ message: candidates.length === 0 ? `"mfu-datagram" track ${JSON.stringify(name)} mirrors no "mfu" track of its namespace with the same timescale, presentationAnchorTicks, group duration and rendition fields (${MMTP_SIBLING_RENDITION_FIELDS.join(", ")}), each equal or absent on both (draft-ramadan-moq-mmt-02 4.3.1, 13.1)` : `"mfu-datagram" track ${JSON.stringify(name)} could mirror ${candidates.length} "mfu" tracks (${candidates.map((c) => JSON.stringify(c["name"])).join(", ")}) that carry one description; the pair is ambiguous`,
7517
+ name,
7518
+ index
7519
+ });
7520
+ }
7521
+ }
7522
+ return issues;
7523
+ }
7259
7524
  function resolveGroupDurationTicks(timing, timescale) {
7260
7525
  if (!Number.isFinite(timescale) || !Number.isInteger(timescale) || timescale <= 0) {
7261
7526
  throw new Error(
@@ -7571,6 +7836,40 @@ var RUNTIME_FEC_RECEIVER2 = Object.freeze({
7571
7836
  overlays: true
7572
7837
  });
7573
7838
 
7839
+ // node_modules/@blockcast/mmt-base/dist/mmtp-siblings.js
7840
+ var MMTP_MODES2 = Object.freeze(["mfu", "mfu-datagram"]);
7841
+ var MMTP_SIBLING_HARD_FIELDS2 = Object.freeze([
7842
+ "namespace",
7843
+ "timescale",
7844
+ "presentationAnchorTicks",
7845
+ "groupDuration"
7846
+ ]);
7847
+ var MMTP_SIBLING_RENDITION_FIELDS2 = Object.freeze([
7848
+ "codec",
7849
+ "width",
7850
+ "height",
7851
+ "framerate",
7852
+ "bitrate",
7853
+ "samplerate",
7854
+ "channelConfig",
7855
+ "lang"
7856
+ ]);
7857
+ var MMTP_SIBLING_SOFT_FIELDS2 = Object.freeze([
7858
+ "initRef",
7859
+ "keyframeIntervalMs",
7860
+ "keyframeIntervalTicks",
7861
+ "isLive",
7862
+ "altGroup"
7863
+ ]);
7864
+
7865
+ // node_modules/@blockcast/mmt-base/dist/datagram-leg-size.js
7866
+ var DATAGRAM_LEG_UDP_FLOOR2 = 1200;
7867
+ var DATAGRAM_LEG_QUIC_WT_FRAMING2 = 48;
7868
+ var DATAGRAM_LEG_OBJECT_HEADER2 = 13;
7869
+ var DATAGRAM_LEG_RELAY_ROOM2 = 16;
7870
+ var DATAGRAM_LEG_DATAGRAM_MAX2 = DATAGRAM_LEG_UDP_FLOOR2 - DATAGRAM_LEG_QUIC_WT_FRAMING2;
7871
+ var DATAGRAM_LEG_BODY_MAX2 = DATAGRAM_LEG_DATAGRAM_MAX2 - DATAGRAM_LEG_OBJECT_HEADER2 - DATAGRAM_LEG_RELAY_ROOM2;
7872
+
7574
7873
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
7575
7874
  var DEFAULT_DWELL_MS = 3e3;
7576
7875
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -9740,11 +10039,15 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9740
10039
  if (ot.role !== void 0 && existing.role === void 0) existing.role = ot.role;
9741
10040
  if (existing.packaging === "mmtp") {
9742
10041
  const mode = existing.mmtpMode ?? ot.mmtpMode;
9743
- if (mode !== "mfu") {
10042
+ if (mode === void 0) {
9744
10043
  throw new Error(
9745
10044
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9746
10045
  );
9747
10046
  }
10047
+ if (!isMmtpMode(mode)) {
10048
+ console.warn(`[phase14-catalog-override] track "${ot.name}" has unknown mmtpMode ${JSON.stringify(mode)}; skipping the override`);
10049
+ continue;
10050
+ }
9748
10051
  existing.mmtpMode = mode;
9749
10052
  if (existing.timescale === void 0 && ot.timescale !== void 0) existing.timescale = ot.timescale;
9750
10053
  if (existing.groupDurationMs === void 0 && ot.groupDurationMs !== void 0) {
@@ -9781,11 +10084,15 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9781
10084
  );
9782
10085
  }
9783
10086
  const mmtpMode = ot.mmtpMode;
9784
- if (packaging === "mmtp" && mmtpMode !== "mfu") {
10087
+ if (packaging === "mmtp" && mmtpMode === void 0) {
9785
10088
  throw new Error(
9786
10089
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9787
10090
  );
9788
10091
  }
10092
+ if (packaging === "mmtp" && !isMmtpMode(mmtpMode)) {
10093
+ console.warn(`[phase14-catalog-override] track "${ot.name}" has unknown mmtpMode ${JSON.stringify(mmtpMode)}; skipping the track`);
10094
+ continue;
10095
+ }
9789
10096
  if (packaging === "mmtp" && !isPositiveInteger(ot.timescale)) {
9790
10097
  throw new Error(
9791
10098
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid timescale`
@@ -13119,6 +13426,34 @@ var IsoBlockLocator = class _IsoBlockLocator {
13119
13426
  isHeld(ssId) {
13120
13427
  return this.#held.has(ssId);
13121
13428
  }
13429
+ /** The payload held unplaced for `ssId`, if any. */
13430
+ heldSource(ssId) {
13431
+ return this.#held.get(ssId);
13432
+ }
13433
+ /**
13434
+ * The SS_IDs strictly between `a` and `b` that no repair has delimited a
13435
+ * block of yet: those from the coverage end on, or all of them before the
13436
+ * first repair. `missing` is the highest of them no source is held for;
13437
+ * absent, every one of them arrived (C.5.2: SS_IDs are consecutive). Null
13438
+ * when none lies past coverage. `flagged` is whether a source held among
13439
+ * them satisfies `flag` (a RAP fragment, say): the held packets read as
13440
+ * fec-multicast-00 Block Classification item 1 reads bounding packets.
13441
+ */
13442
+ undelimitedBetween(a, b, flag) {
13443
+ if (!serial32Precedes(a, b) || serial32Distance(a, b) <= 1) return null;
13444
+ const first = a + 1 >>> 0;
13445
+ const end = this.#coverageEnd;
13446
+ const start = end !== void 0 && serial32Precedes(first, end) ? end : first;
13447
+ if (!serial32Precedes(start, b)) return null;
13448
+ const length = serial32Distance(start, b);
13449
+ const missing = this.#highestMissing(start, length);
13450
+ let flagged = false;
13451
+ for (let i = 0; flag !== void 0 && !flagged && i < length; i++) {
13452
+ const payload = this.#held.get(serial32Add(start, i));
13453
+ flagged = payload !== void 0 && flag(payload);
13454
+ }
13455
+ return missing === void 0 ? { start, flagged } : { start, missing, flagged };
13456
+ }
13122
13457
  /**
13123
13458
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
13124
13459
  * block states its range and places every held source in it; later repair
@@ -13347,6 +13682,7 @@ function resolveFecState(evidence) {
13347
13682
  const catalogFec = requireBoolean(evidence.catalogFec, "catalogFec");
13348
13683
  const bridgeAvailable = requireBoolean(evidence.bridgeAvailable, "bridgeAvailable");
13349
13684
  const multicastLegJoined = requireBoolean(evidence.multicastLegJoined, "multicastLegJoined");
13685
+ const datagramLegJoined = evidence.datagramLegJoined === void 0 ? false : requireBoolean(evidence.datagramLegJoined, "datagramLegJoined");
13350
13686
  const { transportPolicy, stats } = evidence;
13351
13687
  if (typeof transportPolicy !== "string" || !TRANSPORT_POLICIES.has(transportPolicy)) {
13352
13688
  throw new TypeError(`resolveFecState: unsupported transportPolicy ${JSON.stringify(transportPolicy)}`);
@@ -13355,6 +13691,7 @@ function resolveFecState(evidence) {
13355
13691
  throw new TypeError("resolveFecState: stats must be a plain object, null or undefined");
13356
13692
  }
13357
13693
  if (!catalogFec) return INACTIVE["no-catalog-fec"];
13694
+ if (datagramLegJoined) return { ...stats ?? {}, state: "active" };
13358
13695
  if (transportPolicy === "moq-only") return INACTIVE["reliable-moq"];
13359
13696
  if (!bridgeAvailable) return INACTIVE["no-multicast-bridge"];
13360
13697
  if (transportPolicy === "multicast-only" || multicastLegJoined) {
@@ -13395,31 +13732,26 @@ function deriveBlockClassifierGeometry(input) {
13395
13732
  );
13396
13733
  }
13397
13734
  if (input.trackKind === "audio") return { trackKind: "audio" };
13398
- if (!isPositiveFinite(input.framerate)) {
13399
- return { trackKind: "video", mode: "all-protected", reason: "framerate-absent" };
13400
- }
13401
- const framerate = input.framerate;
13402
13735
  let keyframeInterval;
13403
13736
  if (isPositiveFinite(input.keyframeIntervalTicks) && isPositiveFinite(input.timescale)) {
13404
13737
  keyframeInterval = { ticks: input.keyframeIntervalTicks, timescale: input.timescale };
13405
13738
  } else if (isPositiveFinite(input.keyframeIntervalMs)) {
13406
13739
  keyframeInterval = { ticks: input.keyframeIntervalMs, timescale: 1e3 };
13407
- } else {
13408
- return { trackKind: "video", mode: "all-protected", reason: "keyframe-cadence-absent" };
13409
13740
  }
13741
+ const protect = (reason) => ({
13742
+ trackKind: "video",
13743
+ mode: "all-protected",
13744
+ reason,
13745
+ ...keyframeInterval === void 0 ? {} : { keyframeInterval }
13746
+ });
13747
+ if (!isPositiveFinite(input.framerate)) return protect("framerate-absent");
13748
+ const framerate = input.framerate;
13749
+ if (keyframeInterval === void 0) return protect("keyframe-cadence-absent");
13410
13750
  const gopFrames = exactInteger(keyframeInterval.ticks * framerate, keyframeInterval.timescale);
13411
- if (gopFrames === null) {
13412
- return {
13413
- trackKind: "video",
13414
- mode: "all-protected",
13415
- reason: "keyframe-interval-not-integral"
13416
- };
13417
- }
13751
+ if (gopFrames === null) return protect("keyframe-interval-not-integral");
13418
13752
  const frameDurationMs = 1e3 / framerate;
13419
13753
  const interleaveUnits = deriveFecInterleaveDepth(input.interleaveDepthMs, frameDurationMs);
13420
- if (interleaveUnits >= gopFrames) {
13421
- return { trackKind: "video", mode: "all-protected", reason: "block-spans-gop" };
13422
- }
13754
+ if (interleaveUnits >= gopFrames) return protect("block-spans-gop");
13423
13755
  return {
13424
13756
  trackKind: "video",
13425
13757
  mode: "classifying",
@@ -13430,7 +13762,7 @@ function deriveBlockClassifierGeometry(input) {
13430
13762
  };
13431
13763
  }
13432
13764
  function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
13433
- if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return null;
13765
+ if (geometry2.trackKind !== "video" || geometry2.keyframeInterval === void 0) return null;
13434
13766
  if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0) return null;
13435
13767
  const { ticks, timescale } = geometry2.keyframeInterval;
13436
13768
  if (!Number.isSafeInteger(ticks) || !Number.isSafeInteger(timescale)) return null;
@@ -13439,9 +13771,15 @@ function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
13439
13771
  if (scaled % divisor !== 0n) return null;
13440
13772
  return scaled / divisor;
13441
13773
  }
13774
+ function keyframeInstantBetween(start, interval, from, to) {
13775
+ const k = from >= start ? (from - start) / interval + 1n : 1n;
13776
+ return start + k * interval <= to;
13777
+ }
13442
13778
  function compareDataUnitStarts(a, b) {
13443
- return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset;
13779
+ return a.movieFragment - b.movieFragment | 0 || a.idx - b.idx || a.offset - b.offset;
13444
13780
  }
13781
+ var LATE_RAP_MAX_MPUS_BACK = 64;
13782
+ var UNPLACED = { rapNotMpuStart: false };
13445
13783
  var BlockClassifier = class {
13446
13784
  #geometry;
13447
13785
  #mode;
@@ -13464,8 +13802,24 @@ var BlockClassifier = class {
13464
13802
  #mpuSbnSpans = /* @__PURE__ */ new Map();
13465
13803
  #dataUnitStarts = /* @__PURE__ */ new Map();
13466
13804
  #highestMpu = null;
13467
- /** MPU → movie_fragment_sequence_number observed in it. */
13468
- #mpuFragments = /* @__PURE__ */ new Map();
13805
+ /**
13806
+ * P3 layout, kept for the MPUs within the classification horizon and valid
13807
+ * within one continuous SBN sequence (`noteSourceDiscontinuity`).
13808
+ */
13809
+ #mpus = /* @__PURE__ */ new Map();
13810
+ /** An MPU of this sequence showed two movie fragments: each frame is one. */
13811
+ #fragmentPerFrame = false;
13812
+ /** A DU header of this sequence stated sample_number above 1. */
13813
+ #multiSampleFragment = false;
13814
+ /**
13815
+ * The anchor received last, whether or not its MPU is still in the
13816
+ * horizon. Each new anchor, and the anchor of every DU header's MPU, is
13817
+ * checked against it.
13818
+ */
13819
+ #lastAnchor = null;
13820
+ /** Two anchors were exactly G fragments per MPU apart. */
13821
+ #fragmentsProven = false;
13822
+ /** The first RAP released of the latest MPU a RAP was released in, recorded in every mode. */
13469
13823
  #lastRap = null;
13470
13824
  constructor(geometry2) {
13471
13825
  this.#geometry = geometry2;
@@ -13495,7 +13849,7 @@ var BlockClassifier = class {
13495
13849
  this.#geometry = geometry2;
13496
13850
  this.#blocks.clear();
13497
13851
  this.#clearContiguityLedger();
13498
- this.#mpuFragments.clear();
13852
+ this.#clearMpuLayout();
13499
13853
  this.#lastRap = null;
13500
13854
  this.#mpuBoundsRaps = true;
13501
13855
  if (geometry2.trackKind === "video" && geometry2.mode === "all-protected") {
@@ -13529,11 +13883,14 @@ var BlockClassifier = class {
13529
13883
  /**
13530
13884
  * The stream's SBN sequence restarted (FECManager source discontinuity:
13531
13885
  * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
13532
- * order are comparable only within one continuous sequence, so the P1
13533
- * ledger starts again.
13886
+ * order are comparable only within one continuous sequence, and a
13887
+ * restarted publisher numbers MPUs and movie fragments again, so the P1
13888
+ * ledger and the P3 layout start again.
13534
13889
  */
13535
13890
  noteSourceDiscontinuity() {
13536
13891
  this.#clearContiguityLedger();
13892
+ this.#clearMpuLayout();
13893
+ this.#lastRap = null;
13537
13894
  }
13538
13895
  /** Register a block that exists without evidence (a vanished block). */
13539
13896
  touch(sbn) {
@@ -13552,16 +13909,16 @@ var BlockClassifier = class {
13552
13909
  if (this.#geometry.trackKind === "audio") return [];
13553
13910
  const changes = [];
13554
13911
  const block = this.#blockFor(sbn);
13912
+ const placement = this.#place(evidence);
13555
13913
  if (evidence.rap) block.rapSeen = true;
13556
13914
  if (evidence.mpu !== void 0) block.mpus.add(evidence.mpu);
13557
- if (evidence.idx !== void 0) {
13558
- block.idxMin = block.idxMin === void 0 ? evidence.idx : Math.min(block.idxMin, evidence.idx);
13559
- block.idxMax = block.idxMax === void 0 ? evidence.idx : Math.max(block.idxMax, evidence.idx);
13915
+ const { position } = placement;
13916
+ if (position !== void 0) {
13917
+ block.positionMin = block.positionMin === void 0 ? position : Math.min(block.positionMin, position);
13918
+ block.positionMax = block.positionMax === void 0 ? position : Math.max(block.positionMax, position);
13560
13919
  }
13561
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
13562
- this.#mpuBoundsRaps = false;
13563
- }
13564
- const violation = this.#checkInvariants(sbn, block, evidence);
13920
+ if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false;
13921
+ const violation = this.#checkInvariants(sbn, block, evidence, placement);
13565
13922
  if (violation !== null) changes.push(...this.#disable(violation));
13566
13923
  const next = this.#classify(block);
13567
13924
  if (next !== block.cls && this.#allowed(block.cls, next)) {
@@ -13586,18 +13943,35 @@ var BlockClassifier = class {
13586
13943
  * RAP-bearing block is the one a wrong G calls delta), because the next
13587
13944
  * released RAP then belongs to m+2. Every MPU is one interval long, so the
13588
13945
  * span to any later released RAP proves or refutes all MPUs in between.
13589
- */
13590
- noteReleasedRap(mpu, presentationTime, mediaTimescale) {
13591
- if (this.#geometry.trackKind === "audio" || this.#mode === "all-protected") {
13592
- return [];
13593
- }
13594
- const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13595
- if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
13946
+ *
13947
+ * In every mode it keeps each MPU's first released RAP, with its decode
13948
+ * time, as the start keyframeFreeBetween measures the catalog interval
13949
+ * from, and a second RAP released inside one MPU refutes `mpuBoundsRaps`
13950
+ * when it lies off the catalog lattice (not a whole number of intervals
13951
+ * after the first; draft-ramadan-moq-mmt-02 4.4.3 binds every keyframe to
13952
+ * it): with no repair, released RAPs are the only evidence of where they
13953
+ * lie. Without a usable interval, or a decode time on either, any second
13954
+ * RAP with another presentation time refutes.
13955
+ */
13956
+ noteReleasedRap(mpu, presentationTime, mediaTimescale, decodeTime) {
13957
+ if (this.#geometry.trackKind === "audio") return [];
13596
13958
  const previous = this.#lastRap;
13597
13959
  if (previous !== null && previous.mpu === mpu && previous.mediaTimescale === mediaTimescale) {
13960
+ if (presentationTime === previous.presentationTime) return [];
13961
+ const interval2 = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13962
+ if (interval2 === null || decodeTime === void 0 || previous.decodeTime === void 0 || (decodeTime - previous.decodeTime) % interval2 !== 0n) {
13963
+ this.#mpuBoundsRaps = false;
13964
+ }
13598
13965
  return [];
13599
13966
  }
13600
- this.#lastRap = { mpu, presentationTime, mediaTimescale };
13967
+ if (previous !== null && previous.mediaTimescale === mediaTimescale) {
13968
+ const back = previous.mpu - mpu >>> 0;
13969
+ if (back !== 0 && back <= LATE_RAP_MAX_MPUS_BACK && presentationTime < previous.presentationTime) return [];
13970
+ }
13971
+ this.#lastRap = { mpu, presentationTime, mediaTimescale, ...decodeTime === void 0 ? {} : { decodeTime } };
13972
+ if (this.#mode === "all-protected") return [];
13973
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13974
+ if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
13601
13975
  if (previous === null || mpu < previous.mpu || previous.mediaTimescale !== mediaTimescale) {
13602
13976
  return [];
13603
13977
  }
@@ -13606,6 +13980,22 @@ var BlockClassifier = class {
13606
13980
  }
13607
13981
  return this.#disable("rap-spacing-mismatch");
13608
13982
  }
13983
+ /**
13984
+ * Whether a gap inside MPU `mpu`, between the decode times `from` and `to`
13985
+ * of the frames on either side, holds no keyframe: MPU boundaries still
13986
+ * bound RAPs, the catalog states an interval exact in this timescale, and
13987
+ * none of its instants after the MPU's first released RAP lies in
13988
+ * `(from, to]` (fec-multicast-00 Block Classification item 3). Anything
13989
+ * unknown counts as a keyframe.
13990
+ */
13991
+ keyframeFreeBetween(mpu, from, to, mediaTimescale) {
13992
+ const rap = this.#lastRap;
13993
+ if (!this.#mpuBoundsRaps || rap?.mpu !== mpu || rap.mediaTimescale !== mediaTimescale || rap.decodeTime === void 0) {
13994
+ return false;
13995
+ }
13996
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13997
+ return interval !== null && !keyframeInstantBetween(rap.decodeTime, interval, from, to);
13998
+ }
13609
13999
  #blockFor(sbn) {
13610
14000
  let block = this.#blocks.get(sbn);
13611
14001
  if (!block) {
@@ -13614,35 +14004,89 @@ var BlockClassifier = class {
13614
14004
  }
13615
14005
  return block;
13616
14006
  }
13617
- #checkInvariants(sbn, block, evidence) {
14007
+ #checkInvariants(sbn, block, evidence, placement) {
13618
14008
  if (this.#mode === "all-protected" || this.#geometry.trackKind !== "video") return null;
13619
14009
  const geometry2 = this.#geometry;
13620
14010
  if (geometry2.mode !== "classifying") return null;
13621
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
13622
- return "rap-not-mpu-start";
13623
- }
13624
- if (evidence.idx !== void 0 && evidence.idx >= geometry2.gopFrames) {
14011
+ if (placement.rapNotMpuStart) return "rap-not-mpu-start";
14012
+ if (placement.position !== void 0 && placement.position >= geometry2.gopFrames) {
13625
14013
  return "mpu-longer-than-gop";
13626
14014
  }
13627
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0 && block.idxMax - block.idxMin >= geometry2.interleaveUnits) {
14015
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0 && block.positionMax - block.positionMin >= geometry2.interleaveUnits) {
13628
14016
  return "block-wider-than-interleave";
13629
14017
  }
13630
- if (evidence.mpu !== void 0 && evidence.movieFragment !== void 0) {
13631
- const fragment = this.#mpuFragments.get(evidence.mpu);
13632
- if (fragment === void 0) {
13633
- this.#mpuFragments.set(evidence.mpu, evidence.movieFragment);
13634
- for (const mpu of this.#mpuFragments.keys()) {
13635
- if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu);
13636
- }
13637
- } else if (fragment !== evidence.movieFragment) {
13638
- return "mpu-multiple-fragments";
13639
- }
13640
- }
14018
+ if (placement.violation !== void 0) return placement.violation;
13641
14019
  if (evidence.mpu !== void 0 && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
13642
14020
  return "block-not-contiguous";
13643
14021
  }
13644
14022
  return null;
13645
14023
  }
14024
+ /**
14025
+ * The MPU position a source symbol's DU header proves (P3), and what it
14026
+ * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.
14027
+ */
14028
+ #place(evidence) {
14029
+ const { mpu, idx, movieFragment: fragment } = evidence;
14030
+ if (idx === void 0) return UNPLACED;
14031
+ const bySample = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 };
14032
+ if (mpu === void 0 || fragment === void 0) {
14033
+ return this.#fragmentPerFrame && !this.#multiSampleFragment ? { rapNotMpuStart: bySample.rapNotMpuStart } : bySample;
14034
+ }
14035
+ let layout = this.#mpus.get(mpu);
14036
+ if (layout === void 0) {
14037
+ layout = { low: fragment };
14038
+ this.#mpus.set(mpu, layout);
14039
+ for (const other of this.#mpus.keys()) {
14040
+ if (other + 1 < mpu) this.#mpus.delete(other);
14041
+ }
14042
+ } else if (fragment !== layout.low) {
14043
+ this.#fragmentPerFrame = true;
14044
+ if ((fragment - layout.low | 0) < 0) layout.low = fragment;
14045
+ }
14046
+ if (idx !== 0) this.#multiSampleFragment = true;
14047
+ let arrival;
14048
+ if (evidence.rap && layout.anchor === void 0) {
14049
+ layout.anchor = fragment;
14050
+ arrival = this.#anchorDrift(mpu, fragment);
14051
+ if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true;
14052
+ this.#lastAnchor = { mpu, fragment };
14053
+ }
14054
+ if (!this.#fragmentPerFrame) return bySample;
14055
+ if (this.#multiSampleFragment) return { ...bySample, violation: "mpu-multiple-fragments" };
14056
+ const { anchor } = layout;
14057
+ if (anchor === void 0) return UNPLACED;
14058
+ const drift = arrival ?? this.#anchorDrift(mpu, anchor);
14059
+ const offset = fragment - anchor | 0;
14060
+ return {
14061
+ ...offset === 0 || offset > 0 && this.#fragmentsProven ? { position: offset } : {},
14062
+ rapNotMpuStart: evidence.rap && offset !== 0 || (layout.low - anchor | 0) < 0 || // Fragments count frames: an anchor arriving past the spacing is a
14063
+ // RAP inside its MPU, or an earlier MPU outran G.
14064
+ arrival !== void 0 && arrival > 0 && this.#fragmentsProven,
14065
+ ...drift === void 0 || drift === 0 ? {} : { violation: "rap-spacing-mismatch" }
14066
+ };
14067
+ }
14068
+ /**
14069
+ * How many fragments MPU m's anchor `fragment` lies past the start that
14070
+ * the anchor received last predicts for MPU m: one frame per fragment and
14071
+ * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')
14072
+ * fragments apart, modulo 2^32. Undefined without a last anchor, a
14073
+ * cadence, or this layout.
14074
+ */
14075
+ #anchorDrift(mpu, fragment) {
14076
+ const geometry2 = this.#geometry;
14077
+ const last = this.#lastAnchor;
14078
+ if (last === null || !this.#fragmentPerFrame || this.#multiSampleFragment || geometry2.trackKind !== "video" || geometry2.mode !== "classifying") {
14079
+ return void 0;
14080
+ }
14081
+ return fragment - last.fragment - geometry2.gopFrames * (mpu - last.mpu) | 0;
14082
+ }
14083
+ #clearMpuLayout() {
14084
+ this.#mpus.clear();
14085
+ this.#fragmentPerFrame = false;
14086
+ this.#multiSampleFragment = false;
14087
+ this.#lastAnchor = null;
14088
+ this.#fragmentsProven = false;
14089
+ }
13646
14090
  #clearContiguityLedger() {
13647
14091
  this.#mpuSbnSpans.clear();
13648
14092
  this.#dataUnitStarts.clear();
@@ -13742,9 +14186,9 @@ var BlockClassifier = class {
13742
14186
  if (this.#mode === "all-protected") return "unknown";
13743
14187
  const geometry2 = this.#geometry;
13744
14188
  if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return "unknown";
13745
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0) {
14189
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0) {
13746
14190
  const span = geometry2.interleaveUnits - 1;
13747
- if (block.idxMax - span >= 1 && block.idxMin + span <= geometry2.gopFrames - 1) {
14191
+ if (block.positionMax - span >= 1 && block.positionMin + span <= geometry2.gopFrames - 1) {
13748
14192
  return "delta";
13749
14193
  }
13750
14194
  }
@@ -14003,7 +14447,12 @@ var FECManager = class _FECManager {
14003
14447
  this.#repairHoldUntilMs = /* @__PURE__ */ new Map();
14004
14448
  // Receiver-measured multicast delivery gap: the late-symbol wait's jitter
14005
14449
  // term (see DeliveryGapEstimator for the statistic and why).
14006
- this.#deliveryGaps = new DeliveryGapEstimator();
14450
+ // One estimator per lossy path, so a hybrid session never lets one leg's
14451
+ // stall widen the other's wait; the wait reads the larger peak.
14452
+ this.#deliveryGaps = {
14453
+ multicast: new DeliveryGapEstimator(),
14454
+ "moq-datagram": new DeliveryGapEstimator()
14455
+ };
14007
14456
  this.#lifecycleTrace = [];
14008
14457
  // Worker-backed timeouts enqueue cleanup behind all prior symbol messages.
14009
14458
  // Failure remains pending until cleanupComplete acknowledges that queue drain.
@@ -14041,7 +14490,8 @@ var FECManager = class _FECManager {
14041
14490
  this.#ssbLengthConflictCount = 0;
14042
14491
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
14043
14492
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
14044
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
14493
+ // symbols its repair group carries; 0 for a repair-less span no repair can
14494
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
14045
14495
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
14046
14496
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
14047
14497
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -14194,6 +14644,14 @@ var FECManager = class _FECManager {
14194
14644
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
14195
14645
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
14196
14646
  this.#isoLocators = /* @__PURE__ */ new Map();
14647
+ // The ts of the run behind the gap the release gate last asked about, per
14648
+ // stream (isoRepairlessWaitMs), keyed on the frame before the gap: kept, as
14649
+ // the source it came from may retire before the run's deadline, and the
14650
+ // earliest found wins, so a late frame that becomes the head restarts
14651
+ // nothing. It stays until the next run gap: a source discontinuity drops
14652
+ // it, and one older than twice the hold ceiling is not this gap's.
14653
+ // `counted` once the deadline passed (onUndelimitedRunGap).
14654
+ this.#runAnchors = /* @__PURE__ */ new Map();
14197
14655
  this.#deferIsoGaps = false;
14198
14656
  this.#isoRepairRefusedCount = 0;
14199
14657
  this.#isoSourceOversizeCount = 0;
@@ -14229,6 +14687,8 @@ var FECManager = class _FECManager {
14229
14687
  this.#workerErrorCounts = /* @__PURE__ */ new Map();
14230
14688
  this.#decoderUnavailableEvents = 0;
14231
14689
  this.#repairSymbolSizeMismatchCount = 0;
14690
+ this.#unlistedRepairTrackRefusals = 0;
14691
+ this.#unresolvedRepairOwnerDrops = { unregistered: 0, ownerAbsent: 0, ownerAmbiguous: 0 };
14232
14692
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
14233
14693
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
14234
14694
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
@@ -14288,6 +14748,18 @@ var FECManager = class _FECManager {
14288
14748
  this.onBlockResolved = null;
14289
14749
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
14290
14750
  this.onSourceDiscontinuity = null;
14751
+ /** The FEC deadline of a run no repair delimited passed, releasing the gap behind it (once per gap). */
14752
+ this.onUndelimitedRunGap = null;
14753
+ /**
14754
+ * The span and tolerance the catalog states for a keyframe overlay
14755
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
14756
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
14757
+ * undefined while none is installed. A stated block only a late source
14758
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
14759
+ * late source can fill, also wait for that overlay's repair
14760
+ * (#overlayLateWaitMs).
14761
+ */
14762
+ this.keyframeOverlayTiming = null;
14291
14763
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
14292
14764
  /**
14293
14765
  * A recovered source symbol. Return false when admission refused the
@@ -14378,6 +14850,7 @@ var FECManager = class _FECManager {
14378
14850
  #highestSbn;
14379
14851
  #sourceFrontiers;
14380
14852
  #isoLocators;
14853
+ #runAnchors;
14381
14854
  #deferIsoGaps;
14382
14855
  #isoRepairRefusedCount;
14383
14856
  #isoSourceOversizeCount;
@@ -14392,6 +14865,8 @@ var FECManager = class _FECManager {
14392
14865
  #workerErrorCounts;
14393
14866
  #decoderUnavailableEvents;
14394
14867
  #repairSymbolSizeMismatchCount;
14868
+ #unlistedRepairTrackRefusals;
14869
+ #unresolvedRepairOwnerDrops;
14395
14870
  #onUndelimitedLoss;
14396
14871
  #onIsoHoleExpired;
14397
14872
  #encodeTrackName(catalogTrackName) {
@@ -15041,6 +15516,7 @@ var FECManager = class _FECManager {
15041
15516
  const discontinuity = () => {
15042
15517
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
15043
15518
  this.#noSpanRaps.delete(streamKey);
15519
+ this.#runAnchors.delete(streamKey);
15044
15520
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
15045
15521
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
15046
15522
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -15211,7 +15687,7 @@ var FECManager = class _FECManager {
15211
15687
  consider(geometry2, this.#parseStreamKey(streamKey).packetId);
15212
15688
  }
15213
15689
  for (const [packetId, config] of this.#trackConfigs) consider(config.geometry, packetId);
15214
- this.#deliveryGaps.setWindowMs(windowMs);
15690
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.setWindowMs(windowMs);
15215
15691
  }
15216
15692
  /**
15217
15693
  * The multicast late-symbol wait: the block span plus the larger of the
@@ -15224,14 +15700,14 @@ var FECManager = class _FECManager {
15224
15700
  * stream order and never feeds the estimator.
15225
15701
  */
15226
15702
  #multicastWaitMs(config) {
15227
- return this.#waitForGapMs(config, this.#deliveryGaps.peakGapMs(performance.now()));
15703
+ return this.#waitForGapMs(config, this.#peakDeliveryGapMs());
15228
15704
  }
15229
15705
  /**
15230
15706
  * The widest #multicastWaitMs can become: the estimator reports at most its
15231
15707
  * catalog window, so this is a catalog quantity that no measurement moves.
15232
15708
  */
15233
15709
  #maxMulticastWaitMs(config) {
15234
- return this.#waitForGapMs(config, this.#deliveryGaps.windowMs ?? 0);
15710
+ return this.#waitForGapMs(config, this.#deliveryGaps.multicast.windowMs ?? 0);
15235
15711
  }
15236
15712
  #waitForGapMs(config, gapMs) {
15237
15713
  if (!(gapMs > 0) || !(config.interleaveDepthMs > 0)) return config.timeoutMs;
@@ -15415,6 +15891,7 @@ var FECManager = class _FECManager {
15415
15891
  ...(config.trackKind ?? previous.trackKind) === void 0 ? {} : { trackKind: config.trackKind ?? previous.trackKind },
15416
15892
  ...(config.codec ?? previous.codec) === void 0 ? {} : { codec: config.codec ?? previous.codec },
15417
15893
  ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry },
15894
+ ...(config.groupDurationMs ?? previous.groupDurationMs) === void 0 ? {} : { groupDurationMs: config.groupDurationMs ?? previous.groupDurationMs },
15418
15895
  ...(config.repairLayers ?? previous.repairLayers) === void 0 ? {} : { repairLayers: config.repairLayers ?? previous.repairLayers },
15419
15896
  ...(config.heldLayers ?? previous.heldLayers) === void 0 ? {} : { heldLayers: config.heldLayers ?? previous.heldLayers }
15420
15897
  };
@@ -15521,6 +15998,10 @@ var FECManager = class _FECManager {
15521
15998
  lifecycleTrace: this.#lifecycleTrace.map((entry) => ({ ...entry }))
15522
15999
  };
15523
16000
  }
16001
+ /** Count a repair packet the router dropped for want of an owning track (BLO-55759). */
16002
+ countUnresolvedRepairOwner(reason) {
16003
+ this.#unresolvedRepairOwnerDrops[reason]++;
16004
+ }
15524
16005
  get fecStats() {
15525
16006
  const s = this.#fecStats;
15526
16007
  const affected = s.blocksRecovered + s.blocksFailed;
@@ -15560,6 +16041,8 @@ var FECManager = class _FECManager {
15560
16041
  packetId
15561
16042
  })),
15562
16043
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
16044
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
16045
+ unresolvedRepairOwnerDrops: { ...this.#unresolvedRepairOwnerDrops },
15563
16046
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
15564
16047
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
15565
16048
  };
@@ -15584,6 +16067,16 @@ var FECManager = class _FECManager {
15584
16067
  this.#startupRepairBoundaryCounts.clear();
15585
16068
  this.#startupRepairFailOpenPackets.clear();
15586
16069
  }
16070
+ /**
16071
+ * Start a new "mfu-datagram" leg (mmt-02 4.3.1) without discarding
16072
+ * track/decoder state: the same join-boundary rules as a multicast join,
16073
+ * since the leg starts at an arbitrary datagram too. It resets the whole
16074
+ * join boundary of this manager, a multicast ordered-relay frontier
16075
+ * included, so a host gives the leg a manager of its own.
16076
+ */
16077
+ beginLegJoin() {
16078
+ this.beginMulticastJoin();
16079
+ }
15587
16080
  /** How the multicast leg currently delivers symbols. */
15588
16081
  get multicastSymbolDelivery() {
15589
16082
  return this.#multicastSymbolDelivery;
@@ -15606,7 +16099,8 @@ var FECManager = class _FECManager {
15606
16099
  );
15607
16100
  }
15608
16101
  if (delivery === this.#multicastSymbolDelivery) return;
15609
- this.#deliveryGaps.reset();
16102
+ this.#deliveryGaps.multicast.reset();
16103
+ this.#runAnchors.clear();
15610
16104
  if (delivery === "ordered-relay") {
15611
16105
  for (const [packetId, config] of this.#trackConfigs) {
15612
16106
  this.#orderedHorizonBlocksFor(packetId, config);
@@ -15695,6 +16189,7 @@ var FECManager = class _FECManager {
15695
16189
  resetMap(this.#highestSbn);
15696
16190
  resetMap(this.#sourceFrontiers);
15697
16191
  resetMap(this.#isoLocators);
16192
+ resetMap(this.#runAnchors);
15698
16193
  resetMap(this.#sourceAnchors);
15699
16194
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
15700
16195
  this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
@@ -15804,6 +16299,7 @@ var FECManager = class _FECManager {
15804
16299
  dropMap(this.#highestSbn);
15805
16300
  dropMap(this.#sourceFrontiers);
15806
16301
  dropMap(this.#isoLocators);
16302
+ dropMap(this.#runAnchors);
15807
16303
  dropMap(this.#sourceAnchors);
15808
16304
  dropMap(this.#classifiers);
15809
16305
  dropMap(this.#noSpanRaps);
@@ -15871,8 +16367,8 @@ var FECManager = class _FECManager {
15871
16367
  const sourceSymbols = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? this.#trackConfig(packetId).k;
15872
16368
  const isSourceSymbol = esi >= 0 && esi < sourceSymbols;
15873
16369
  const isStartupPartial = this.#startupPartialBlocks.has(blockKey);
15874
- const isReadyMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
15875
- const awaitingMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !this.#startupRepairReadyPackets.has(streamKey) && !this.#startupRepairFailOpenPackets.has(streamKey);
16370
+ const isReadyMulticastRepair = this.#startupRequireRepairReady && source !== "moq" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
16371
+ const awaitingMulticastRepair = this.#startupRequireRepairReady && source !== "moq" && !this.#startupRepairReadyPackets.has(streamKey) && !this.#startupRepairFailOpenPackets.has(streamKey);
15876
16372
  if (awaitingMulticastRepair) {
15877
16373
  if (!isSourceSymbol) {
15878
16374
  this.#startupRepairReadyPackets.add(streamKey);
@@ -15926,12 +16422,14 @@ var FECManager = class _FECManager {
15926
16422
  ...catalogTrackName === void 0 ? {} : { catalogTrackName },
15927
16423
  multicastSymbols: 0,
15928
16424
  moqSymbols: 0,
16425
+ datagramSymbols: 0,
15929
16426
  complete: false
15930
16427
  };
15931
16428
  const receivedAtMs = this.#receiptNow();
15932
16429
  const anchorMs = this.#blockAnchorsMs.get(blockKey);
15933
16430
  if (anchorMs === void 0 || receivedAtMs < anchorMs) this.#blockAnchorsMs.set(blockKey, receivedAtMs);
15934
16431
  if (source === "multicast") counts.multicastSymbols++;
16432
+ else if (source === "moq-datagram") counts.datagramSymbols++;
15935
16433
  else counts.moqSymbols++;
15936
16434
  this.#blockPathCounts.set(blockKey, counts);
15937
16435
  this.#observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName);
@@ -15952,7 +16450,7 @@ var FECManager = class _FECManager {
15952
16450
  this.#unindexBlockKey(key);
15953
16451
  }
15954
16452
  }
15955
- if (isSourceSymbol && source === "multicast") {
16453
+ if (isSourceSymbol && source !== "moq") {
15956
16454
  this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
15957
16455
  }
15958
16456
  return true;
@@ -16041,8 +16539,22 @@ var FECManager = class _FECManager {
16041
16539
  * DeliveryGapEstimator). Datagram delivery only.
16042
16540
  */
16043
16541
  noteMulticastArrival(packetId, packetSequenceNumber) {
16044
- if (this.#multicastSymbolDelivery !== "datagram") return;
16045
- this.#deliveryGaps.noteArrival(performance.now(), packetId, packetSequenceNumber);
16542
+ this.noteArrival("multicast", packetId, packetSequenceNumber);
16543
+ }
16544
+ /**
16545
+ * Record one MMTP packet arrival on a lossy path for that path's
16546
+ * delivery-gap measurement: the multicast leg (datagram delivery only; an
16547
+ * ordered relay settles by stream order) or an "mfu-datagram" leg, whose
16548
+ * datagrams are always a lossy path (#lossyDatagramPath).
16549
+ */
16550
+ noteArrival(path, packetId, packetSequenceNumber) {
16551
+ if (!this.#lossyDatagramPath(path)) return;
16552
+ this.#deliveryGaps[path].noteArrival(performance.now(), packetId, packetSequenceNumber);
16553
+ }
16554
+ /** The largest delivery gap any lossy path measured over its window. */
16555
+ #peakDeliveryGapMs() {
16556
+ const now = performance.now();
16557
+ return Math.max(...Object.values(this.#deliveryGaps).map((estimator) => estimator.peakGapMs(now)));
16046
16558
  }
16047
16559
  /**
16048
16560
  * Resolved per-track multicast late-symbol wait in milliseconds: the span
@@ -16056,16 +16568,18 @@ var FECManager = class _FECManager {
16056
16568
  * Largest multicast delivery gap measured over the current window (ms), and
16057
16569
  * that window (undefined: held since the last reset). Diagnostics.
16058
16570
  */
16059
- multicastDeliveryGap() {
16571
+ multicastDeliveryGap(path = "multicast") {
16060
16572
  return {
16061
- peakGapMs: this.#deliveryGaps.peakGapMs(performance.now()),
16062
- windowMs: this.#deliveryGaps.windowMs
16573
+ peakGapMs: this.#deliveryGaps[path].peakGapMs(performance.now()),
16574
+ windowMs: this.#deliveryGaps[path].windowMs
16063
16575
  };
16064
16576
  }
16065
16577
  /**
16066
16578
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
16067
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
16068
- * Undefined for a block that is not open.
16579
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
16580
+ * repair-less span states its length, and RSB_length 0 when it is longer
16581
+ * than K, since no repair can reach it). Undefined for a block that is not
16582
+ * open.
16069
16583
  */
16070
16584
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
16071
16585
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16155,6 +16669,23 @@ var FECManager = class _FECManager {
16155
16669
  const config = this.#trackConfigs.get(packetId);
16156
16670
  return config === void 0 ? void 0 : this.#blockLifetimeMs(config);
16157
16671
  }
16672
+ /**
16673
+ * How long an "mfu-datagram" leg's duplicate ledgers must remember a packet
16674
+ * so a legal reorder never reads as a publisher restart: one block span,
16675
+ * the reorder tolerance (`timeoutMs` is span + tolerance) and one group,
16676
+ * since a datagram may trail the stream by a whole group behind a joining
16677
+ * FETCH (mmt-02 6.1 step 3). The group is the catalog group duration
16678
+ * (`groupDurationMs`), whatever the track kind; a video track configured
16679
+ * without one falls back to its keyframe interval (one GOP per group).
16680
+ * Undefined for an unconfigured packet id.
16681
+ */
16682
+ datagramLegLedgerRetentionMsForPacket(packetId) {
16683
+ const config = this.#trackConfigs.get(packetId);
16684
+ if (config === void 0) return void 0;
16685
+ const geometry2 = config.geometry;
16686
+ const groupMs = config.groupDurationMs ?? (geometry2?.trackKind === "video" && geometry2.mode === "classifying" ? geometry2.keyframeInterval.ticks / geometry2.keyframeInterval.timescale * 1e3 : 0);
16687
+ return config.timeoutMs + (Number.isFinite(groupMs) ? groupMs : 0);
16688
+ }
16158
16689
  /**
16159
16690
  * How long a terminal (clean, recovered or failed) block stays authoritative,
16160
16691
  * for late symbols and for the in-order release gate. It is also the gate's
@@ -16181,7 +16712,7 @@ var FECManager = class _FECManager {
16181
16712
  }
16182
16713
  const trackConfig = this.#trackConfigs.get(packetId);
16183
16714
  if (trackConfig === void 0) return void 0;
16184
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
16715
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
16185
16716
  }
16186
16717
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
16187
16718
  // -----------------------------------------------------------------------
@@ -16223,6 +16754,9 @@ var FECManager = class _FECManager {
16223
16754
  for (const key of [...this.#isoLocators.keys()]) {
16224
16755
  if (this.#belongsToPacket(key, packetId)) this.#isoLocators.delete(key);
16225
16756
  }
16757
+ for (const key of [...this.#runAnchors.keys()]) {
16758
+ if (this.#belongsToPacket(key, packetId)) this.#runAnchors.delete(key);
16759
+ }
16226
16760
  }
16227
16761
  /**
16228
16762
  * The iso-ssbg1-v1 locator horizon in blocks: every block the manager can
@@ -16272,9 +16806,9 @@ var FECManager = class _FECManager {
16272
16806
  holdIsoSource(packetId, catalogTrackName, ssId, source) {
16273
16807
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16274
16808
  const evictedBefore = locator.heldEvicted;
16275
- const held = locator.hold(ssId, source);
16809
+ const held = locator.hold(ssId, source.arrivedAtMs === void 0 ? { ...source, arrivedAtMs: this.#receiptNow() } : source);
16276
16810
  this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16277
- if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16811
+ if (held && source.source !== "moq") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16278
16812
  const evicted = locator.heldEvicted - evictedBefore;
16279
16813
  if (evicted > 0) {
16280
16814
  const before = this.#isoHeldEvictedCount;
@@ -16367,12 +16901,24 @@ var FECManager = class _FECManager {
16367
16901
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
16368
16902
  * SS_ID of which vanished resolves through its deadline like any vanished
16369
16903
  * block.
16904
+ *
16905
+ * A span longer than K holds more than one block (SSB_length <= K), and the
16906
+ * locator states no block inside a span, only one exactly its range
16907
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
16908
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
16909
+ * Group of it (group-cannot-complete). Every span still keeps its whole
16910
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
16911
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
16912
+ * gate lets those frames go once only a late source can fill the gap
16913
+ * before them, as long after they arrived as the gap's decision allows
16914
+ * (isoRepairlessWaitMs).
16370
16915
  */
16371
16916
  #openIsoSpan(span, packetId, catalogTrackName) {
16372
16917
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
16373
16918
  if (!this.#blockAuthoredLengths.has(key)) {
16374
16919
  this.#blockAuthoredLengths.set(key, span.block.length);
16375
16920
  this.#isoSpanKeys.add(key);
16921
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
16376
16922
  }
16377
16923
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
16378
16924
  }
@@ -16380,7 +16926,12 @@ var FECManager = class _FECManager {
16380
16926
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
16381
16927
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
16382
16928
  * that could hold them is pending or not yet stated by a repair, else the
16383
- * starts of the blocks that failed or vanished.
16929
+ * starts of the blocks that failed or vanished. SS_IDs no repair has
16930
+ * delimited yet that all arrived lost nothing and wait for no repair, only
16931
+ * the late-source allowance after the datagram of a lossy path that clocks
16932
+ * them arrived (#lossFreeRunReadyAtMs), and not even that when none of them
16933
+ * came as one; one missing makes a run that waits as one block
16934
+ * (isoRepairlessWaitMs).
16384
16935
  *
16385
16936
  * `untracked` reads as the release gate reads it (MmtpRouter
16386
16937
  * #createFecReleaseGate): a block holding either released frame's SS_ID
@@ -16393,7 +16944,16 @@ var FECManager = class _FECManager {
16393
16944
  isoSpanResolution(packetId, catalogTrackName, fromSsId, toSsId) {
16394
16945
  if (!serial32Precedes(fromSsId, toSsId) || serial32Distance(fromSsId, toSsId) <= 1) return [];
16395
16946
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
16396
- if (!locator || !locator.coversBetween(fromSsId, toSsId)) return null;
16947
+ if (!locator) return null;
16948
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
16949
+ if (run?.missing !== void 0) return null;
16950
+ if (run !== null) {
16951
+ const config = this.#trackConfigs.get(packetId);
16952
+ const readyAtMs = config === void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
16953
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) return null;
16954
+ }
16955
+ if (locator.coverageEnd === void 0) return [];
16956
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return null;
16397
16957
  const highest = this.highestSbn(packetId, catalogTrackName);
16398
16958
  const lost = [];
16399
16959
  for (const block of locator.blocksBetween(fromSsId, toSsId)) {
@@ -16411,6 +16971,162 @@ var FECManager = class _FECManager {
16411
16971
  }
16412
16972
  return lost;
16413
16973
  }
16974
+ /**
16975
+ * When undelimited SS_IDs from `runStart` up to `toSsId` that all arrived
16976
+ * stop holding its frame: the late-source allowance after the receipt of
16977
+ * a datagram of a lossy path (#lossyDatagramPath: a multicast datagram, or
16978
+ * one of an "mfu-datagram" leg). Until then a frame between them may still
16979
+ * complete from a packet with no SS_ID (an untagged FT=0/FT=1 reordered
16980
+ * behind the next frame), and a repair may delimit them. The receipt is
16981
+ * `toSsId`'s own when it is held from such a datagram. Otherwise (its
16982
+ * packet came only as an overlap copy or from a MoQ stream, or was evicted
16983
+ * or retired) it is the newest among those SS_IDs, every one of which is
16984
+ * held and states its path. So the time moves at most once, when the
16985
+ * head's own datagram copy arrives while its frame waits or its held
16986
+ * source is dropped, and never on a later ask.
16987
+ *
16988
+ * Undefined, so the range releases at once, when no SS_ID of it came as
16989
+ * such a datagram: a MoQ arrival, an ordered relay's and the frame's own
16990
+ * are no clock for datagram reordering (#lossyReceiptMs). Undefined too
16991
+ * on a track with no catalog span, which states no allowance: the local
16992
+ * timeout is a cleanup bound, and isoRepairlessWaitMs arms no wake there,
16993
+ * so a wait would hold the frame until the next packet. The cost, on
16994
+ * multicast and on the leg too: an untagged FT=0/FT=1 reordered behind
16995
+ * the next frame of such a track is dropped stale.
16996
+ */
16997
+ #lossFreeRunReadyAtMs(config, locator, runStart, toSsId) {
16998
+ if (!_FECManager.#hasCatalogTiming(config)) return void 0;
16999
+ let clockMs = this.#lossyReceiptMs(locator.heldSource(toSsId));
17000
+ if (clockMs === void 0) {
17001
+ for (let ssId = runStart; ssId !== toSsId; ssId = ssId + 1 >>> 0) {
17002
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
17003
+ if (atMs !== void 0 && (clockMs === void 0 || atMs > clockMs)) clockMs = atMs;
17004
+ }
17005
+ }
17006
+ if (clockMs === void 0) return void 0;
17007
+ return clockMs + Math.max(0, this.#multicastWaitMs(config) - config.interleaveDepthMs);
17008
+ }
17009
+ /**
17010
+ * Receipt time of a held source that came as a datagram of a lossy path
17011
+ * (#lossyDatagramPath), else undefined: a MoQ stream and an ordered relay
17012
+ * deliver in order, so their arrivals clock no reorder allowance and no
17013
+ * FEC deadline. The path is the one the feed stated (IsoHeldSource.source,
17014
+ * and MulticastSymbolDelivery for a multicast source), never a guess.
17015
+ */
17016
+ #lossyReceiptMs(held) {
17017
+ return held !== void 0 && this.#lossyDatagramPath(held.source) ? held.arrivedAtMs : void 0;
17018
+ }
17019
+ /**
17020
+ * The one path predicate of the loss gates: whether a symbol fed as
17021
+ * `source` reached this manager as a datagram of its own, on a path that
17022
+ * loses and reorders (mmt-02 Section 2, a datagram leg). A multicast
17023
+ * symbol does unless its provider declared an ordered relay. An
17024
+ * "mfu-datagram" object always does (4.3.1): MulticastSymbolDelivery is
17025
+ * the multicast provider's statement and is never read for the leg. A MoQ
17026
+ * stream object never does, a stream copy of the leg included.
17027
+ */
17028
+ #lossyDatagramPath(source) {
17029
+ return source === "moq-datagram" || source === "multicast" && this.#multicastSymbolDelivery === "datagram";
17030
+ }
17031
+ /**
17032
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
17033
+ * between two released frames' SS_IDs once only a late source can still
17034
+ * fill them, else undefined. That is when every one missing (neither
17035
+ * arrived nor held) lies in a repair-less span longer than K, which no
17036
+ * repair can state a block of (#openIsoSpan), or in a stated block its
17037
+ * own repair group cannot complete every SS_ID of which it misses lies
17038
+ * between them (so the gap's decision covers all it lost), and a source of
17039
+ * a lossy leg (multicast, or an "mfu-datagram" leg's datagram) at or past
17040
+ * `toSsId` arrived, so each is lost or reordered behind it (a MoQ source
17041
+ * shows nothing: MoQ streams overtake one another). The span or block
17042
+ * itself keeps its own wait.
17043
+ *
17044
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
17045
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
17046
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
17047
+ * Then the frame waits as a stated block its group cannot complete does
17048
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
17049
+ * overlay's span plus the larger of the allowance and its tolerance, or,
17050
+ * for an overlay that states no span, the span's whole wait (undefined).
17051
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
17052
+ * the gap holds a stated block's loss.
17053
+ *
17054
+ * A run of SS_IDs no repair has delimited yet, one of which never arrived,
17055
+ * is one block of its own instead (draft-ramadan-moq-fec-multicast-00,
17056
+ * Receiver Repair Policy; on an "mfu-datagram" leg fec-core-00 9.3 and
17057
+ * mmt-02 5.3.3): the frame then waits for that block's FEC deadline,
17058
+ * whatever the flags: ts plus the whole multicast wait (fec-core-00 9.3),
17059
+ * ts the receipt of the lowest held source above the run that came as a
17060
+ * datagram of a lossy path (#lossyDatagramPath), up to the newest
17061
+ * (fec-multicast-00, Deadline Anchoring; under reordering at or after the
17062
+ * draft's first signal, never before). The wait returned counts from
17063
+ * `arrivedAtMs`, the frame's arrival; without it, it is the whole wait.
17064
+ * With no such source held (never arrived, retired, or evicted, or every
17065
+ * one from a MoQ stream or an ordered relay) the frame keeps the hold
17066
+ * ceiling: a stream arrival is no clock for a datagram deadline.
17067
+ */
17068
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false, arrivedAtMs) {
17069
+ const config = this.#trackConfigs.get(packetId);
17070
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
17071
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
17072
+ const locator = this.#isoLocators.get(streamKey);
17073
+ if (locator === void 0) return void 0;
17074
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
17075
+ const readyAtMs = run === null || run.missing !== void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
17076
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) {
17077
+ return Math.max(0, readyAtMs - (arrivedAtMs ?? this.#receiptNow()));
17078
+ }
17079
+ const newestSource = locator.newestSource;
17080
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
17081
+ if (run?.missing !== void 0) {
17082
+ if (this.isoSpanResolution(packetId, catalogTrackName, fromSsId, run.start) === null) return void 0;
17083
+ const kept = this.#runAnchors.get(streamKey);
17084
+ const anchor = kept?.fromSsId === fromSsId && this.#receiptNow() - kept.tsMs <= 2 * (config.interleaveDepthMs + 2 * this.#blockLifetimeMs(config)) ? kept : void 0;
17085
+ let tsMs = anchor?.tsMs;
17086
+ for (let ssId = run.missing + 1 >>> 0; !serial32Precedes(newestSource, ssId); ssId = ssId + 1 >>> 0) {
17087
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
17088
+ if (atMs === void 0) continue;
17089
+ if (tsMs === void 0 || atMs < tsMs) tsMs = atMs;
17090
+ break;
17091
+ }
17092
+ if (tsMs === void 0) return void 0;
17093
+ const waitMs2 = this.#multicastWaitMs(config);
17094
+ let counted = anchor?.counted === true;
17095
+ if (!counted && tsMs + waitMs2 <= this.#receiptNow()) {
17096
+ counted = true;
17097
+ this.onUndelimitedRunGap?.(packetId, catalogTrackName);
17098
+ }
17099
+ this.#runAnchors.set(streamKey, { fromSsId, tsMs, counted });
17100
+ return arrivedAtMs === void 0 ? waitMs2 : Math.max(0, tsMs + waitMs2 - arrivedAtMs);
17101
+ }
17102
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return void 0;
17103
+ let repairless = false;
17104
+ let stated = false;
17105
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
17106
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
17107
+ if (this.#completedBlocks.has(key)) continue;
17108
+ if (block.span && block.length > locator.kMax) {
17109
+ repairless = true;
17110
+ continue;
17111
+ }
17112
+ const received = this.#blockSourceEsis.get(key);
17113
+ const rebuilt = this.#blockRebuiltEsis.get(key);
17114
+ let missesInGap = false;
17115
+ let missesOutside = false;
17116
+ for (let esi = 0; esi < block.length; esi++) {
17117
+ const ssId = serial32Add(block.start, esi);
17118
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
17119
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
17120
+ else if (!rebuilt?.has(esi)) missesOutside = true;
17121
+ }
17122
+ if (!missesInGap) continue;
17123
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
17124
+ repairless = stated = true;
17125
+ }
17126
+ if (!repairless) return void 0;
17127
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
17128
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
17129
+ }
16414
17130
  /**
16415
17131
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
16416
17132
  * the sources held now for a block no repair has stated yet, and the held
@@ -16464,11 +17180,31 @@ var FECManager = class _FECManager {
16464
17180
  * it does not. A stream with no classifier yet has shown nothing against it,
16465
17181
  * and neither has a stream without catalog timing until it releases two
16466
17182
  * RAPs inside one MPU.
16467
- */
16468
- mpuBoundsRapsFor(packetId, catalogTrackName) {
17183
+ *
17184
+ * With catalog timing and a `gap` inside one MPU, between the authored
17185
+ * timing of the frames on either side, it also takes the catalog keyframe
17186
+ * interval to rule a keyframe out of the gap
17187
+ * (`BlockClassifier.keyframeFreeBetween`, fec-multicast-00 Block
17188
+ * Classification item 3), and no source held between the frames' SS_IDs
17189
+ * may carry the RAP flag or another MPU's number (item 1 read on the held
17190
+ * packets: a RAP the loss cut in two is never released, so the frames
17191
+ * alone cannot show it); anything unknown counts as a keyframe.
17192
+ */
17193
+ mpuBoundsRapsFor(packetId, catalogTrackName, gap) {
16469
17194
  const streamKey = this.#streamKey(packetId, catalogTrackName);
16470
17195
  if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
16471
- return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true;
17196
+ const classifier = this.#classifiers.get(streamKey);
17197
+ if (gap === void 0) return classifier?.mpuBoundsRaps ?? true;
17198
+ const { mpu, from, to, fromSsId, toSsId } = gap;
17199
+ if (fromSsId !== void 0 && toSsId !== void 0) {
17200
+ const run = this.#isoLocators.get(streamKey)?.undelimitedBetween(
17201
+ fromSsId,
17202
+ toSsId,
17203
+ ({ evidence }) => evidence.rap || evidence.mpu !== void 0 && evidence.mpu !== mpu
17204
+ );
17205
+ if (run?.flagged) return false;
17206
+ }
17207
+ return classifier !== void 0 && from !== void 0 && to !== void 0 && from.mediaTimescale === to.mediaTimescale && classifier.keyframeFreeBetween(mpu, from.decodeTime, to.decodeTime, from.mediaTimescale);
16472
17208
  }
16473
17209
  /** A block's class now, or frozen at its resolution. */
16474
17210
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -16491,9 +17227,11 @@ var FECManager = class _FECManager {
16491
17227
  }
16492
17228
  /**
16493
17229
  * Record a RAP frame released in order, for the classifier's RAP-spacing
16494
- * invariant (consecutive MPUs exactly one keyframe interval apart).
17230
+ * invariant (consecutive MPUs exactly one keyframe interval apart) and,
17231
+ * with its decode time, as the MPU start gap decisions measure the catalog
17232
+ * keyframe interval from (mpuBoundsRapsFor).
16495
17233
  */
16496
- noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
17234
+ noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale, decodeTime) {
16497
17235
  if (!this.#trackConfigs.has(packetId)) return;
16498
17236
  if (!this.#hasCatalogTimingForPacket(packetId)) {
16499
17237
  const streamKey = this.#streamKey(packetId, catalogTrackName);
@@ -16508,7 +17246,8 @@ var FECManager = class _FECManager {
16508
17246
  this.#classifierFor(packetId, catalogTrackName).noteReleasedRap(
16509
17247
  mpu,
16510
17248
  presentationTime,
16511
- mediaTimescale
17249
+ mediaTimescale,
17250
+ decodeTime
16512
17251
  )
16513
17252
  );
16514
17253
  }
@@ -17059,7 +17798,10 @@ var FECManager = class _FECManager {
17059
17798
  this.#layerAnchorHorizon(packetId),
17060
17799
  this.#sourceFrontiers.get(streamKey)?.sbn
17061
17800
  );
17062
- if (verdict === "discard") return false;
17801
+ if (verdict === "discard") {
17802
+ this.#unlistedRepairTrackRefusals++;
17803
+ return false;
17804
+ }
17063
17805
  if (verdict !== void 0) {
17064
17806
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName);
17065
17807
  return false;
@@ -17208,15 +17950,17 @@ var FECManager = class _FECManager {
17208
17950
  * its sources in send order, so one that moves the stream's newest source
17209
17951
  * position past a block leaves the sources that block still misses
17210
17952
  * reordered behind it at best: it shortens the wait of every block it
17211
- * passed that only a late source can complete. MoQ is left out: its streams
17212
- * can overtake one another, so a MoQ source shows nothing about the sources
17213
- * sent before it.
17953
+ * passed that only a late source can complete. Reliable MoQ is left out:
17954
+ * its streams can overtake one another, so a MoQ source shows nothing
17955
+ * about the sources sent before it. An "mfu-datagram" leg is in: its
17956
+ * datagrams leave the publisher in send order and reorder only within the
17957
+ * path's tolerance, as multicast does.
17214
17958
  */
17215
17959
  #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
17216
17960
  const previous = locator.newestSource;
17217
17961
  if (!locator.noteSource(ssId) || previous === void 0) return;
17218
17962
  for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
17219
- if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17963
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17220
17964
  this.#shortenUnrecoverableWait(
17221
17965
  this.#blockKey(block.start, packetId, catalogTrackName),
17222
17966
  block.start,
@@ -17234,21 +17978,61 @@ var FECManager = class _FECManager {
17234
17978
  * covers repair symbols paced after its sources, buys it nothing: it waits
17235
17979
  * the late-symbol allowance alone, the multicast wait less the span (the
17236
17980
  * catalog tolerance or the measured delivery gap). Undefined for any other
17237
- * block.
17981
+ * block. While a keyframe overlay is installed, the block waits for its
17982
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
17983
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
17984
+ * resolution is what releases the frames behind it, and failing it early
17985
+ * released them past a keyframe the overlay was still rebuilding, which
17986
+ * then arrived stale. The release gate lets them go instead
17987
+ * (isoRepairlessWaitMs).
17238
17988
  */
17239
17989
  #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
17990
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
17240
17991
  const authoredLength = this.#blockAuthoredLengths.get(key);
17241
- const rsbLength = this.#blockRsbLengths.get(key);
17242
- if (authoredLength === void 0 || rsbLength === void 0) return void 0;
17243
- let present = this.#blockSourceCounts.get(key) ?? 0;
17244
- const received = this.#blockSourceEsis.get(key);
17245
- for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
17246
- if (present + rsbLength >= authoredLength) return void 0;
17247
17992
  const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
17248
17993
  if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
17249
17994
  return void 0;
17250
17995
  }
17251
- return this.#multicastWaitMs(config) - config.interleaveDepthMs;
17996
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
17997
+ }
17998
+ /**
17999
+ * A repair stated the block, and its sources plus every symbol its repair
18000
+ * group carries (RSB_length) are short of its SSB_length.
18001
+ */
18002
+ #groupCannotComplete(key) {
18003
+ const authoredLength = this.#blockAuthoredLengths.get(key);
18004
+ const rsbLength = this.#blockRsbLengths.get(key);
18005
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
18006
+ let present = this.#blockSourceCounts.get(key) ?? 0;
18007
+ const received = this.#blockSourceEsis.get(key);
18008
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
18009
+ return present + rsbLength < authoredLength;
18010
+ }
18011
+ /**
18012
+ * How long a loss only a late source or an installed keyframe overlay can
18013
+ * still fill waits once a later source passed it: the late-symbol
18014
+ * allowance alone (the multicast wait less the span) while no overlay is
18015
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
18016
+ * RAP packet the loss took: a second FEC instance over the same packets
18017
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
18018
+ * span, unrelated to the base's. That packet can complete a stated block
18019
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
18020
+ * first lets the release gate pass the keyframe, whose rebuild then lands
18021
+ * stale. The overlay repair of a packet the loss took goes out within the
18022
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
18023
+ * sent after it, so the loss waits that span plus the larger of the
18024
+ * allowance and the overlay's own tolerance. An overlay that states no
18025
+ * span (its block may then span keyframes), or one whose wait is not
18026
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
18027
+ */
18028
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
18029
+ const waitMs = this.#multicastWaitMs(config);
18030
+ const allowanceMs = waitMs - config.interleaveDepthMs;
18031
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
18032
+ if (overlay === void 0) return allowanceMs;
18033
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
18034
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
18035
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
17252
18036
  }
17253
18037
  /**
17254
18038
  * Bring an open block's wait in to its late-source wait, when it has one.
@@ -17637,7 +18421,7 @@ var FECManager = class _FECManager {
17637
18421
  blockDeliveryProvenance(sbn, packetId, catalogTrackName) {
17638
18422
  const counts = this.blockPathCount(sbn, packetId, catalogTrackName);
17639
18423
  if (!counts) return "unknown";
17640
- if (counts.moqSymbols > 0) return "mixed";
18424
+ if (counts.moqSymbols > 0 || counts.datagramSymbols > 0) return "mixed";
17641
18425
  if (counts.multicastSymbols > 0) return "multicast";
17642
18426
  return "unknown";
17643
18427
  }
@@ -17664,7 +18448,7 @@ var FECManager = class _FECManager {
17664
18448
  this.#activeBlockDeadlinesMs.clear();
17665
18449
  this.#blockWaitDeadlinesMs.clear();
17666
18450
  this.#repairHoldUntilMs.clear();
17667
- this.#deliveryGaps.reset();
18451
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.reset();
17668
18452
  this.#pendingWorkerCleanups.clear();
17669
18453
  this.#pendingWorkerCleanupClients.clear();
17670
18454
  for (const bound of this.#pendingWorkerCleanupBounds.values()) clearTimeout(bound.handle);
@@ -17715,6 +18499,7 @@ var FECManager = class _FECManager {
17715
18499
  this.#highestSbn.clear();
17716
18500
  this.#sourceFrontiers.clear();
17717
18501
  this.#isoLocators.clear();
18502
+ this.#runAnchors.clear();
17718
18503
  this.#sourceAnchors.clear();
17719
18504
  this.#trackConfigs.clear();
17720
18505
  this.#fecDecoders.clear();
@@ -18889,7 +19674,7 @@ var FecReleaseSequencer = class {
18889
19674
  from
18890
19675
  );
18891
19676
  unresolved = resolved === null;
18892
- if (unresolved && !this.#cursorPassed(stream, asUnanchored)) {
19677
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
18893
19678
  const heldMs = performance.now() - head.arrivedAtMs;
18894
19679
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
18895
19680
  this.#recordStat("forcedWindowFlushes");
@@ -18907,6 +19692,19 @@ var FecReleaseSequencer = class {
18907
19692
  );
18908
19693
  }
18909
19694
  }
19695
+ /**
19696
+ * The head has waited out a gap only a late source can still fill
19697
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
19698
+ * the stream when it has (`wakeAt`), since no packet may come by then.
19699
+ */
19700
+ #unrepairableWaitOver(stream, last, head, from, to) {
19701
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
19702
+ if (waitMs === void 0) return false;
19703
+ const atMs = head.arrivedAtMs + waitMs;
19704
+ if (performance.now() >= atMs) return true;
19705
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
19706
+ return false;
19707
+ }
18910
19708
  /**
18911
19709
  * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
18912
19710
  * source cursor holds it unanchored, and neither does a later frame behind
@@ -21172,12 +21970,12 @@ function validPort(value) {
21172
21970
  return Number.isInteger(value) && value >= 0 && value <= 65535;
21173
21971
  }
21174
21972
  function parseIpv42(address) {
21175
- const fields = address.split(".");
21176
- if (fields.length !== 4 || fields.some((field) => !/^\d+$/.test(field))) {
21973
+ const fields2 = address.split(".");
21974
+ if (fields2.length !== 4 || fields2.some((field) => !/^\d+$/.test(field))) {
21177
21975
  throw new Error(`invalid IPv4 address ${address}`);
21178
21976
  }
21179
- const values = fields.map(Number);
21180
- if (values.some((value, index) => value > 255 || String(value) !== fields[index])) {
21977
+ const values = fields2.map(Number);
21978
+ if (values.some((value, index) => value > 255 || String(value) !== fields2[index])) {
21181
21979
  throw new Error(`invalid IPv4 address ${address}`);
21182
21980
  }
21183
21981
  return Uint8Array.from(values);
@@ -21391,7 +22189,7 @@ function bitLen(n) {
21391
22189
  return len;
21392
22190
  }
21393
22191
  var bitMask = (n) => (_1n << BigInt(n)) - _1n;
21394
- function _validateObject(object2, fields, optFields = {}) {
22192
+ function _validateObject(object2, fields2, optFields = {}) {
21395
22193
  if (!object2 || typeof object2 !== "object")
21396
22194
  throw new Error("expected valid options object");
21397
22195
  function checkField2(fieldName, expectedType, isOpt) {
@@ -21402,7 +22200,7 @@ function _validateObject(object2, fields, optFields = {}) {
21402
22200
  if (current !== expectedType || val === null)
21403
22201
  throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
21404
22202
  }
21405
- Object.entries(fields).forEach(([k, v]) => checkField2(k, v, false));
22203
+ Object.entries(fields2).forEach(([k, v]) => checkField2(k, v, false));
21406
22204
  Object.entries(optFields).forEach(([k, v]) => checkField2(k, v, true));
21407
22205
  }
21408
22206
  var notImplemented = () => {
@@ -23383,6 +24181,20 @@ var MmtpRouter = class {
23383
24181
  /** The flow whose receiver admitted a stream's source datagrams, by packetId then catalog track name: recovered packets answer to it. */
23384
24182
  #provenanceStreamFlow = /* @__PURE__ */ new Map();
23385
24183
  #unregisteredFlowDrops = 0;
24184
+ /** "mfu-datagram" leg packets of a packet id the ingress does not name (never the signaling flow). */
24185
+ #datagramLegIngressDrops = 0;
24186
+ /** "mfu-datagram" leg packets of the signaling flow (packet id 0): expected, one per group. */
24187
+ #datagramLegSignalingPackets = 0;
24188
+ /**
24189
+ * The streams a live "mfu-datagram" leg has fed, catalog track names by
24190
+ * packet id: their ledgers and release gate take the leg's bounds. A stream
24191
+ * leaves when its leg does: `endDatagramLeg`, `resetTrack`, `dispose`, or
24192
+ * the first multicast packet of its packet id (the ordered switch retires
24193
+ * the leg first). The "mfu" sibling shares the packet id, never the name.
24194
+ */
24195
+ #datagramLegStreams = /* @__PURE__ */ new Map();
24196
+ /** The leg's presentation budget (setDatagramLegPresentationBudget), or null: no presentation bound. */
24197
+ #datagramLegPresentationBudgetMs = null;
23386
24198
  #ambiguousRecoveredDrops = 0;
23387
24199
  // Temp state set by #processMMTP before calling parser.feed(),
23388
24200
  // read by the parser's onFrame callback for CMAF assembly + dedup.
@@ -23488,6 +24300,8 @@ var MmtpRouter = class {
23488
24300
  // end: a synchronous recovery completes its block BEFORE routing the
23489
24301
  // recovered frames, and releasing a held gap in between would strand them.
23490
24302
  #fecPokeDepth = 0;
24303
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
24304
+ #fecWakes = /* @__PURE__ */ new Map();
23491
24305
  #pendingFecPokes = /* @__PURE__ */ new Map();
23492
24306
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
23493
24307
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -23756,10 +24570,11 @@ var MmtpRouter = class {
23756
24570
  const blockLifetimeMs = fec.blockLifetimeMsForPacket(packetId);
23757
24571
  if (blockSpanMs === void 0 || blockLifetimeMs === void 0) return NO_FEC_GEOMETRY_HORIZON;
23758
24572
  if (blockSpanMs === 0) return NO_BLOCK_SPAN_HORIZON;
23759
- return {
23760
- kind: "fec-horizon",
23761
- retentionMs: duplicateRetentionMs({ blockSpanMs, blockLifetimeMs })
23762
- };
24573
+ let retentionMs = duplicateRetentionMs({ blockSpanMs, blockLifetimeMs });
24574
+ if (this.#datagramLegStreams.has(packetId)) {
24575
+ retentionMs = Math.max(retentionMs, fec.datagramLegLedgerRetentionMsForPacket?.(packetId) ?? 0);
24576
+ }
24577
+ return { kind: "fec-horizon", retentionMs };
23763
24578
  }
23764
24579
  /**
23765
24580
  * Init segments rejected since construction because their packetId had no
@@ -24182,7 +24997,7 @@ var MmtpRouter = class {
24182
24997
  const blockStart = placement.block.start;
24183
24998
  if (placement.span !== void 0) this.#replayOverlaySources(inst, placement.span.block.start, placement.span.placed);
24184
24999
  this.#replayOverlaySources(inst, blockStart, placement.placed);
24185
- if (source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
25000
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
24186
25001
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
24187
25002
  const recovered = fec.feedRepairSymbol(pid, repair.ssStart, repair.ssbLength, repair.rsId, repair.symbolData, name);
24188
25003
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, blockStart, recovered);
@@ -24190,7 +25005,7 @@ var MmtpRouter = class {
24190
25005
  #replayOverlaySources(inst, blockStart, placed) {
24191
25006
  const { fec, repairPacketId: pid, streamName: name } = inst;
24192
25007
  for (const { ssId, payload } of placed) {
24193
- if (payload.source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
25008
+ if (payload.source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
24194
25009
  if (payload.oversized) continue;
24195
25010
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
24196
25011
  const recovered = fec.feedSourceSymbol(pid, ssId, payload.symbolData, name);
@@ -24243,7 +25058,7 @@ var MmtpRouter = class {
24243
25058
  });
24244
25059
  continue;
24245
25060
  }
24246
- if (source === "moq") this.#noteOverlayMoqBlock(inst, coords.sbn);
25061
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, coords.sbn);
24247
25062
  if (oversized) continue;
24248
25063
  const alreadyCompleted = fec.isBlockCompleted(coords.sbn, pid, name);
24249
25064
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
@@ -24832,6 +25647,46 @@ var MmtpRouter = class {
24832
25647
  get unregisteredFlowDropCount() {
24833
25648
  return this.#unregisteredFlowDrops;
24834
25649
  }
25650
+ /** "mfu-datagram" leg packets dropped because the leg's ingress does not name their packet id (packet id 0 apart). */
25651
+ get datagramLegIngressDropCount() {
25652
+ return this.#datagramLegIngressDrops;
25653
+ }
25654
+ /** "mfu-datagram" leg packets of the MMTP signaling flow (packet id 0), which no track owns. */
25655
+ get datagramLegSignalingPacketCount() {
25656
+ return this.#datagramLegSignalingPackets;
25657
+ }
25658
+ /**
25659
+ * The "mfu-datagram" leg's presentation bound (mmt-02 6.1 step 6): how
25660
+ * long after a frame arrives it must leave the release gate when the gap
25661
+ * before it holds no RAP, FT=0 or FT=1 data (the player's presentation
25662
+ * delay less its decode lead). The gap is then decided at the earlier of
25663
+ * the FEC block deadline and this bound; a gap that may hold a RAP keeps
25664
+ * the block deadline. Null, or a value that is not finite and positive:
25665
+ * the block deadline alone, as on multicast.
25666
+ */
25667
+ setDatagramLegPresentationBudget(budgetMs) {
25668
+ this.#datagramLegPresentationBudgetMs = budgetMs;
25669
+ }
25670
+ /**
25671
+ * The "mfu-datagram" leg is over (unsubscribed, or switched to another
25672
+ * path): no stream keeps its presentation bound or its ledger retention.
25673
+ * Parser, FEC and ledger state stay, so the packet ids continue on the
25674
+ * next path without an epoch. A later leg datagram starts a leg again.
25675
+ */
25676
+ endDatagramLeg() {
25677
+ this.#datagramLegStreams.clear();
25678
+ this.#datagramLegPresentationBudgetMs = null;
25679
+ }
25680
+ #datagramLegPresentationWaitMs(packetId, catalogTrackName) {
25681
+ if (this.#datagramLegPresentationBudgetMs === null || this.#datagramLegStreams.get(packetId)?.has(catalogTrackName) !== true) return void 0;
25682
+ let budgetMs;
25683
+ try {
25684
+ budgetMs = this.#datagramLegPresentationBudgetMs(packetId, catalogTrackName);
25685
+ } catch {
25686
+ return void 0;
25687
+ }
25688
+ return Number.isFinite(budgetMs) && budgetMs > 0 ? budgetMs : void 0;
25689
+ }
24835
25690
  /** Recovered packets dropped because more than one protected flow could own their stream. */
24836
25691
  get ambiguousRecoveredDropCount() {
24837
25692
  return this.#ambiguousRecoveredDrops;
@@ -24849,6 +25704,10 @@ var MmtpRouter = class {
24849
25704
  * caller that forgot it silently attributed its bytes to a multicast socket
24850
25705
  * they may never have crossed — and that attribution is what the physical-
24851
25706
  * delivery evidence path is built on. Absence is not multicast; say which.
25707
+ * `"moq-datagram"` is an "mfu-datagram" subscription (MmtpIngestSource):
25708
+ * `ingress.tracks` MUST name the datagram catalog track for its packet id,
25709
+ * and a packet of a packet id it does not name is dropped and counted
25710
+ * (`datagramLegIngressDropCount`; the signaling flow, packet id 0, apart).
24852
25711
  */
24853
25712
  feedPacket(packet, source, ingress) {
24854
25713
  if (this.#disposed) return;
@@ -24898,15 +25757,18 @@ var MmtpRouter = class {
24898
25757
  }
24899
25758
  /**
24900
25759
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
24901
- * header and delegates to FECManager for FEC recovery.
25760
+ * header and delegates to FECManager for FEC recovery. `source` is
25761
+ * `"moq-datagram"` for a repair object of an "mfu-datagram" track's repair
25762
+ * track, which arrives as a datagram and so counts as an in-band symbol of
25763
+ * the leg; a FETCHed repair stays `"moq"` (RepairVia `quic`).
24902
25764
  */
24903
- feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
25765
+ feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source = "moq") {
24904
25766
  if (this.#disposed) return;
24905
25767
  this.#withDeferredFecPokes(() => {
24906
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
25768
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source);
24907
25769
  });
24908
25770
  }
24909
- #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, admitted = false) {
25771
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source, admitted = false) {
24910
25772
  let header;
24911
25773
  try {
24912
25774
  header = parseMMTPHeader(packet);
@@ -24916,7 +25778,7 @@ var MmtpRouter = class {
24916
25778
  const repairPacketId = header.packetId;
24917
25779
  const overlay = this.#overlayRepairTarget(repairPacketId, repairTrackName);
24918
25780
  if (overlay !== void 0) {
24919
- this.#routeOverlayRepair(overlay, repairPacketId, packet, header, "moq");
25781
+ this.#routeOverlayRepair(overlay, repairPacketId, packet, header, source);
24920
25782
  return;
24921
25783
  }
24922
25784
  const hintedOwner = ownerPacketIdHint != null && this.#classifyPacketId(ownerPacketIdHint) !== null ? ownerPacketIdHint : null;
@@ -24928,7 +25790,7 @@ var MmtpRouter = class {
24928
25790
  }
24929
25791
  let unlisted = false;
24930
25792
  if (ownerPacketId != null && !admitted) {
24931
- const admit = this.#admitUnicast(repairPacketId, packet, () => this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, true));
25793
+ const admit = this.#admitUnicast(repairPacketId, packet, () => this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source, true));
24932
25794
  if (admit === "held" || admit === "dropped") return;
24933
25795
  unlisted = admit === "unlisted";
24934
25796
  }
@@ -24949,7 +25811,7 @@ var MmtpRouter = class {
24949
25811
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
24950
25812
  return;
24951
25813
  }
24952
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
25814
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, source, repairTrackName);
24953
25815
  }
24954
25816
  }
24955
25817
  // ── Packet FEC geometry and block profile ───────────────────────
@@ -25154,6 +26016,7 @@ var MmtpRouter = class {
25154
26016
  debugRouter(
25155
26017
  `[MmtpRouter] Dropping repair packet pid=${packetId}: physical PID is unregistered`
25156
26018
  );
26019
+ this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
25157
26020
  return null;
25158
26021
  }
25159
26022
  const registeredOwners = this.#repairOwnersByPacketId.get(packetId) ?? /* @__PURE__ */ new Set();
@@ -25162,6 +26025,7 @@ var MmtpRouter = class {
25162
26025
  debugRouter(
25163
26026
  `[MmtpRouter] Dropping repair packet pid=${packetId}: catalog owner is ${owners.length === 0 ? "absent" : "ambiguous"}`
25164
26027
  );
26028
+ this.#fecManager?.countUnresolvedRepairOwner?.(owners.length === 0 ? "ownerAbsent" : "ownerAmbiguous");
25165
26029
  return null;
25166
26030
  }
25167
26031
  /** Route a recovered FEC block through the parser + dedup pipeline.
@@ -25211,6 +26075,8 @@ var MmtpRouter = class {
25211
26075
  }
25212
26076
  this.#parser.resetTrack(packetId, catalogTrackName);
25213
26077
  this.resetKeyframeOverlays(packetId, catalogTrackName);
26078
+ const legNames = this.#datagramLegStreams.get(packetId);
26079
+ if (legNames?.delete(catalogTrackName) && legNames.size === 0) this.#datagramLegStreams.delete(packetId);
25214
26080
  this.#restampedStreams.delete(this.#mediaStreamKey(packetId, catalogTrackName));
25215
26081
  const assistPrefix = assistKey(packetId, catalogTrackName, 0).slice(0, -1);
25216
26082
  for (const key of this.#assistBlocks.keys()) if (key.startsWith(assistPrefix)) this.#assistBlocks.delete(key);
@@ -25548,8 +26414,11 @@ var MmtpRouter = class {
25548
26414
  this.#disposed = true;
25549
26415
  this.#staged = null;
25550
26416
  this.cancelKeyframeLostTimer();
26417
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
26418
+ this.#fecWakes.clear();
25551
26419
  this.#parser.dispose();
25552
26420
  this.#streams.clear();
26421
+ this.endDatagramLeg();
25553
26422
  this.#trackPacketCallbacks.clear();
25554
26423
  this.#latestVideoSeqByStream.clear();
25555
26424
  this.#lastDirectSourceVideoTsByStream.clear();
@@ -25729,6 +26598,38 @@ var MmtpRouter = class {
25729
26598
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
25730
26599
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
25731
26600
  },
26601
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
26602
+ // late source can), its frame waits the late-symbol allowance when the
26603
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
26604
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
26605
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
26606
+ // unless the gap holds a stated block's loss: the overlay may rebuild
26607
+ // that MPU's FT=0, and the block's group then complete it), or
26608
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
26609
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
26610
+ // overlay protects) waits for that overlay's repair too (BLO-52085
26611
+ // D4). A run no repair has delimited instead waits for its FEC
26612
+ // deadline, whatever the decision (FECManager.isoRepairlessWaitMs). The
26613
+ // FEC check comes first: most held gaps are not behind such a span, and
26614
+ // deciding one scans both frames' bitstreams.
26615
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
26616
+ const fec = this.#fecManager;
26617
+ const { packetId, catalogTrackName } = after.meta;
26618
+ const arrivedAtMs = after.arrivedAtMs;
26619
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, false, arrivedAtMs);
26620
+ const presentationMs = this.#datagramLegPresentationWaitMs(packetId, catalogTrackName);
26621
+ if (!fec || allowanceMs === void 0 && presentationMs === void 0) return void 0;
26622
+ const decision = this.#decideGap(before, after, [], false);
26623
+ const mpu = before.meta.mpuSequenceNumber;
26624
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
26625
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
26626
+ return allowanceMs === void 0 ? void 0 : fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true, false, arrivedAtMs);
26627
+ }
26628
+ const waitMs = allowanceMs === void 0 ? void 0 : decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true, arrivedAtMs) : allowanceMs;
26629
+ if (decision.reason === "delta-lost" && !((fec.interleaveDepthMsForPacket?.(packetId) ?? 0) > 0)) return waitMs;
26630
+ if (presentationMs === void 0) return waitMs;
26631
+ return waitMs === void 0 ? presentationMs : Math.min(waitMs, presentationMs);
26632
+ },
25732
26633
  decide: (before, after, lostBlocks, discontinuity) => {
25733
26634
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
25734
26635
  this.#onFrameGap?.(decision);
@@ -25738,6 +26639,20 @@ var MmtpRouter = class {
25738
26639
  onRap: (packetId, catalogTrackName, ssId) => {
25739
26640
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
25740
26641
  },
26642
+ // One timer per stream, at the earliest wake asked: its drain re-arms
26643
+ // for the next frame still waiting.
26644
+ wakeAt: (packetId, catalogTrackName, atMs) => {
26645
+ if (this.#disposed) return;
26646
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
26647
+ const armed = this.#fecWakes.get(key);
26648
+ if (armed !== void 0 && armed.atMs <= atMs) return;
26649
+ if (armed !== void 0) clearTimeout(armed.timer);
26650
+ const timer = setTimeout(() => {
26651
+ this.#fecWakes.delete(key);
26652
+ this.#requestFecPoke(packetId, catalogTrackName);
26653
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
26654
+ this.#fecWakes.set(key, { atMs, timer });
26655
+ },
25741
26656
  // A staged switch commits on when each side's frames reach it
25742
26657
  // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
25743
26658
  // they did unanchored.
@@ -25755,7 +26670,8 @@ var MmtpRouter = class {
25755
26670
  meta.catalogTrackName,
25756
26671
  meta.mpuSequenceNumber,
25757
26672
  timing.presentationTime,
25758
- timing.mediaTimescale
26673
+ timing.mediaTimescale,
26674
+ timing.decodeTime
25759
26675
  );
25760
26676
  }
25761
26677
  };
@@ -25773,8 +26689,20 @@ var MmtpRouter = class {
25773
26689
  #decideGap(before, after, lostBlocks, discontinuity) {
25774
26690
  const { packetId, catalogTrackName } = after.meta;
25775
26691
  const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
25776
- const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying";
25777
- const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
26692
+ const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying" && before.meta.movieFragmentSequenceNumber === after.meta.movieFragmentSequenceNumber;
26693
+ const mpu = before.meta.mpuSequenceNumber;
26694
+ const sameMpu = trackKind === "video" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu;
26695
+ const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(
26696
+ packetId,
26697
+ catalogTrackName,
26698
+ sameMpu ? {
26699
+ mpu,
26700
+ from: before.meta.authoredTiming,
26701
+ to: after.meta.authoredTiming,
26702
+ fromSsId: before.meta.fecSbn,
26703
+ toSsId: after.meta.fecSbnFirst ?? after.meta.fecSbn
26704
+ } : void 0
26705
+ ) === true;
25778
26706
  const evidence = (frame) => {
25779
26707
  const timing = frame.meta.authoredTiming;
25780
26708
  const sampleNumber = frame.meta.sampleNumber;
@@ -25890,18 +26818,34 @@ var MmtpRouter = class {
25890
26818
  if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
25891
26819
  if (source === "multicast" && !manifestAdmitted) {
25892
26820
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
26821
+ } else if (source === "moq-datagram" && !manifestAdmitted) {
26822
+ this.#fecManager?.noteArrival?.("moq-datagram", info.packetId, info.sequenceNumber);
25893
26823
  }
25894
- if (source === "multicast" && !ingressHasPacketId(ingress, info.packetId)) {
26824
+ if (source !== "moq" && !ingressHasPacketId(ingress, info.packetId)) {
26825
+ if (source === "moq-datagram") {
26826
+ if (info.packetId === MMTP_SIGNALING_PACKET_ID) this.#datagramLegSignalingPackets++;
26827
+ else this.#datagramLegIngressDrops++;
26828
+ }
25895
26829
  debugRouter(
25896
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: absent from ingress tracks`
26830
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: absent from ingress tracks`
25897
26831
  );
25898
26832
  return;
25899
26833
  }
26834
+ if (source === "moq-datagram") {
26835
+ if (!info.isRepair) {
26836
+ let names = this.#datagramLegStreams.get(info.packetId);
26837
+ if (!names) this.#datagramLegStreams.set(info.packetId, names = /* @__PURE__ */ new Set());
26838
+ names.add(catalogTrackNameForPacket(ingress, info.packetId));
26839
+ }
26840
+ } else if (source === "multicast") {
26841
+ this.#datagramLegStreams.delete(info.packetId);
26842
+ }
25900
26843
  const packetRole = this.#packetIdRoles.get(info.packetId);
25901
- if (source === "multicast" && this.#classifyPacketId(info.packetId) === null && (!info.isRepair || packetRole !== "repair")) {
26844
+ if (source !== "moq" && this.#classifyPacketId(info.packetId) === null && (!info.isRepair || packetRole !== "repair")) {
25902
26845
  debugRouter(
25903
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: physical PID is unregistered`
26846
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: physical PID is unregistered`
25904
26847
  );
26848
+ if (info.isRepair) this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
25905
26849
  return;
25906
26850
  }
25907
26851
  if (!info.isRepair && hasAmbiguousCatalogTrackName(ingress, info.packetId)) {
@@ -25937,7 +26881,7 @@ var MmtpRouter = class {
25937
26881
  }
25938
26882
  return;
25939
26883
  }
25940
- if (source === "moq" && !manifestAdmitted) {
26884
+ if (source !== "multicast" && !manifestAdmitted) {
25941
26885
  const admit = this.#admitUnicast(info.packetId, packet, () => this.#processMMTP(packet, source, true, ingress, overlapCopy, true), overlapCopy);
25942
26886
  if (admit !== "unlisted") {
25943
26887
  if (admit === "admitted") this.#processMMTP(packet, source, true, ingress, overlapCopy);
@@ -25966,7 +26910,7 @@ var MmtpRouter = class {
25966
26910
  );
25967
26911
  if (!repair) return;
25968
26912
  if (ownerPacketId != null && this.#fecManager) {
25969
- if ((flowless && this.#userAgentGoverns(ownerPacketId) || source === "moq" && !manifestAdmitted) && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)) return;
26913
+ if ((flowless && this.#userAgentGoverns(ownerPacketId) || source !== "multicast" && !manifestAdmitted) && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)) return;
25970
26914
  this.#repairPidCounts[info.packetId] = (this.#repairPidCounts[info.packetId] || 0) + 1;
25971
26915
  const count = this.#repairPidCounts[info.packetId];
25972
26916
  if (count <= 2 || count % 500 === 0) {
@@ -26005,7 +26949,7 @@ var MmtpRouter = class {
26005
26949
  const fecSource = this.#fecManager !== null && fecPayloadId != null;
26006
26950
  const coords = fecSource && fecPayloadId ? this.#locateFecSource(info.packetId, catalogTrackName, fecPayloadId.ssId) ?? void 0 : void 0;
26007
26951
  duplicates.advance(coords?.sbn);
26008
- if (source === "multicast" && !overlapCopy && !releasedFromQuarantine && catalogTrackName !== void 0 && duplicates.predatesHorizon(info.sequenceNumber, fecPayloadId?.ssId)) {
26952
+ if (source !== "moq" && !overlapCopy && !releasedFromQuarantine && catalogTrackName !== void 0 && duplicates.predatesHorizon(info.sequenceNumber, fecPayloadId?.ssId)) {
26009
26953
  this.#publisherRestarts++;
26010
26954
  console.warn(
26011
26955
  `[MmtpRouter] publisher restart on pid=${info.packetId} track=${catalogTrackName}: packet_sequence_number=${info.sequenceNumber} predates the stream's FEC horizon; starting a new epoch`
@@ -26066,6 +27010,7 @@ var MmtpRouter = class {
26066
27010
  evidence: sourceSymbolEvidence(packet, parsed.header, info.rapFlag, info.sequenceNumber),
26067
27011
  oversized: !(this.#fecManager.isoSourceFits?.(info.packetId, rawSymbol.length) ?? false)
26068
27012
  }) ?? false;
27013
+ if (held) this.#requestFecPoke(info.packetId, catalogTrackName);
26069
27014
  parseSourceSymbol = held && !duplicates.parsedSymbols.has(ssId);
26070
27015
  }
26071
27016
  } else if (fecUnreadable && info.fecPayloadId) {
@@ -26193,7 +27138,9 @@ var MmtpRouter = class {
26193
27138
  const feedOptions = {
26194
27139
  skipFecPayloadId: parserOptions?.skipFecPayloadId,
26195
27140
  recovered: parserOptions?.recovered,
26196
- source: parserOptions?.source,
27141
+ // Frame attribution is the transport path: an "mfu-datagram" object
27142
+ // crossed QUIC, so its frames are 'moq' (provenance 'mixed').
27143
+ source: parserOptions?.source === "moq-datagram" ? "moq" : parserOptions?.source,
26197
27144
  deliveryProvenance: parserOptions?.deliveryProvenance,
26198
27145
  catalogTrackName: parserOptions?.catalogTrackName,
26199
27146
  ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
@@ -27453,14 +28400,14 @@ function createWasmMmtpContainerParser(config) {
27453
28400
  var JOIN_SUCCEEDED = Object.freeze({ ok: true });
27454
28401
  function providerErrorOf(error) {
27455
28402
  if (typeof error !== "object" || error === null) return void 0;
27456
- const fields = error;
28403
+ const fields2 = error;
27457
28404
  let name;
27458
28405
  let message;
27459
28406
  let code;
27460
28407
  try {
27461
- name = fields.name;
27462
- message = fields.message;
27463
- code = fields.code;
28408
+ name = fields2.name;
28409
+ message = fields2.message;
28410
+ code = fields2.code;
27464
28411
  } catch {
27465
28412
  return void 0;
27466
28413
  }
@@ -28358,6 +29305,7 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
28358
29305
  stalls: 0,
28359
29306
  concealedBlocks: 0,
28360
29307
  concealedGaps: 0,
29308
+ undelimitedRunGaps: 0,
28361
29309
  concealedFrames: 0,
28362
29310
  concealedAudioMs: 0,
28363
29311
  vanishedBlocks: 0
@@ -28701,6 +29649,8 @@ var MulticastManager = class {
28701
29649
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
28702
29650
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
28703
29651
  #repairReleases = /* @__PURE__ */ new Map();
29652
+ /** Protected repair flows owned by each live repair-endpoint release. */
29653
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
28704
29654
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
28705
29655
  #overlayBindings = /* @__PURE__ */ new Map();
28706
29656
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -28862,9 +29812,17 @@ var MulticastManager = class {
28862
29812
  reason
28863
29813
  });
28864
29814
  };
29815
+ this.#fec.onUndelimitedRunGap = (packetId, catalogTrackName) => {
29816
+ this.#statsFor(packetId, catalogTrackName).undelimitedRunGaps++;
29817
+ };
28865
29818
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
28866
29819
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
28867
29820
  };
29821
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
29822
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
29823
+ if (binding === void 0) return void 0;
29824
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
29825
+ };
28868
29826
  this.#fec.onDecoderUnavailable = (event) => {
28869
29827
  this.#emitRepairLifecycle({
28870
29828
  version: 2,
@@ -29161,6 +30119,7 @@ var MulticastManager = class {
29161
30119
  assertPositiveGeometry("timescale", config.timescale);
29162
30120
  assertPositiveGeometry("keyframeIntervalTicks", config.keyframeIntervalTicks);
29163
30121
  assertPositiveGeometry("keyframeIntervalMs", config.keyframeIntervalMs);
30122
+ assertPositiveGeometry("groupDurationMs", config.groupDurationMs);
29164
30123
  assertNonNegativeGeometry("fecRepairSymbols", config.fecRepairSymbols);
29165
30124
  assertNonNegativeGeometry(
29166
30125
  "fecReorderToleranceMs",
@@ -29193,7 +30152,8 @@ var MulticastManager = class {
29193
30152
  timeoutMs: deliveryWindowMs,
29194
30153
  ...trackKind === void 0 ? {} : { trackKind },
29195
30154
  ...config.codec === void 0 ? {} : { codec: config.codec },
29196
- ...geometry2 === void 0 ? {} : { geometry: geometry2 }
30155
+ ...geometry2 === void 0 ? {} : { geometry: geometry2 },
30156
+ ...config.groupDurationMs === void 0 ? {} : { groupDurationMs: config.groupDurationMs }
29197
30157
  };
29198
30158
  this.#fec.configureTrack(packetId, fecConfig, catalogTrackName);
29199
30159
  this.#configureTrackMapper(packetId, fecConfig);
@@ -29367,6 +30327,9 @@ var MulticastManager = class {
29367
30327
  this.#transport.onFailback((reason) => {
29368
30328
  const joined = this.#provenanceJoin;
29369
30329
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
30330
+ for (const flows of this.#repairProvenanceFlows.values()) {
30331
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
30332
+ }
29370
30333
  this.#onFailback?.(reason);
29371
30334
  });
29372
30335
  }
@@ -29401,6 +30364,12 @@ var MulticastManager = class {
29401
30364
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
29402
30365
  );
29403
30366
  }
30367
+ if (provenanceFlow !== void 0) {
30368
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
30369
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
30370
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
30371
+ }
30372
+ }
29404
30373
  const staged = this.#renditionSwitch;
29405
30374
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
29406
30375
  this.configureFec(config);
@@ -29408,8 +30377,8 @@ var MulticastManager = class {
29408
30377
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
29409
30378
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
29410
30379
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
29411
- this.#releaseProvenanceJoin();
29412
30380
  const provenance = config.provenance;
30381
+ this.#releaseProvenanceJoin();
29413
30382
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
29414
30383
  const ingress = protectedTracks === void 0 ? void 0 : {
29415
30384
  tracks: Object.freeze(
@@ -29462,8 +30431,13 @@ var MulticastManager = class {
29462
30431
  * feeds the flow's receiver; media datagrams are held until one admits them.
29463
30432
  */
29464
30433
  #joinProvenance(provenance, ingress) {
30434
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
30435
+ this.#hookFailback();
30436
+ this.#provenanceJoin = { flow: ingress.flow };
30437
+ }
30438
+ #provenanceReceiver(provenance) {
29465
30439
  const { flow, auth } = provenance;
29466
- const receiver = new BcProvenanceV2Receiver({
30440
+ return new BcProvenanceV2Receiver({
29467
30441
  ...provenance.receiver,
29468
30442
  // The caller's ctx when it passes one, else the catalog's: an explicit
29469
30443
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -29480,9 +30454,6 @@ var MulticastManager = class {
29480
30454
  maxAuthDelayMs: flow.maxAuthDelayMs,
29481
30455
  manifestTimerMs: flow.manifestTimerMs
29482
30456
  });
29483
- this.#router.registerProvenanceFlow(ingress, receiver);
29484
- this.#hookFailback();
29485
- this.#provenanceJoin = { flow: ingress.flow };
29486
30457
  }
29487
30458
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
29488
30459
  #releaseProvenanceJoin() {
@@ -29513,8 +30484,25 @@ var MulticastManager = class {
29513
30484
  * callback delivers must come from a subscription opened on
29514
30485
  * `options.gateway`. A callback that also merges another source (a MoQ or
29515
30486
  * WebSocket repair feed) must not name a native provider here.
30487
+ *
30488
+ * An endpoint's `provenance` makes its group a protected flow of its own
30489
+ * (multicast-02 7.2.7), registered here and released with the group; its
30490
+ * records ride in band on the group's port. On the user-agent path a
30491
+ * flow-less repair group of a protected track is set aside, never read, so
30492
+ * a player joining a protected catalog's repair groups passes it.
29516
30493
  */
29517
30494
  joinRepairEndpoints(endpoints, provider, options) {
30495
+ for (const { provenance, flow, source, group, port: port2 } of endpoints) {
30496
+ if (provenance === void 0) continue;
30497
+ if (flow !== void 0) {
30498
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
30499
+ }
30500
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port2 !== provenance.flow.port) {
30501
+ throw new RangeError(
30502
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
30503
+ );
30504
+ }
30505
+ }
29518
30506
  const releases = [];
29519
30507
  let released = false;
29520
30508
  const safely = (each) => {
@@ -29524,17 +30512,36 @@ var MulticastManager = class {
29524
30512
  console.warn("[MulticastManager] repair group release failed", error);
29525
30513
  }
29526
30514
  };
30515
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
30516
+ const preparedProvenance = endpoints.map((endpoint) => {
30517
+ if (endpoint.provenance === void 0) return void 0;
30518
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
30519
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
30520
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
30521
+ }
30522
+ usedFlows.add(flow);
30523
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
30524
+ });
30525
+ const provenanceFlows = [];
29527
30526
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
29528
30527
  ...owner,
29529
30528
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
29530
30529
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
29531
30530
  }));
29532
30531
  this.#applyRepairOwners(repairOwners);
29533
- for (const endpoint of endpoints) {
30532
+ for (const [index, endpoint] of endpoints.entries()) {
30533
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
29534
30534
  const ingress = {
29535
30535
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
29536
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
30536
+ ...flow === void 0 ? {} : { flow }
29537
30537
  };
30538
+ if (endpoint.provenance !== void 0) {
30539
+ const prepared = preparedProvenance[index];
30540
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
30541
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
30542
+ provenanceFlows.push(prepared.flow);
30543
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
30544
+ }
29538
30545
  let sender;
29539
30546
  const feed = (packet, sourceAddress, ingressToFeed) => {
29540
30547
  if (released) return;
@@ -29564,7 +30571,7 @@ var MulticastManager = class {
29564
30571
  packetIds: endpoint.packetIds,
29565
30572
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
29566
30573
  // A protected repair group's records ride in band on its port (7.2.3).
29567
- ...endpoint.flow === void 0 ? {} : { protected: true }
30574
+ ...flow === void 0 ? {} : { protected: true }
29568
30575
  }, ingress).then((joined) => {
29569
30576
  if (!joined && !released) fail(transport.lastJoinOutcome);
29570
30577
  });
@@ -29573,9 +30580,12 @@ var MulticastManager = class {
29573
30580
  if (released) return;
29574
30581
  released = true;
29575
30582
  this.#repairReleases.delete(release);
30583
+ this.#repairProvenanceFlows.delete(release);
29576
30584
  for (const each of releases.splice(0)) safely(each);
29577
30585
  };
29578
30586
  this.#repairReleases.set(release, repairOwners);
30587
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
30588
+ if (provenanceFlows.length) this.#hookFailback();
29579
30589
  return release;
29580
30590
  }
29581
30591
  #applyRepairOwners(owners) {
@@ -29844,6 +30854,70 @@ var MulticastManager = class {
29844
30854
  feedPacket(data, ingress, sourceAddress) {
29845
30855
  this.#transport.feedPacket(data, ingress, sourceAddress);
29846
30856
  }
30857
+ /**
30858
+ * Start an "mfu-datagram" leg (draft-ramadan-moq-mmt-02 4.3.1): a
30859
+ * subscription whose objects arrive as datagrams, a lossy unicast path.
30860
+ * Arms the join-boundary rules exactly as a multicast join does (the leg
30861
+ * starts at an arbitrary datagram), keeping configured tracks, decoders
30862
+ * and diagnostics. No MulticastTransport is involved: no takeover, no
30863
+ * failback watchdog, no bridge. While the leg is up the player publishes
30864
+ * `datagramLegDiagnostics(...)` in its FEC stats (`DatagramLegDiagnostics`:
30865
+ * `datagramLegJoined`, `datagramLegIngressDrops`,
30866
+ * `datagramLegRepairBeforePacketId`, `datagramUnknownAlias`,
30867
+ * `transport.maxDatagramSize`), the same keys in every player.
30868
+ */
30869
+ startDatagramLeg(options = {}) {
30870
+ this.#router.setDatagramLegPresentationBudget(options.presentationBudgetMs ?? null);
30871
+ this.#fec.beginLegJoin();
30872
+ }
30873
+ /**
30874
+ * Feed one object of an "mfu-datagram" subscription (one MMTP packet) in
30875
+ * arrival order. `ingress.tracks` names the datagram catalog track for the
30876
+ * packet id; the router restores serial order, holds FEC sources until a
30877
+ * repair states their block, and declares loss at the block deadline
30878
+ * (mmt-02 5.3.3). Bypasses MulticastTransport, unlike `feedPacket`.
30879
+ */
30880
+ feedDatagramLegPacket(packet, ingress) {
30881
+ this.#router.feedPacket(packet, "moq-datagram", ingress);
30882
+ }
30883
+ /**
30884
+ * Feed one repair object of an "mfu-datagram" track's repair track (sent
30885
+ * as datagrams, mmt-02 4.3.1): the repair track's own packet id names no
30886
+ * owner, so the subscription supplies it, as `router.feedRepairPacket`
30887
+ * does for a MoQ repair; the symbol counts as in-band (`RepairVia`
30888
+ * `inband`), unlike a FETCHed repair.
30889
+ */
30890
+ feedDatagramLegRepair(packet, ownerPacketId, catalogTrackName, repairTrackName) {
30891
+ this.#router.feedRepairPacket(packet, ownerPacketId, catalogTrackName, repairTrackName, "moq-datagram");
30892
+ }
30893
+ /**
30894
+ * End the "mfu-datagram" leg: call it when the subscription is dropped and
30895
+ * before the first packet of the path that replaces it (the ordered switch
30896
+ * to multicast, a fallback to the "mfu" track). The leg's presentation
30897
+ * bound and ledger retention stop applying; tracks, decoders, FEC state
30898
+ * and diagnostics stay, so the next path continues without a new epoch.
30899
+ */
30900
+ stopDatagramLeg() {
30901
+ this.#router.endDatagramLeg();
30902
+ }
30903
+ /** "mfu-datagram" leg packets dropped because their packet id is not the leg's (`MmtpRouter.datagramLegIngressDropCount`). */
30904
+ get datagramLegIngressDropCount() {
30905
+ return this.#router.datagramLegIngressDropCount;
30906
+ }
30907
+ /**
30908
+ * The leg's diagnostics as one object with the shared names
30909
+ * (`DatagramLegDiagnostics`): the player supplies what it alone counts and
30910
+ * spreads the result into its published FEC stats while a leg is up.
30911
+ */
30912
+ datagramLegDiagnostics(player) {
30913
+ return {
30914
+ datagramLegJoined: player.joined,
30915
+ datagramLegIngressDrops: this.#router.datagramLegIngressDropCount,
30916
+ datagramLegRepairBeforePacketId: player.repairBeforePacketId,
30917
+ datagramUnknownAlias: player.unknownAlias,
30918
+ transport: { maxDatagramSize: player.maxDatagramSize ?? null }
30919
+ };
30920
+ }
29847
30921
  /**
29848
30922
  * Declare how packets given to feedPacket() reach this manager. A consumer
29849
30923
  * that owns the multicast socket itself declares its own leg; join()
@@ -30061,7 +31135,8 @@ var MulticastManager = class {
30061
31135
  blockProfile: parseFecBlockProfile(
30062
31136
  geometry2.blockProfile,
30063
31137
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
30064
- )
31138
+ ),
31139
+ geometry: geometry2
30065
31140
  });
30066
31141
  }
30067
31142
  }
@@ -30100,7 +31175,7 @@ var MulticastManager = class {
30100
31175
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
30101
31176
  const before = this.#overlayBindings.get(sourcePacketId);
30102
31177
  const after = overlayBindings.get(sourcePacketId);
30103
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
31178
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
30104
31179
  if (!same) install.dispose();
30105
31180
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
30106
31181
  else install.reattach();
@@ -31212,15 +32287,15 @@ function asSeconds(n) {
31212
32287
  }
31213
32288
  return n;
31214
32289
  }
31215
- function groupIdForTicks(ticks, groupDurationTicks, presentationAnchorTicks = 0) {
32290
+ function groupIdForTicks(ticks, groupDurationTicks2, presentationAnchorTicks = 0) {
31216
32291
  if (!Number.isInteger(ticks)) {
31217
32292
  throw new Error(
31218
32293
  `[align] groupIdForTicks: ticks must be an integer, got ${ticks}`
31219
32294
  );
31220
32295
  }
31221
- if (!Number.isInteger(groupDurationTicks) || groupDurationTicks <= 0) {
32296
+ if (!Number.isInteger(groupDurationTicks2) || groupDurationTicks2 <= 0) {
31222
32297
  throw new Error(
31223
- `[align] groupIdForTicks: groupDurationTicks must be a positive integer, got ${groupDurationTicks}`
32298
+ `[align] groupIdForTicks: groupDurationTicks must be a positive integer, got ${groupDurationTicks2}`
31224
32299
  );
31225
32300
  }
31226
32301
  if (!Number.isInteger(presentationAnchorTicks)) {
@@ -31239,7 +32314,7 @@ function groupIdForTicks(ticks, groupDurationTicks, presentationAnchorTicks = 0)
31239
32314
  `[align] groupIdForTicks: ticks ${ticks} precede presentationAnchorTicks ${presentationAnchorTicks}; the publisher must reject this MPU (moq-mmt-01 4.4.1)`
31240
32315
  );
31241
32316
  }
31242
- return Math.floor(relativeTicks / groupDurationTicks);
32317
+ return Math.floor(relativeTicks / groupDurationTicks2);
31243
32318
  }
31244
32319
  function groupIdFor(mediaTimeSec, groupDurationSec) {
31245
32320
  if (!Number.isFinite(mediaTimeSec)) {
@@ -32464,6 +33539,223 @@ function resolveCatalogTrackFec(catalog, tracks) {
32464
33539
  };
32465
33540
  }
32466
33541
 
33542
+ // src/mmtp-mode-selection.ts
33543
+ function selectMmtpMode(input) {
33544
+ if (input.transportPolicy === "multicast-only") return { mode: "mfu", reason: "multicast-only" };
33545
+ if (input.override === "mfu") return { mode: "mfu", reason: "override" };
33546
+ if (!input.datagramSibling) return { mode: "mfu", reason: "no-datagram-sibling" };
33547
+ if (input.datagramFecDecodable === false) return { mode: "mfu", reason: "datagram-fec-undecodable" };
33548
+ if (input.override === "mfu-datagram") {
33549
+ return input.unreliable ? { mode: "mfu-datagram", reason: "override" } : { mode: "mfu", reason: "override-refused-reliable" };
33550
+ }
33551
+ if (!input.unreliable) return { mode: "mfu", reason: "reliable-session" };
33552
+ if (input.maxDatagramSize !== void 0 && input.symbolSize !== void 0 && input.maxDatagramSize < datagramLegObjectMax(input.symbolSize)) {
33553
+ return { mode: "mfu", reason: "repair-object-too-large" };
33554
+ }
33555
+ return { mode: "mfu-datagram", reason: "datagram" };
33556
+ }
33557
+
33558
+ // src/datagram-leg-deadline.ts
33559
+ var positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
33560
+ function fecWindow(fec) {
33561
+ if (!Array.isArray(fec) || !positive(fec[0]?.interleaveDepthMs)) return void 0;
33562
+ let window2 = 0;
33563
+ for (const instance of fec) {
33564
+ const tolerance = instance?.reorderToleranceMs;
33565
+ if (tolerance !== void 0 && !(typeof tolerance === "number" && Number.isFinite(tolerance) && tolerance >= 0)) {
33566
+ return void 0;
33567
+ }
33568
+ if (!positive(instance?.interleaveDepthMs)) continue;
33569
+ try {
33570
+ window2 = Math.max(window2, fecSpanDeliveryWindowMs(instance.interleaveDepthMs, tolerance));
33571
+ } catch {
33572
+ return void 0;
33573
+ }
33574
+ }
33575
+ return window2;
33576
+ }
33577
+ function computeDatagramLegDeadlines(input) {
33578
+ const window2 = fecWindow(input?.fec);
33579
+ if (window2 === void 0) return { take: false, reason: "no-fec-span" };
33580
+ const group = input.groupDurationMs;
33581
+ if (!positive(group)) return { take: false, reason: "no-group-duration", fecWindowMs: window2 };
33582
+ const delay = input.delayTargetMs;
33583
+ if (!positive(delay)) return { take: false, reason: "no-delay-target", fecWindowMs: window2 };
33584
+ const unit = positive(input.mediaUnitMs) ? input.mediaUnitMs : 0;
33585
+ const tolerance = input.fec[0]?.reorderToleranceMs;
33586
+ const fits = window2 <= delay;
33587
+ return {
33588
+ take: fits || input.forced === true,
33589
+ reason: fits ? "ok" : "fec-window-exceeds-delay-target",
33590
+ fecWindowMs: window2,
33591
+ joinDarkMs: Math.ceil(group + window2),
33592
+ darkMs: Math.ceil(Math.max(delay, window2)),
33593
+ noFrameMs: Math.ceil(Math.max(delay, group + unit + window2)),
33594
+ confirmMs: positive(tolerance) ? tolerance : unit
33595
+ };
33596
+ }
33597
+ var DatagramLegWatch = class {
33598
+ #options;
33599
+ #setTimeout;
33600
+ #clearTimeout;
33601
+ #now;
33602
+ #limits;
33603
+ #timer;
33604
+ #stopped = false;
33605
+ #pausedMs = 0;
33606
+ #pausedAt;
33607
+ #joinAt;
33608
+ #lastSourceAt;
33609
+ #frameClockAt;
33610
+ #chain = false;
33611
+ #suspect;
33612
+ constructor(options) {
33613
+ this.#options = options;
33614
+ const timers = options.timers;
33615
+ this.#setTimeout = (handler, ms) => timers ? timers.setTimeout(handler, ms) : setTimeout(handler, ms);
33616
+ this.#clearTimeout = (handle) => timers ? timers.clearTimeout(handle) : clearTimeout(handle);
33617
+ this.#now = options.now ?? (() => typeof performance === "undefined" ? Date.now() : performance.now());
33618
+ this.#joinAt = this.#clock();
33619
+ this.#arm();
33620
+ }
33621
+ /** SUBSCRIBE_OK: the join clock starts again. */
33622
+ subscribed() {
33623
+ if (this.#stopped || this.#lastSourceAt !== void 0) return;
33624
+ this.#joinAt = this.#clock();
33625
+ }
33626
+ /** A source object of the track arrived as a datagram. Never call it for repair, fill or FETCH objects. */
33627
+ source() {
33628
+ if (this.#stopped) return;
33629
+ const at2 = this.#clock();
33630
+ const first = this.#lastSourceAt === void 0;
33631
+ this.#lastSourceAt = at2;
33632
+ this.#frameClockAt ??= at2;
33633
+ if (first) this.#arm();
33634
+ }
33635
+ /**
33636
+ * A frame left the leg. Without `meta` every frame counts (audio, or a sink
33637
+ * that already counts decodable frames). With `meta` a frame counts when it
33638
+ * is a keyframe, or stands behind one with no stall decision between.
33639
+ */
33640
+ frame(meta) {
33641
+ if (this.#stopped) return;
33642
+ if (meta !== void 0) {
33643
+ if (meta.keyframe === true) this.#chain = true;
33644
+ else if (meta.gapBefore?.action === "stall") this.#chain = false;
33645
+ if (!this.#chain) return;
33646
+ }
33647
+ if (this.#frameClockAt !== void 0) this.#frameClockAt = this.#clock();
33648
+ }
33649
+ /** false while the player itself does not read the track: that time is not silence. */
33650
+ setReading(reading) {
33651
+ if (this.#stopped) return;
33652
+ if (!reading) {
33653
+ this.#pausedAt ??= this.#now();
33654
+ return;
33655
+ }
33656
+ if (this.#pausedAt === void 0) return;
33657
+ this.#pausedMs += this.#now() - this.#pausedAt;
33658
+ this.#pausedAt = void 0;
33659
+ if (this.#timer === void 0) this.#arm();
33660
+ }
33661
+ /** The limits moved (the delay target shrank): arm on the new ones now. */
33662
+ refresh() {
33663
+ if (this.#stopped) return;
33664
+ this.#suspect = void 0;
33665
+ this.#arm();
33666
+ }
33667
+ stop() {
33668
+ this.#stopped = true;
33669
+ this.#clear();
33670
+ }
33671
+ /** The leg's own time: it stands still while the player is not reading. */
33672
+ #clock() {
33673
+ return (this.#pausedAt ?? this.#now()) - this.#pausedMs;
33674
+ }
33675
+ #clear() {
33676
+ if (this.#timer === void 0) return;
33677
+ this.#clearTimeout(this.#timer);
33678
+ this.#timer = void 0;
33679
+ }
33680
+ #readLimits() {
33681
+ const next = this.#options.limits();
33682
+ const usable = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
33683
+ if (next && usable(next.joinDarkMs) && usable(next.darkMs) && usable(next.noFrameMs)) {
33684
+ this.#limits = {
33685
+ joinDarkMs: next.joinDarkMs,
33686
+ darkMs: next.darkMs,
33687
+ noFrameMs: next.noFrameMs,
33688
+ confirmMs: usable(next.confirmMs) ? next.confirmMs : 0
33689
+ };
33690
+ }
33691
+ return this.#limits;
33692
+ }
33693
+ #clocks(limits) {
33694
+ const joining = this.#lastSourceAt === void 0 && this.#options.joinsAtNextGroup;
33695
+ const clocks = [
33696
+ {
33697
+ clock: "dark",
33698
+ since: this.#lastSourceAt ?? this.#joinAt,
33699
+ limit: joining ? limits.joinDarkMs : limits.darkMs
33700
+ }
33701
+ ];
33702
+ if (this.#frameClockAt !== void 0) {
33703
+ clocks.push({ clock: "frame", since: this.#frameClockAt, limit: limits.noFrameMs });
33704
+ }
33705
+ return clocks;
33706
+ }
33707
+ #arm() {
33708
+ this.#clear();
33709
+ if (this.#stopped || this.#pausedAt !== void 0) return;
33710
+ const limits = this.#readLimits();
33711
+ if (!limits) return;
33712
+ const at2 = this.#clock();
33713
+ let wait = Number.POSITIVE_INFINITY;
33714
+ for (const clock of this.#clocks(limits)) {
33715
+ wait = Math.min(wait, clock.since + clock.limit - limits.confirmMs - at2);
33716
+ }
33717
+ this.#timer = this.#setTimeout(() => this.#suspectTurn(), Math.max(0, wait));
33718
+ }
33719
+ #suspectTurn() {
33720
+ this.#timer = void 0;
33721
+ if (this.#stopped || this.#pausedAt !== void 0) return;
33722
+ const limits = this.#readLimits();
33723
+ if (!limits) return;
33724
+ const at2 = this.#clock();
33725
+ const reached = this.#clocks(limits).find((clock) => at2 >= clock.since + clock.limit - limits.confirmMs);
33726
+ if (!reached) {
33727
+ this.#arm();
33728
+ return;
33729
+ }
33730
+ this.#suspect = { clock: reached.clock, since: reached.since };
33731
+ this.#timer = this.#setTimeout(() => this.#verdictTurn(), limits.confirmMs);
33732
+ }
33733
+ #verdictTurn() {
33734
+ this.#timer = void 0;
33735
+ const suspect = this.#suspect;
33736
+ this.#suspect = void 0;
33737
+ if (this.#stopped || suspect === void 0 || this.#pausedAt !== void 0) return;
33738
+ const limits = this.#readLimits();
33739
+ if (!limits) return;
33740
+ const at2 = this.#clock();
33741
+ const clock = this.#clocks(limits).find((candidate) => candidate.clock === suspect.clock);
33742
+ if (!clock || clock.since !== suspect.since) {
33743
+ this.#arm();
33744
+ return;
33745
+ }
33746
+ const silentMs = at2 - clock.since;
33747
+ if (silentMs < clock.limit) {
33748
+ this.#suspect = suspect;
33749
+ this.#timer = this.#setTimeout(() => this.#verdictTurn(), clock.limit - silentMs);
33750
+ return;
33751
+ }
33752
+ this.#stopped = true;
33753
+ const joining = this.#lastSourceAt === void 0 && this.#options.joinsAtNextGroup;
33754
+ const verdict = clock.clock === "frame" ? "no-frame" : joining ? "join" : "dark";
33755
+ this.#options.onVerdict(verdict, silentMs, clock.limit);
33756
+ }
33757
+ };
33758
+
32467
33759
  // src/mmtp-fec-session.ts
32468
33760
  var PATH_BITS = { moq: 1, multicast: 2 };
32469
33761
  var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
@@ -33522,6 +34814,22 @@ function wireRepairFetch(mc, opts) {
33522
34814
  dispatch();
33523
34815
  return;
33524
34816
  }
34817
+ if (event.type === "gap") {
34818
+ if (event.action !== "stall" || event.reason !== "discontinuity") return;
34819
+ const now = performance.now();
34820
+ let expired = false;
34821
+ for (const entry2 of [...entries.values()]) {
34822
+ if (entry2.packetId !== event.stream.packetId) continue;
34823
+ if (entry2.catalogTrackName !== (event.stream.catalogTrackName ?? void 0)) continue;
34824
+ if (!entry2.running || entry2.deadlineAt > now) continue;
34825
+ stop(entry2, "expired");
34826
+ retire(entry2);
34827
+ clearEntry(entry2);
34828
+ expired = true;
34829
+ }
34830
+ if (expired) dispatch();
34831
+ return;
34832
+ }
33525
34833
  if (event.type !== "recovered" && event.type !== "failed") return;
33526
34834
  const entry = entries.get(
33527
34835
  requestKey(event.block.sbn, event.block.packetId, event.block.catalogTrackName ?? void 0)
@@ -33820,6 +35128,7 @@ export {
33820
35128
  CmsfCatalogValidationError,
33821
35129
  DEFAULT_AMT_RELAY_PORT,
33822
35130
  DEFAULT_REPAIR_PRIORITY,
35131
+ DatagramLegWatch,
33823
35132
  DeliveryGapEstimator,
33824
35133
  FECManager,
33825
35134
  FEC_BLOCK_PROFILES,
@@ -33886,6 +35195,7 @@ export {
33886
35195
  classifyHevcKeyframe,
33887
35196
  classifyPacket,
33888
35197
  codecStringFromAvcC,
35198
+ computeDatagramLegDeadlines,
33889
35199
  computeFecDeliveryWindowMediaUnits,
33890
35200
  computeFecDeliveryWindowMs,
33891
35201
  computeFecLossWindowMs,
@@ -33952,6 +35262,7 @@ export {
33952
35262
  mfuReassemblyTimeoutMs,
33953
35263
  mmtpFrameReorderWindowFrames,
33954
35264
  mmtpTimestampToMicros,
35265
+ mmtpTrackIssues,
33955
35266
  multicastFromConfig,
33956
35267
  multicastFromEnv,
33957
35268
  normalizeDeliveryCatalog,
@@ -33978,7 +35289,9 @@ export {
33978
35289
  resolveGroupDurationMs,
33979
35290
  resolveGroupDurationTicks,
33980
35291
  resolveRepairLayers,
35292
+ runtimeFecCatalogReport,
33981
35293
  secondsFromTicks,
35294
+ selectMmtpMode,
33982
35295
  setupFecWorkerForTrack,
33983
35296
  setupTrackPipeline,
33984
35297
  splitAnnexBNalUnits,