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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +2163 -303
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +40 -1
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +163 -10
  11. package/dist/carp-catalog.js.map +4 -4
  12. package/dist/catalog-fec-params.d.ts +1 -1
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +48 -1
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.js +34 -0
  17. package/dist/catalog-network-source.js.map +3 -3
  18. package/dist/cmaf-block-assembler.js +92 -1
  19. package/dist/cmaf-block-assembler.js.map +2 -2
  20. package/dist/codec-utils.d.ts.map +1 -1
  21. package/dist/codec-utils.js +92 -1
  22. package/dist/codec-utils.js.map +2 -2
  23. package/dist/delivery-catalog.js +68 -0
  24. package/dist/delivery-catalog.js.map +4 -4
  25. package/dist/delta-fallback-config.js +39 -1
  26. package/dist/delta-fallback-config.js.map +4 -4
  27. package/dist/fec-manager.d.ts +222 -21
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +875 -131
  30. package/dist/fec-manager.js.map +4 -4
  31. package/dist/fec-state.d.ts +17 -5
  32. package/dist/fec-state.d.ts.map +1 -1
  33. package/dist/fec-state.js +41 -1
  34. package/dist/fec-state.js.map +3 -3
  35. package/dist/fec-worker-setup.js +34 -0
  36. package/dist/fec-worker-setup.js.map +3 -3
  37. package/dist/held-layer-admission.js +34 -0
  38. package/dist/held-layer-admission.js.map +3 -3
  39. package/dist/index.d.ts +6 -5
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +9 -1
  42. package/dist/index.js.map +2 -2
  43. package/dist/iso-block-locator.d.ts +55 -13
  44. package/dist/iso-block-locator.d.ts.map +1 -1
  45. package/dist/iso-block-locator.js +142 -25
  46. package/dist/iso-block-locator.js.map +3 -3
  47. package/dist/media-router.js.map +1 -1
  48. package/dist/mfu-reassembler.js +34 -0
  49. package/dist/mfu-reassembler.js.map +3 -3
  50. package/dist/mmtp-container-parser.d.ts +72 -10
  51. package/dist/mmtp-container-parser.d.ts.map +1 -1
  52. package/dist/mmtp-container-parser.js +260 -18
  53. package/dist/mmtp-container-parser.js.map +3 -3
  54. package/dist/mmtp-container-parser.no-modules.js +411 -34
  55. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  56. package/dist/mmtp-decode-pipeline.js +260 -18
  57. package/dist/mmtp-decode-pipeline.js.map +3 -3
  58. package/dist/mmtp-fec-session.js +34 -0
  59. package/dist/mmtp-fec-session.js.map +3 -3
  60. package/dist/mmtp-mode-selection.d.ts +48 -0
  61. package/dist/mmtp-mode-selection.d.ts.map +1 -0
  62. package/dist/mmtp-mode-selection.js +79 -0
  63. package/dist/mmtp-mode-selection.js.map +7 -0
  64. package/dist/mmtp-router.d.ts +94 -16
  65. package/dist/mmtp-router.d.ts.map +1 -1
  66. package/dist/mmtp-router.js +754 -78
  67. package/dist/mmtp-router.js.map +4 -4
  68. package/dist/multicast-auth-catalog.js +42 -2
  69. package/dist/multicast-auth-catalog.js.map +3 -3
  70. package/dist/multicast-input.js +42 -2
  71. package/dist/multicast-input.js.map +3 -3
  72. package/dist/multicast-manager.d.ts +121 -4
  73. package/dist/multicast-manager.d.ts.map +1 -1
  74. package/dist/multicast-manager.js +1774 -248
  75. package/dist/multicast-manager.js.map +4 -4
  76. package/dist/multicast-transport.js +70 -2
  77. package/dist/multicast-transport.js.map +4 -4
  78. package/dist/multicast-unwrap.js +34 -0
  79. package/dist/multicast-unwrap.js.map +3 -3
  80. package/dist/no-modules.d.ts +1 -0
  81. package/dist/no-modules.d.ts.map +1 -1
  82. package/dist/no-modules.js +415 -35
  83. package/dist/no-modules.js.map +4 -4
  84. package/dist/phase14-catalog-override.d.ts +2 -1
  85. package/dist/phase14-catalog-override.d.ts.map +1 -1
  86. package/dist/phase14-catalog-override.js +69 -2
  87. package/dist/phase14-catalog-override.js.map +3 -3
  88. package/dist/repair-fetch.d.ts +38 -8
  89. package/dist/repair-fetch.d.ts.map +1 -1
  90. package/dist/repair-fetch.js +336 -27
  91. package/dist/repair-fetch.js.map +3 -3
  92. package/dist/repair-layer-subscriptions.js +34 -0
  93. package/dist/repair-layer-subscriptions.js.map +3 -3
  94. package/dist/signaling.js +34 -0
  95. package/dist/signaling.js.map +3 -3
  96. package/dist/timestamp-codec.js +34 -0
  97. package/dist/timestamp-codec.js.map +3 -3
  98. package/dist/track-session.d.ts.map +1 -1
  99. package/dist/track-session.js +1 -0
  100. package/dist/track-session.js.map +2 -2
  101. package/dist/wasm-mfu-reassembler.js +34 -0
  102. package/dist/wasm-mfu-reassembler.js.map +3 -3
  103. package/dist/wasm-mmtp-container-parser.js +260 -18
  104. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  105. package/package.json +5 -5
  106. package/schemas/catalog.schema.json +2 -2
  107. package/src/block-policy.ts +324 -83
  108. package/src/carp-catalog.ts +165 -5
  109. package/src/catalog-fec-params.ts +1 -0
  110. package/src/codec-utils.ts +121 -1
  111. package/src/fec-manager.ts +835 -66
  112. package/src/fec-state.ts +21 -5
  113. package/src/index.ts +25 -0
  114. package/src/iso-block-locator.ts +148 -31
  115. package/src/mmtp-container-parser.ts +259 -24
  116. package/src/mmtp-mode-selection.ts +80 -0
  117. package/src/mmtp-router.ts +774 -86
  118. package/src/multicast-manager.ts +262 -16
  119. package/src/no-modules.ts +3 -0
  120. package/src/phase14-catalog-override.ts +14 -3
  121. package/src/repair-fetch.ts +389 -50
  122. package/src/track-session.ts +3 -0
  123. package/test-vectors/catalog/README.md +36 -2
  124. package/test-vectors/catalog/mmtp-siblings/ambiguous-sibling.json +158 -0
  125. package/test-vectors/catalog/mmtp-siblings/ladder-bitrate-only.json +231 -0
  126. package/test-vectors/catalog/mmtp-siblings/ladder-four-rungs.json +405 -0
  127. package/test-vectors/catalog/mmtp-siblings/ladder-other-names.json +231 -0
  128. package/test-vectors/catalog/mmtp-siblings/mmtp-mode-unknown.json +143 -0
  129. package/test-vectors/catalog/mmtp-siblings/multicast-endpoint-lists-datagram-track.json +143 -0
  130. package/test-vectors/catalog/mmtp-siblings/no-sibling.json +79 -0
  131. package/test-vectors/catalog/mmtp-siblings/rendition-mismatch.json +143 -0
  132. package/test-vectors/catalog/mmtp-siblings/stream-delivery-mode.json +143 -0
  133. package/test-vectors/catalog/mmtp-siblings/timescale-mismatch.json +143 -0
  134. package/test-vectors/catalog/mmtp-siblings/valid-pair.json +142 -0
  135. package/test-vectors/catalog/section-codes.json +3 -3
  136. package/test-vectors/catalog-validation.json +266 -7
  137. package/test-vectors/moq/mmtp-mode-selection.json +259 -0
@@ -851,6 +851,17 @@ function readRepairFecPayloadIdFields(mmtpPacket, parsedHeader) {
851
851
  dataOffset: off + REPAIR_FEC_PID_SIZE
852
852
  };
853
853
  }
854
+ function extractRepairFecPayloadId(mmtpPacket) {
855
+ const fields2 = readRepairFecPayloadIdFields(mmtpPacket);
856
+ if (!fields2)
857
+ return null;
858
+ return {
859
+ ssStart: fields2.ssStart,
860
+ rsbLength: fields2.rsbLength,
861
+ rsId: fields2.rsId,
862
+ ssbLength: fields2.ssbLength
863
+ };
864
+ }
854
865
  function parseMoqRepairFrame(frame) {
855
866
  return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame));
856
867
  }
@@ -1017,11 +1028,11 @@ function isoBlocksBehindLowerBound(a, b, kMax) {
1017
1028
  var DEC_OCTET = /^(?:0|[1-9]\d{0,2})$/;
1018
1029
  var H16 = /^[0-9A-Fa-f]{1,4}$/;
1019
1030
  function parseIpv4(text2) {
1020
- const fields = text2.split(".");
1021
- if (fields.length !== 4)
1031
+ const fields2 = text2.split(".");
1032
+ if (fields2.length !== 4)
1022
1033
  return void 0;
1023
1034
  const octets = [];
1024
- for (const field of fields) {
1035
+ for (const field of fields2) {
1025
1036
  if (!DEC_OCTET.test(field))
1026
1037
  return void 0;
1027
1038
  const value = Number(field);
@@ -1255,9 +1266,12 @@ function multicastCatalogIssues(catalog, options = {}) {
1255
1266
  return issues;
1256
1267
  const tracks = Array.isArray(catalog["tracks"]) ? catalog["tracks"] : [];
1257
1268
  const namespaceOf = /* @__PURE__ */ new Map();
1269
+ const modeOf = /* @__PURE__ */ new Map();
1258
1270
  for (const track of tracks) {
1259
- if (isObject(track) && typeof track["name"] === "string")
1260
- 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"]);
1261
1275
  }
1262
1276
  const tagged = catalog[CATALOG_NAMESPACE];
1263
1277
  let referenceNamespace = options.catalogNamespace ?? (typeof tagged === "string" ? tagged : void 0);
@@ -1327,6 +1341,9 @@ function multicastCatalogIssues(catalog, options = {}) {
1327
1341
  const name = isObject(ref) ? ref["name"] : ref;
1328
1342
  if (typeof name !== "string")
1329
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
+ }
1330
1347
  const namespace = namespaceOf.get(name);
1331
1348
  if (typeof namespace !== "string")
1332
1349
  continue;
@@ -1786,13 +1803,25 @@ function fecCatalogTracks(catalog) {
1786
1803
  });
1787
1804
  return { tracks, pointers };
1788
1805
  }
1789
- function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1806
+ function runtimeView(catalog, receiver) {
1790
1807
  const { tracks, pointers } = fecCatalogTracks(catalog);
1791
1808
  const report = validateFecCatalog({ tracks }, receiver);
1792
1809
  const at2 = (path) => {
1793
1810
  const m = /^\/tracks\/(\d+)(.*)$/.exec(path);
1794
1811
  return m ? pointers[Number(m[1])] + m[2] : path;
1795
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);
1796
1825
  const trackAt = (i) => recordOf(tracks[i]) ?? {};
1797
1826
  const nameAt = (i) => i === null ? void 0 : trackAt(i)["name"];
1798
1827
  const why = (i) => Object.freeze({
@@ -1890,6 +1919,70 @@ function geometry(o, instanceId, symbolTrack) {
1890
1919
  });
1891
1920
  }
1892
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
+
1893
1986
  // src/mfu-reassembler.ts
1894
1987
  function fragmentProvenance(fragment) {
1895
1988
  if (fragment.deliveryProvenance !== void 0) return fragment.deliveryProvenance;
@@ -6088,9 +6181,10 @@ function isH264IntraSlice(nal) {
6088
6181
  const sliceType = readH264SliceType(nal);
6089
6182
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
6090
6183
  }
6184
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
6091
6185
  function readH264SliceType(nal) {
6092
6186
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6093
- const rbsp = removeEmulationPrevention(nal.subarray(1));
6187
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
6094
6188
  const state = { bitOffset: 0 };
6095
6189
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6096
6190
  return readUnsignedExpGolomb(rbsp, state);
@@ -6459,6 +6553,96 @@ if (void 0) {
6459
6553
  ]))).toBe(false);
6460
6554
  });
6461
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
+ });
6462
6646
  describe("avccToAnnexB", () => {
6463
6647
  test("converts with SPS/PPS on keyframe", () => {
6464
6648
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -7127,13 +7311,13 @@ function validateCmsfMmtpCatalog(value, _options = {}) {
7127
7311
  }
7128
7312
  const timescale = track["timescale"];
7129
7313
  const groupDurationMs = track["groupDurationMs"];
7130
- const groupDurationTicks = track["groupDurationTicks"];
7314
+ const groupDurationTicks2 = track["groupDurationTicks"];
7131
7315
  const keyframeIntervalMs = track["keyframeIntervalMs"];
7132
7316
  const keyframeIntervalTicks = track["keyframeIntervalTicks"];
7133
7317
  if (groupDurationMs !== void 0 && !positiveInteger2(groupDurationMs)) {
7134
7318
  catalogError("track_group_duration_ms", `${path}.groupDurationMs`, "must be a positive integer");
7135
7319
  }
7136
- if (groupDurationTicks !== void 0 && !positiveInteger2(groupDurationTicks)) {
7320
+ if (groupDurationTicks2 !== void 0 && !positiveInteger2(groupDurationTicks2)) {
7137
7321
  catalogError("track_group_duration_ticks", `${path}.groupDurationTicks`, "must be a positive integer");
7138
7322
  }
7139
7323
  if (keyframeIntervalMs !== void 0 && !positiveNumber2(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger2(keyframeIntervalTicks)) {
@@ -7148,20 +7332,17 @@ function validateCmsfMmtpCatalog(value, _options = {}) {
7148
7332
  catalogError("track_init_ref", `${path}.initRef`, "must be a non-empty string");
7149
7333
  }
7150
7334
  if (packaging === "mmtp") {
7151
- if (track["mmtpMode"] !== "mfu") {
7152
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
7153
- }
7154
7335
  if (!positiveInteger2(timescale)) {
7155
7336
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
7156
7337
  }
7157
- if (groupDurationMs === void 0 && groupDurationTicks === void 0) {
7338
+ if (groupDurationMs === void 0 && groupDurationTicks2 === void 0) {
7158
7339
  catalogError(
7159
7340
  "track_group_duration_ms",
7160
7341
  path,
7161
7342
  "groupDurationMs or groupDurationTicks must be a positive integer"
7162
7343
  );
7163
7344
  }
7164
- if (groupDurationTicks === void 0 && BigInt(groupDurationMs) * BigInt(timescale) % 1000n !== 0n) {
7345
+ if (groupDurationTicks2 === void 0 && BigInt(groupDurationMs) * BigInt(timescale) % 1000n !== 0n) {
7165
7346
  catalogError("track_group_duration_exact", `${path}.groupDurationMs`, "does not resolve to an exact integer tick count");
7166
7347
  }
7167
7348
  }
@@ -7243,8 +7424,103 @@ function validateCmsfMmtpCatalog(value, _options = {}) {
7243
7424
  }
7244
7425
  }
7245
7426
  validateArchive(catalog);
7427
+ dropRejectedMmtpTracks(catalog);
7246
7428
  return catalog;
7247
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
+ }
7248
7524
  function resolveGroupDurationTicks(timing, timescale) {
7249
7525
  if (!Number.isFinite(timescale) || !Number.isInteger(timescale) || timescale <= 0) {
7250
7526
  throw new Error(
@@ -7560,6 +7836,40 @@ var RUNTIME_FEC_RECEIVER2 = Object.freeze({
7560
7836
  overlays: true
7561
7837
  });
7562
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
+
7563
7873
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
7564
7874
  var DEFAULT_DWELL_MS = 3e3;
7565
7875
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -8625,9 +8935,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
8625
8935
  } catch (error) {
8626
8936
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
8627
8937
  }
8628
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
8938
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
8629
8939
  await rx.close();
8630
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8940
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8631
8941
  }
8632
8942
  const events = new EventTarget();
8633
8943
  let state = "connected";
@@ -9729,11 +10039,15 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9729
10039
  if (ot.role !== void 0 && existing.role === void 0) existing.role = ot.role;
9730
10040
  if (existing.packaging === "mmtp") {
9731
10041
  const mode = existing.mmtpMode ?? ot.mmtpMode;
9732
- if (mode !== "mfu") {
10042
+ if (mode === void 0) {
9733
10043
  throw new Error(
9734
10044
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9735
10045
  );
9736
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
+ }
9737
10051
  existing.mmtpMode = mode;
9738
10052
  if (existing.timescale === void 0 && ot.timescale !== void 0) existing.timescale = ot.timescale;
9739
10053
  if (existing.groupDurationMs === void 0 && ot.groupDurationMs !== void 0) {
@@ -9770,11 +10084,15 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9770
10084
  );
9771
10085
  }
9772
10086
  const mmtpMode = ot.mmtpMode;
9773
- if (packaging === "mmtp" && mmtpMode !== "mfu") {
10087
+ if (packaging === "mmtp" && mmtpMode === void 0) {
9774
10088
  throw new Error(
9775
10089
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9776
10090
  );
9777
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
+ }
9778
10096
  if (packaging === "mmtp" && !isPositiveInteger(ot.timescale)) {
9779
10097
  throw new Error(
9780
10098
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid timescale`
@@ -12435,6 +12753,7 @@ var TrackSession = class {
12435
12753
  this.#state = "idle";
12436
12754
  this.#subscription = null;
12437
12755
  this.#disarmFec();
12756
+ this.#unsuppress();
12438
12757
  }
12439
12758
  // -----------------------------------------------------------------------
12440
12759
  // Internal
@@ -12928,6 +13247,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
12928
13247
  this.#heldEvicted = 0;
12929
13248
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
12930
13249
  this.#holes = [];
13250
+ /** Holes the horizon passed while pending: sources held until closed. */
13251
+ this.#expired = [];
13252
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
13253
+ this.#newlyExpired = [];
13254
+ /**
13255
+ * Spans closed from expired holes: behind the horizon, so kept only for
13256
+ * `locate` while their sources are fed, until the next retirement.
13257
+ */
13258
+ this.#closedBehind = [];
12931
13259
  /**
12932
13260
  * Keep a gap that is missing a source as a pending hole rather than a span,
12933
13261
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -12951,6 +13279,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
12951
13279
  #newest;
12952
13280
  #newestSource;
12953
13281
  #holes;
13282
+ #expired;
13283
+ #newlyExpired;
13284
+ #closedBehind;
12954
13285
  static #checkedRetention(retentionBlocks) {
12955
13286
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
12956
13287
  throw new Error(
@@ -13020,17 +13351,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
13020
13351
  }
13021
13352
  /** The known block or span containing `ssId`, with its ESI. */
13022
13353
  locate(ssId) {
13023
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
13024
- const block = this.#blocks[i];
13025
- if (isoBlockContains(block.start, block.length, ssId)) {
13026
- return { block, esi: serial32Distance(block.start, ssId) };
13354
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
13355
+ for (let i = blocks.length - 1; i >= 0; i--) {
13356
+ const block = blocks[i];
13357
+ if (isoBlockContains(block.start, block.length, ssId)) {
13358
+ return { block, esi: serial32Distance(block.start, ssId) };
13359
+ }
13027
13360
  }
13028
13361
  }
13029
13362
  return null;
13030
13363
  }
13031
- /** Number of pending holes. */
13364
+ /** Number of holes not closed yet, pending or past the horizon. */
13032
13365
  get holeCount() {
13033
- return this.#holes.length;
13366
+ return this.#holes.length + this.#expired.length;
13367
+ }
13368
+ /**
13369
+ * The pending holes the horizon has passed since the last call, in the
13370
+ * order it passed them. Each is no longer pending: no repair states a block
13371
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
13372
+ * release gate does not wait for it. Its owner must close it
13373
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
13374
+ */
13375
+ takeExpiredHoles() {
13376
+ return this.#newlyExpired.splice(0);
13034
13377
  }
13035
13378
  /** The stated block (never a span) ending exactly at `end`. */
13036
13379
  blockEndingAt(end) {
@@ -13083,12 +13426,42 @@ var IsoBlockLocator = class _IsoBlockLocator {
13083
13426
  isHeld(ssId) {
13084
13427
  return this.#held.has(ssId);
13085
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
+ }
13086
13457
  /**
13087
13458
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
13088
13459
  * block states its range and places every held source in it; later repair
13089
- * symbols of the same block change nothing. A range that contradicts a
13090
- * known block (a different length, or an overlap with another block or a
13091
- * span) fails closed: the repair symbol is dropped and no block changes.
13460
+ * symbols of the same block change nothing. A repair whose range is exactly
13461
+ * a repair-less span states that span's one block. A range that contradicts
13462
+ * a known block (a different length, or an overlap with another block or
13463
+ * with part of a span) fails closed: the repair symbol is dropped and no
13464
+ * block changes.
13092
13465
  * A newly stated block retires behind its SS_Start (see the class note).
13093
13466
  * A block so far past `newest` that stating it would retire the position
13094
13467
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -13107,7 +13480,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
13107
13480
  const known = this.blockAt(start);
13108
13481
  if (known !== void 0) {
13109
13482
  if (known.span) {
13110
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
13483
+ if (known.length === length) {
13484
+ const block2 = { start, length, span: false };
13485
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
13486
+ return { status: "placed", block: block2, placed: [] };
13487
+ }
13488
+ return length < known.length ? {
13489
+ status: "overlap",
13490
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
13491
+ ofSpan: known
13492
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
13111
13493
  }
13112
13494
  if (known.length !== length) {
13113
13495
  return {
@@ -13175,18 +13557,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
13175
13557
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
13176
13558
  }
13177
13559
  /**
13178
- * Turn every pending hole inside `[start, start + length)` into a
13179
- * repair-less span, claiming its held sources: its range FETCH ended, so
13180
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
13560
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
13561
+ * claiming its held sources: its range FETCH ended, so nothing more will
13562
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
13563
+ * span that is not kept among the blocks, as the horizon would retire it at
13564
+ * once; only `locate` finds it, until the next retirement, so its sources
13565
+ * can be fed. Returns the spans, in SS_ID order.
13181
13566
  */
13182
13567
  closeHolesWithin(start, length) {
13183
13568
  const closed = [];
13184
- for (const hole of [...this.#holes]) {
13185
- if (!isoBlockContains(start, length, hole.start)) continue;
13186
- this.#holes.splice(this.#holes.indexOf(hole), 1);
13187
- const spanBlock = { start: hole.start, length: hole.length, span: true };
13188
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13189
- this.#blocks.push(spanBlock);
13569
+ for (const holes of [this.#holes, this.#expired]) {
13570
+ for (const hole of [...holes]) {
13571
+ if (!isoBlockContains(start, length, hole.start)) continue;
13572
+ holes.splice(holes.indexOf(hole), 1);
13573
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
13574
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13575
+ if (holes === this.#holes) {
13576
+ this.#blocks.push(spanBlock);
13577
+ } else {
13578
+ this.#closedBehind.push(spanBlock);
13579
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
13580
+ }
13581
+ }
13190
13582
  }
13191
13583
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
13192
13584
  }
@@ -13200,15 +13592,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
13200
13592
  return void 0;
13201
13593
  }
13202
13594
  /**
13203
- * Retire every block and span whose last SS_ID, and every held source,
13204
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
13205
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
13206
- * horizon uses. Returns the retired block starts.
13595
+ * Retire every block and span whose last SS_ID, and every held source
13596
+ * outside a hole, lies more than `retentionBlocks` blocks behind
13597
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
13598
+ * every ISO interleave horizon uses; a pending hole so far behind expires
13599
+ * (`takeExpiredHoles`). Returns the retired block starts.
13207
13600
  */
13208
13601
  retireBehind(position) {
13209
13602
  this.observe(position);
13210
13603
  const horizon = this.#retentionBlocks;
13211
13604
  const retired = [];
13605
+ this.#closedBehind.length = 0;
13212
13606
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
13213
13607
  const block = this.#blocks[i];
13214
13608
  const last = serial32Add(block.start, block.length - 1);
@@ -13220,10 +13614,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
13220
13614
  for (let i = this.#holes.length - 1; i >= 0; i--) {
13221
13615
  const hole = this.#holes[i];
13222
13616
  const last = serial32Add(hole.start, hole.length - 1);
13223
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
13617
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
13618
+ this.#holes.splice(i, 1);
13619
+ this.#expired.push(hole);
13620
+ this.#newlyExpired.push(hole);
13224
13621
  }
13225
13622
  for (const ssId of [...this.#held.keys()]) {
13226
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
13623
+ if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon && !this.#holes.some((hole) => isoBlockContains(hole.start, hole.length, ssId)) && !this.#expired.some((hole) => isoBlockContains(hole.start, hole.length, ssId))) {
13624
+ this.#held.delete(ssId);
13625
+ }
13227
13626
  }
13228
13627
  return retired;
13229
13628
  }
@@ -13231,6 +13630,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
13231
13630
  reset() {
13232
13631
  this.#blocks.length = 0;
13233
13632
  this.#holes.length = 0;
13633
+ this.#expired.length = 0;
13634
+ this.#newlyExpired.length = 0;
13635
+ this.#closedBehind.length = 0;
13234
13636
  this.#held.clear();
13235
13637
  this.#coverageEnd = void 0;
13236
13638
  this.#newest = void 0;
@@ -13280,6 +13682,7 @@ function resolveFecState(evidence) {
13280
13682
  const catalogFec = requireBoolean(evidence.catalogFec, "catalogFec");
13281
13683
  const bridgeAvailable = requireBoolean(evidence.bridgeAvailable, "bridgeAvailable");
13282
13684
  const multicastLegJoined = requireBoolean(evidence.multicastLegJoined, "multicastLegJoined");
13685
+ const datagramLegJoined = evidence.datagramLegJoined === void 0 ? false : requireBoolean(evidence.datagramLegJoined, "datagramLegJoined");
13283
13686
  const { transportPolicy, stats } = evidence;
13284
13687
  if (typeof transportPolicy !== "string" || !TRANSPORT_POLICIES.has(transportPolicy)) {
13285
13688
  throw new TypeError(`resolveFecState: unsupported transportPolicy ${JSON.stringify(transportPolicy)}`);
@@ -13288,6 +13691,7 @@ function resolveFecState(evidence) {
13288
13691
  throw new TypeError("resolveFecState: stats must be a plain object, null or undefined");
13289
13692
  }
13290
13693
  if (!catalogFec) return INACTIVE["no-catalog-fec"];
13694
+ if (datagramLegJoined) return { ...stats ?? {}, state: "active" };
13291
13695
  if (transportPolicy === "moq-only") return INACTIVE["reliable-moq"];
13292
13696
  if (!bridgeAvailable) return INACTIVE["no-multicast-bridge"];
13293
13697
  if (transportPolicy === "multicast-only" || multicastLegJoined) {
@@ -13328,31 +13732,26 @@ function deriveBlockClassifierGeometry(input) {
13328
13732
  );
13329
13733
  }
13330
13734
  if (input.trackKind === "audio") return { trackKind: "audio" };
13331
- if (!isPositiveFinite(input.framerate)) {
13332
- return { trackKind: "video", mode: "all-protected", reason: "framerate-absent" };
13333
- }
13334
- const framerate = input.framerate;
13335
13735
  let keyframeInterval;
13336
13736
  if (isPositiveFinite(input.keyframeIntervalTicks) && isPositiveFinite(input.timescale)) {
13337
13737
  keyframeInterval = { ticks: input.keyframeIntervalTicks, timescale: input.timescale };
13338
13738
  } else if (isPositiveFinite(input.keyframeIntervalMs)) {
13339
13739
  keyframeInterval = { ticks: input.keyframeIntervalMs, timescale: 1e3 };
13340
- } else {
13341
- return { trackKind: "video", mode: "all-protected", reason: "keyframe-cadence-absent" };
13342
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");
13343
13750
  const gopFrames = exactInteger(keyframeInterval.ticks * framerate, keyframeInterval.timescale);
13344
- if (gopFrames === null) {
13345
- return {
13346
- trackKind: "video",
13347
- mode: "all-protected",
13348
- reason: "keyframe-interval-not-integral"
13349
- };
13350
- }
13751
+ if (gopFrames === null) return protect("keyframe-interval-not-integral");
13351
13752
  const frameDurationMs = 1e3 / framerate;
13352
13753
  const interleaveUnits = deriveFecInterleaveDepth(input.interleaveDepthMs, frameDurationMs);
13353
- if (interleaveUnits >= gopFrames) {
13354
- return { trackKind: "video", mode: "all-protected", reason: "block-spans-gop" };
13355
- }
13754
+ if (interleaveUnits >= gopFrames) return protect("block-spans-gop");
13356
13755
  return {
13357
13756
  trackKind: "video",
13358
13757
  mode: "classifying",
@@ -13363,7 +13762,7 @@ function deriveBlockClassifierGeometry(input) {
13363
13762
  };
13364
13763
  }
13365
13764
  function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
13366
- if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return null;
13765
+ if (geometry2.trackKind !== "video" || geometry2.keyframeInterval === void 0) return null;
13367
13766
  if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0) return null;
13368
13767
  const { ticks, timescale } = geometry2.keyframeInterval;
13369
13768
  if (!Number.isSafeInteger(ticks) || !Number.isSafeInteger(timescale)) return null;
@@ -13372,9 +13771,15 @@ function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
13372
13771
  if (scaled % divisor !== 0n) return null;
13373
13772
  return scaled / divisor;
13374
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
+ }
13375
13778
  function compareDataUnitStarts(a, b) {
13376
- 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;
13377
13780
  }
13781
+ var LATE_RAP_MAX_MPUS_BACK = 64;
13782
+ var UNPLACED = { rapNotMpuStart: false };
13378
13783
  var BlockClassifier = class {
13379
13784
  #geometry;
13380
13785
  #mode;
@@ -13397,8 +13802,24 @@ var BlockClassifier = class {
13397
13802
  #mpuSbnSpans = /* @__PURE__ */ new Map();
13398
13803
  #dataUnitStarts = /* @__PURE__ */ new Map();
13399
13804
  #highestMpu = null;
13400
- /** MPU → movie_fragment_sequence_number observed in it. */
13401
- #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. */
13402
13823
  #lastRap = null;
13403
13824
  constructor(geometry2) {
13404
13825
  this.#geometry = geometry2;
@@ -13428,7 +13849,7 @@ var BlockClassifier = class {
13428
13849
  this.#geometry = geometry2;
13429
13850
  this.#blocks.clear();
13430
13851
  this.#clearContiguityLedger();
13431
- this.#mpuFragments.clear();
13852
+ this.#clearMpuLayout();
13432
13853
  this.#lastRap = null;
13433
13854
  this.#mpuBoundsRaps = true;
13434
13855
  if (geometry2.trackKind === "video" && geometry2.mode === "all-protected") {
@@ -13462,11 +13883,14 @@ var BlockClassifier = class {
13462
13883
  /**
13463
13884
  * The stream's SBN sequence restarted (FECManager source discontinuity:
13464
13885
  * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
13465
- * order are comparable only within one continuous sequence, so the P1
13466
- * 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.
13467
13889
  */
13468
13890
  noteSourceDiscontinuity() {
13469
13891
  this.#clearContiguityLedger();
13892
+ this.#clearMpuLayout();
13893
+ this.#lastRap = null;
13470
13894
  }
13471
13895
  /** Register a block that exists without evidence (a vanished block). */
13472
13896
  touch(sbn) {
@@ -13485,16 +13909,16 @@ var BlockClassifier = class {
13485
13909
  if (this.#geometry.trackKind === "audio") return [];
13486
13910
  const changes = [];
13487
13911
  const block = this.#blockFor(sbn);
13912
+ const placement = this.#place(evidence);
13488
13913
  if (evidence.rap) block.rapSeen = true;
13489
13914
  if (evidence.mpu !== void 0) block.mpus.add(evidence.mpu);
13490
- if (evidence.idx !== void 0) {
13491
- block.idxMin = block.idxMin === void 0 ? evidence.idx : Math.min(block.idxMin, evidence.idx);
13492
- block.idxMax = block.idxMax === void 0 ? evidence.idx : Math.max(block.idxMax, evidence.idx);
13493
- }
13494
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
13495
- this.#mpuBoundsRaps = false;
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);
13496
13919
  }
13497
- const violation = this.#checkInvariants(sbn, block, evidence);
13920
+ if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false;
13921
+ const violation = this.#checkInvariants(sbn, block, evidence, placement);
13498
13922
  if (violation !== null) changes.push(...this.#disable(violation));
13499
13923
  const next = this.#classify(block);
13500
13924
  if (next !== block.cls && this.#allowed(block.cls, next)) {
@@ -13519,18 +13943,35 @@ var BlockClassifier = class {
13519
13943
  * RAP-bearing block is the one a wrong G calls delta), because the next
13520
13944
  * released RAP then belongs to m+2. Every MPU is one interval long, so the
13521
13945
  * span to any later released RAP proves or refutes all MPUs in between.
13522
- */
13523
- noteReleasedRap(mpu, presentationTime, mediaTimescale) {
13524
- if (this.#geometry.trackKind === "audio" || this.#mode === "all-protected") {
13525
- return [];
13526
- }
13527
- const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13528
- 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 [];
13529
13958
  const previous = this.#lastRap;
13530
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
+ }
13531
13965
  return [];
13532
13966
  }
13533
- 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");
13534
13975
  if (previous === null || mpu < previous.mpu || previous.mediaTimescale !== mediaTimescale) {
13535
13976
  return [];
13536
13977
  }
@@ -13539,6 +13980,22 @@ var BlockClassifier = class {
13539
13980
  }
13540
13981
  return this.#disable("rap-spacing-mismatch");
13541
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
+ }
13542
13999
  #blockFor(sbn) {
13543
14000
  let block = this.#blocks.get(sbn);
13544
14001
  if (!block) {
@@ -13547,35 +14004,89 @@ var BlockClassifier = class {
13547
14004
  }
13548
14005
  return block;
13549
14006
  }
13550
- #checkInvariants(sbn, block, evidence) {
14007
+ #checkInvariants(sbn, block, evidence, placement) {
13551
14008
  if (this.#mode === "all-protected" || this.#geometry.trackKind !== "video") return null;
13552
14009
  const geometry2 = this.#geometry;
13553
14010
  if (geometry2.mode !== "classifying") return null;
13554
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
13555
- return "rap-not-mpu-start";
13556
- }
13557
- 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) {
13558
14013
  return "mpu-longer-than-gop";
13559
14014
  }
13560
- 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) {
13561
14016
  return "block-wider-than-interleave";
13562
14017
  }
13563
- if (evidence.mpu !== void 0 && evidence.movieFragment !== void 0) {
13564
- const fragment = this.#mpuFragments.get(evidence.mpu);
13565
- if (fragment === void 0) {
13566
- this.#mpuFragments.set(evidence.mpu, evidence.movieFragment);
13567
- for (const mpu of this.#mpuFragments.keys()) {
13568
- if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu);
13569
- }
13570
- } else if (fragment !== evidence.movieFragment) {
13571
- return "mpu-multiple-fragments";
13572
- }
13573
- }
14018
+ if (placement.violation !== void 0) return placement.violation;
13574
14019
  if (evidence.mpu !== void 0 && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
13575
14020
  return "block-not-contiguous";
13576
14021
  }
13577
14022
  return null;
13578
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
+ }
13579
14090
  #clearContiguityLedger() {
13580
14091
  this.#mpuSbnSpans.clear();
13581
14092
  this.#dataUnitStarts.clear();
@@ -13675,9 +14186,9 @@ var BlockClassifier = class {
13675
14186
  if (this.#mode === "all-protected") return "unknown";
13676
14187
  const geometry2 = this.#geometry;
13677
14188
  if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return "unknown";
13678
- 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) {
13679
14190
  const span = geometry2.interleaveUnits - 1;
13680
- if (block.idxMax - span >= 1 && block.idxMin + span <= geometry2.gopFrames - 1) {
14191
+ if (block.positionMax - span >= 1 && block.positionMin + span <= geometry2.gopFrames - 1) {
13681
14192
  return "delta";
13682
14193
  }
13683
14194
  }
@@ -13854,6 +14365,7 @@ var WORKER_ERROR_LOG_CAP = 5;
13854
14365
  var WORKER_ERROR_KIND_CAP = 32;
13855
14366
  var WORKER_ERROR_OVERFLOW_KIND = "other";
13856
14367
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
14368
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
13857
14369
  function isMulticastSymbolDelivery(value) {
13858
14370
  return value === "datagram" || value === "ordered-relay";
13859
14371
  }
@@ -13935,7 +14447,12 @@ var FECManager = class _FECManager {
13935
14447
  this.#repairHoldUntilMs = /* @__PURE__ */ new Map();
13936
14448
  // Receiver-measured multicast delivery gap: the late-symbol wait's jitter
13937
14449
  // term (see DeliveryGapEstimator for the statistic and why).
13938
- 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
+ };
13939
14456
  this.#lifecycleTrace = [];
13940
14457
  // Worker-backed timeouts enqueue cleanup behind all prior symbol messages.
13941
14458
  // Failure remains pending until cleanupComplete acknowledges that queue drain.
@@ -13947,10 +14464,18 @@ var FECManager = class _FECManager {
13947
14464
  // 'pending' forever, which would park every later frame of its stream in
13948
14465
  // the in-order release gate. Each entry owns its handle; the callback
13949
14466
  // checks it still owns the key, so a settled or reset key is never touched.
14467
+ /**
14468
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
14469
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
14470
+ */
13950
14471
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
13951
14472
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
13952
14473
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
13953
14474
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
14475
+ // Source ESIs per block that another FEC instance rebuilt and fed in
14476
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
14477
+ // not network arrivals and never make a block clean.
14478
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
13954
14479
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
13955
14480
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
13956
14481
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -13959,10 +14484,14 @@ var FECManager = class _FECManager {
13959
14484
  // SSB_length source arrivals and recoverable from SSB_length received
13960
14485
  // symbols; waiting for K fails every one of them.
13961
14486
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
14487
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
14488
+ // a repair states the block there or the span resolves.
14489
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
13962
14490
  this.#ssbLengthConflictCount = 0;
13963
14491
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
13964
14492
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
13965
- // 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.
13966
14495
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
13967
14496
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
13968
14497
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -14115,6 +14644,14 @@ var FECManager = class _FECManager {
14115
14644
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
14116
14645
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
14117
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();
14118
14655
  this.#deferIsoGaps = false;
14119
14656
  this.#isoRepairRefusedCount = 0;
14120
14657
  this.#isoSourceOversizeCount = 0;
@@ -14150,13 +14687,18 @@ var FECManager = class _FECManager {
14150
14687
  this.#workerErrorCounts = /* @__PURE__ */ new Map();
14151
14688
  this.#decoderUnavailableEvents = 0;
14152
14689
  this.#repairSymbolSizeMismatchCount = 0;
14690
+ this.#unlistedRepairTrackRefusals = 0;
14691
+ this.#unresolvedRepairOwnerDrops = { unregistered: 0, ownerAbsent: 0, ownerAmbiguous: 0 };
14153
14692
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
14154
14693
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
14155
14694
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
14156
14695
  // arrives via onBlockRecovered callback.
14157
14696
  this.onBlockStarted = null;
14158
14697
  this.onBlockComplete = null;
14159
- /** A block reached its fail bound. `blockClass` is its class at failure. */
14698
+ /**
14699
+ * A block reached its fail bound. `blockClass` is its class at failure.
14700
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
14701
+ */
14160
14702
  this.onBlockFailed = null;
14161
14703
  /**
14162
14704
  * Fired once per stream when its Worker decoder stops being routable.
@@ -14198,12 +14740,26 @@ var FECManager = class _FECManager {
14198
14740
  * for it, which it must be.
14199
14741
  */
14200
14742
  this.#onUndelimitedLoss = null;
14743
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
14744
+ this.#onIsoHoleExpired = null;
14201
14745
  /** A block every symbol of which vanished was created by SBN evidence. */
14202
14746
  this.onBlockVanished = null;
14203
14747
  /** A block reached a terminal state (completed, recovered, or failed). */
14204
14748
  this.onBlockResolved = null;
14205
14749
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
14206
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;
14207
14763
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
14208
14764
  /**
14209
14765
  * A recovered source symbol. Return false when admission refused the
@@ -14240,7 +14796,9 @@ var FECManager = class _FECManager {
14240
14796
  #pendingWorkerCleanupBounds;
14241
14797
  #blockSourceCounts;
14242
14798
  #blockSourceEsis;
14799
+ #blockRebuiltEsis;
14243
14800
  #blockAuthoredLengths;
14801
+ #isoSpanKeys;
14244
14802
  #ssbLengthConflictCount;
14245
14803
  #blockRepairRsIds;
14246
14804
  #blockRsbLengths;
@@ -14292,6 +14850,7 @@ var FECManager = class _FECManager {
14292
14850
  #highestSbn;
14293
14851
  #sourceFrontiers;
14294
14852
  #isoLocators;
14853
+ #runAnchors;
14295
14854
  #deferIsoGaps;
14296
14855
  #isoRepairRefusedCount;
14297
14856
  #isoSourceOversizeCount;
@@ -14306,7 +14865,10 @@ var FECManager = class _FECManager {
14306
14865
  #workerErrorCounts;
14307
14866
  #decoderUnavailableEvents;
14308
14867
  #repairSymbolSizeMismatchCount;
14868
+ #unlistedRepairTrackRefusals;
14869
+ #unresolvedRepairOwnerDrops;
14309
14870
  #onUndelimitedLoss;
14871
+ #onIsoHoleExpired;
14310
14872
  #encodeTrackName(catalogTrackName) {
14311
14873
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
14312
14874
  if (encoded === void 0) {
@@ -14778,7 +15340,10 @@ var FECManager = class _FECManager {
14778
15340
  timer.handle = null;
14779
15341
  this.#requestRepair(sbn, packetId, catalogTrackName);
14780
15342
  };
14781
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
15343
+ timer.handle = setTimeout(
15344
+ onFire,
15345
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
15346
+ );
14782
15347
  this.#repairDeadlines.set(key, timer);
14783
15348
  }
14784
15349
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -14922,8 +15487,14 @@ var FECManager = class _FECManager {
14922
15487
  * Vanished blocks are not enumerated here: their starts are unknown until a
14923
15488
  * repair states them. The SS_IDs between two stated blocks become one
14924
15489
  * repair-less span when the later block's repair arrives (placeIsoRepair).
15490
+ *
15491
+ * A `held` source arrived before its block was known and is fed only now
15492
+ * that a repair, a span or a closed hole placed it: how far its block start
15493
+ * then lies behind the frontier measures how long the receiver held it, not
15494
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
15495
+ * it (BLO-52085).
14925
15496
  */
14926
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
15497
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
14927
15498
  const streamKey = this.#streamKey(packetId, catalogTrackName);
14928
15499
  const now = performance.now();
14929
15500
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -14945,6 +15516,7 @@ var FECManager = class _FECManager {
14945
15516
  const discontinuity = () => {
14946
15517
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
14947
15518
  this.#noSpanRaps.delete(streamKey);
15519
+ this.#runAnchors.delete(streamKey);
14948
15520
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
14949
15521
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
14950
15522
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -14962,7 +15534,7 @@ var FECManager = class _FECManager {
14962
15534
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
14963
15535
  };
14964
15536
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
14965
- if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
15537
+ if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (!held && this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
14966
15538
  discontinuity();
14967
15539
  return;
14968
15540
  }
@@ -15115,7 +15687,7 @@ var FECManager = class _FECManager {
15115
15687
  consider(geometry2, this.#parseStreamKey(streamKey).packetId);
15116
15688
  }
15117
15689
  for (const [packetId, config] of this.#trackConfigs) consider(config.geometry, packetId);
15118
- this.#deliveryGaps.setWindowMs(windowMs);
15690
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.setWindowMs(windowMs);
15119
15691
  }
15120
15692
  /**
15121
15693
  * The multicast late-symbol wait: the block span plus the larger of the
@@ -15128,14 +15700,14 @@ var FECManager = class _FECManager {
15128
15700
  * stream order and never feeds the estimator.
15129
15701
  */
15130
15702
  #multicastWaitMs(config) {
15131
- return this.#waitForGapMs(config, this.#deliveryGaps.peakGapMs(performance.now()));
15703
+ return this.#waitForGapMs(config, this.#peakDeliveryGapMs());
15132
15704
  }
15133
15705
  /**
15134
15706
  * The widest #multicastWaitMs can become: the estimator reports at most its
15135
15707
  * catalog window, so this is a catalog quantity that no measurement moves.
15136
15708
  */
15137
15709
  #maxMulticastWaitMs(config) {
15138
- return this.#waitForGapMs(config, this.#deliveryGaps.windowMs ?? 0);
15710
+ return this.#waitForGapMs(config, this.#deliveryGaps.multicast.windowMs ?? 0);
15139
15711
  }
15140
15712
  #waitForGapMs(config, gapMs) {
15141
15713
  if (!(gapMs > 0) || !(config.interleaveDepthMs > 0)) return config.timeoutMs;
@@ -15224,17 +15796,21 @@ var FECManager = class _FECManager {
15224
15796
  this.#blockWaitDeadlinesMs.delete(key);
15225
15797
  this.#repairHoldUntilMs.delete(key);
15226
15798
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
15227
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
15799
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
15228
15800
  };
15229
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
15801
+ timer.handle = setTimeout(
15802
+ onFire,
15803
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
15804
+ );
15230
15805
  this.#activeBlocks.set(key, timer);
15231
15806
  this.#indexBlockKey(key, sbn, packetId);
15232
15807
  }
15233
15808
  /**
15234
15809
  * Hand a block whose delivery is over to its decoder for finalization: the
15235
- * datagram deadline fired, or the ordered relay moved past it.
15810
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
15811
+ * is when it was due: its deadline, or now.
15236
15812
  */
15237
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
15813
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
15238
15814
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
15239
15815
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
15240
15816
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -15250,7 +15826,7 @@ var FECManager = class _FECManager {
15250
15826
  if (workerClient) {
15251
15827
  this.#pendingWorkerCleanups.add(key);
15252
15828
  this.#pendingWorkerCleanupClients.set(key, workerClient);
15253
- this.#boundOwedCleanup(key, packetId, workerClient);
15829
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
15254
15830
  workerClient.cleanup(sbn);
15255
15831
  } else {
15256
15832
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -15315,6 +15891,7 @@ var FECManager = class _FECManager {
15315
15891
  ...(config.trackKind ?? previous.trackKind) === void 0 ? {} : { trackKind: config.trackKind ?? previous.trackKind },
15316
15892
  ...(config.codec ?? previous.codec) === void 0 ? {} : { codec: config.codec ?? previous.codec },
15317
15893
  ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry },
15894
+ ...(config.groupDurationMs ?? previous.groupDurationMs) === void 0 ? {} : { groupDurationMs: config.groupDurationMs ?? previous.groupDurationMs },
15318
15895
  ...(config.repairLayers ?? previous.repairLayers) === void 0 ? {} : { repairLayers: config.repairLayers ?? previous.repairLayers },
15319
15896
  ...(config.heldLayers ?? previous.heldLayers) === void 0 ? {} : { heldLayers: config.heldLayers ?? previous.heldLayers }
15320
15897
  };
@@ -15421,6 +15998,10 @@ var FECManager = class _FECManager {
15421
15998
  lifecycleTrace: this.#lifecycleTrace.map((entry) => ({ ...entry }))
15422
15999
  };
15423
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
+ }
15424
16005
  get fecStats() {
15425
16006
  const s = this.#fecStats;
15426
16007
  const affected = s.blocksRecovered + s.blocksFailed;
@@ -15460,6 +16041,8 @@ var FECManager = class _FECManager {
15460
16041
  packetId
15461
16042
  })),
15462
16043
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
16044
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
16045
+ unresolvedRepairOwnerDrops: { ...this.#unresolvedRepairOwnerDrops },
15463
16046
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
15464
16047
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
15465
16048
  };
@@ -15484,6 +16067,16 @@ var FECManager = class _FECManager {
15484
16067
  this.#startupRepairBoundaryCounts.clear();
15485
16068
  this.#startupRepairFailOpenPackets.clear();
15486
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
+ }
15487
16080
  /** How the multicast leg currently delivers symbols. */
15488
16081
  get multicastSymbolDelivery() {
15489
16082
  return this.#multicastSymbolDelivery;
@@ -15506,7 +16099,8 @@ var FECManager = class _FECManager {
15506
16099
  );
15507
16100
  }
15508
16101
  if (delivery === this.#multicastSymbolDelivery) return;
15509
- this.#deliveryGaps.reset();
16102
+ this.#deliveryGaps.multicast.reset();
16103
+ this.#runAnchors.clear();
15510
16104
  if (delivery === "ordered-relay") {
15511
16105
  for (const [packetId, config] of this.#trackConfigs) {
15512
16106
  this.#orderedHorizonBlocksFor(packetId, config);
@@ -15562,7 +16156,9 @@ var FECManager = class _FECManager {
15562
16156
  }
15563
16157
  resetMap(this.#blockSourceCounts);
15564
16158
  resetMap(this.#blockSourceEsis);
16159
+ resetMap(this.#blockRebuiltEsis);
15565
16160
  resetMap(this.#blockAuthoredLengths);
16161
+ resetSet(this.#isoSpanKeys);
15566
16162
  resetMap(this.#blockRepairRsIds);
15567
16163
  resetMap(this.#blockRsbLengths);
15568
16164
  resetMap(this.#heldLayerStates);
@@ -15593,6 +16189,7 @@ var FECManager = class _FECManager {
15593
16189
  resetMap(this.#highestSbn);
15594
16190
  resetMap(this.#sourceFrontiers);
15595
16191
  resetMap(this.#isoLocators);
16192
+ resetMap(this.#runAnchors);
15596
16193
  resetMap(this.#sourceAnchors);
15597
16194
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
15598
16195
  this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
@@ -15686,7 +16283,9 @@ var FECManager = class _FECManager {
15686
16283
  dropMap(this.#pendingWorkerCleanupClients);
15687
16284
  dropMap(this.#blockSourceCounts);
15688
16285
  dropMap(this.#blockSourceEsis);
16286
+ dropMap(this.#blockRebuiltEsis);
15689
16287
  dropMap(this.#blockAuthoredLengths);
16288
+ dropSet(this.#isoSpanKeys);
15690
16289
  dropMap(this.#blockRepairRsIds);
15691
16290
  dropMap(this.#blockRsbLengths);
15692
16291
  dropMap(this.#blockPathCounts);
@@ -15700,6 +16299,7 @@ var FECManager = class _FECManager {
15700
16299
  dropMap(this.#highestSbn);
15701
16300
  dropMap(this.#sourceFrontiers);
15702
16301
  dropMap(this.#isoLocators);
16302
+ dropMap(this.#runAnchors);
15703
16303
  dropMap(this.#sourceAnchors);
15704
16304
  dropMap(this.#classifiers);
15705
16305
  dropMap(this.#noSpanRaps);
@@ -15767,8 +16367,8 @@ var FECManager = class _FECManager {
15767
16367
  const sourceSymbols = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? this.#trackConfig(packetId).k;
15768
16368
  const isSourceSymbol = esi >= 0 && esi < sourceSymbols;
15769
16369
  const isStartupPartial = this.#startupPartialBlocks.has(blockKey);
15770
- const isReadyMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
15771
- 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);
15772
16372
  if (awaitingMulticastRepair) {
15773
16373
  if (!isSourceSymbol) {
15774
16374
  this.#startupRepairReadyPackets.add(streamKey);
@@ -15822,12 +16422,14 @@ var FECManager = class _FECManager {
15822
16422
  ...catalogTrackName === void 0 ? {} : { catalogTrackName },
15823
16423
  multicastSymbols: 0,
15824
16424
  moqSymbols: 0,
16425
+ datagramSymbols: 0,
15825
16426
  complete: false
15826
16427
  };
15827
16428
  const receivedAtMs = this.#receiptNow();
15828
16429
  const anchorMs = this.#blockAnchorsMs.get(blockKey);
15829
16430
  if (anchorMs === void 0 || receivedAtMs < anchorMs) this.#blockAnchorsMs.set(blockKey, receivedAtMs);
15830
16431
  if (source === "multicast") counts.multicastSymbols++;
16432
+ else if (source === "moq-datagram") counts.datagramSymbols++;
15831
16433
  else counts.moqSymbols++;
15832
16434
  this.#blockPathCounts.set(blockKey, counts);
15833
16435
  this.#observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName);
@@ -15848,7 +16450,7 @@ var FECManager = class _FECManager {
15848
16450
  this.#unindexBlockKey(key);
15849
16451
  }
15850
16452
  }
15851
- if (isSourceSymbol && source === "multicast") {
16453
+ if (isSourceSymbol && source !== "moq") {
15852
16454
  this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
15853
16455
  }
15854
16456
  return true;
@@ -15937,8 +16539,22 @@ var FECManager = class _FECManager {
15937
16539
  * DeliveryGapEstimator). Datagram delivery only.
15938
16540
  */
15939
16541
  noteMulticastArrival(packetId, packetSequenceNumber) {
15940
- if (this.#multicastSymbolDelivery !== "datagram") return;
15941
- 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)));
15942
16558
  }
15943
16559
  /**
15944
16560
  * Resolved per-track multicast late-symbol wait in milliseconds: the span
@@ -15952,16 +16568,18 @@ var FECManager = class _FECManager {
15952
16568
  * Largest multicast delivery gap measured over the current window (ms), and
15953
16569
  * that window (undefined: held since the last reset). Diagnostics.
15954
16570
  */
15955
- multicastDeliveryGap() {
16571
+ multicastDeliveryGap(path = "multicast") {
15956
16572
  return {
15957
- peakGapMs: this.#deliveryGaps.peakGapMs(performance.now()),
15958
- windowMs: this.#deliveryGaps.windowMs
16573
+ peakGapMs: this.#deliveryGaps[path].peakGapMs(performance.now()),
16574
+ windowMs: this.#deliveryGaps[path].windowMs
15959
16575
  };
15960
16576
  }
15961
16577
  /**
15962
16578
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
15963
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
15964
- * 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.
15965
16583
  */
15966
16584
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
15967
16585
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16029,8 +16647,9 @@ var FECManager = class _FECManager {
16029
16647
  return true;
16030
16648
  }
16031
16649
  /**
16032
- * Drop a block's repair hold: its FETCH ended without delivering. The block
16033
- * falls back to its multicast wait, which may already have passed.
16650
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
16651
+ * back only a repair that cannot complete it. The block falls back to its
16652
+ * multicast wait, which may already have passed.
16034
16653
  */
16035
16654
  releaseRepairHold(sbn, packetId, catalogTrackName) {
16036
16655
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16050,6 +16669,23 @@ var FECManager = class _FECManager {
16050
16669
  const config = this.#trackConfigs.get(packetId);
16051
16670
  return config === void 0 ? void 0 : this.#blockLifetimeMs(config);
16052
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
+ }
16053
16689
  /**
16054
16690
  * How long a terminal (clean, recovered or failed) block stays authoritative,
16055
16691
  * for late symbols and for the in-order release gate. It is also the gate's
@@ -16076,7 +16712,7 @@ var FECManager = class _FECManager {
16076
16712
  }
16077
16713
  const trackConfig = this.#trackConfigs.get(packetId);
16078
16714
  if (trackConfig === void 0) return void 0;
16079
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
16715
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
16080
16716
  }
16081
16717
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
16082
16718
  // -----------------------------------------------------------------------
@@ -16118,6 +16754,9 @@ var FECManager = class _FECManager {
16118
16754
  for (const key of [...this.#isoLocators.keys()]) {
16119
16755
  if (this.#belongsToPacket(key, packetId)) this.#isoLocators.delete(key);
16120
16756
  }
16757
+ for (const key of [...this.#runAnchors.keys()]) {
16758
+ if (this.#belongsToPacket(key, packetId)) this.#runAnchors.delete(key);
16759
+ }
16121
16760
  }
16122
16761
  /**
16123
16762
  * The iso-ssbg1-v1 locator horizon in blocks: every block the manager can
@@ -16167,8 +16806,9 @@ var FECManager = class _FECManager {
16167
16806
  holdIsoSource(packetId, catalogTrackName, ssId, source) {
16168
16807
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16169
16808
  const evictedBefore = locator.heldEvicted;
16170
- const held = locator.hold(ssId, source);
16171
- if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16809
+ const held = locator.hold(ssId, source.arrivedAtMs === void 0 ? { ...source, arrivedAtMs: this.#receiptNow() } : source);
16810
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16811
+ if (held && source.source !== "moq") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16172
16812
  const evicted = locator.heldEvicted - evictedBefore;
16173
16813
  if (evicted > 0) {
16174
16814
  const before = this.#isoHeldEvictedCount;
@@ -16189,17 +16829,20 @@ var FECManager = class _FECManager {
16189
16829
  * contradicts a known block is refused (counted) and must be dropped.
16190
16830
  */
16191
16831
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
16192
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
16832
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16833
+ const placement = locator.placeRepair(ssStart, ssbLength);
16834
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16193
16835
  if (placement.status !== "placed") {
16194
16836
  this.#isoRepairRefusedCount++;
16195
16837
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
16196
16838
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
16197
16839
  }
16840
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
16198
16841
  return placement;
16199
16842
  }
16843
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
16200
16844
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
16201
16845
  if (placement.hole !== void 0) {
16202
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
16203
16846
  const hole = placement.hole.block;
16204
16847
  const previous = locator.blockEndingAt(hole.start);
16205
16848
  const loss = {
@@ -16220,17 +16863,29 @@ var FECManager = class _FECManager {
16220
16863
  * `handler`, instead of a repair-less span; null restores spans. Set by the
16221
16864
  * range repair scheduler; applies to every stream from its next gap. The
16222
16865
  * handler and the deferral are one setting, so no hole is ever created with
16223
- * nobody to close it.
16866
+ * nobody to close it. `onExpired` is told of each pending hole the stream
16867
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
16868
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
16869
+ * reported; otherwise the hole is discarded with its sources.
16224
16870
  */
16225
- setUndelimitedLossHandler(handler) {
16871
+ setUndelimitedLossHandler(handler, onExpired = null) {
16226
16872
  this.#onUndelimitedLoss = handler;
16873
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
16227
16874
  this.#deferIsoGaps = handler !== null;
16228
16875
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
16229
16876
  }
16877
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
16878
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
16879
+ for (const hole of locator.takeExpiredHoles()) {
16880
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
16881
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
16882
+ }
16883
+ }
16230
16884
  /**
16231
- * The range repair for a hole ended: every hole still pending inside
16232
- * `[start, start + length)` becomes a repair-less span. Returns those spans
16233
- * with the held sources they placed, for the caller to feed (MmtpRouter).
16885
+ * The range repair for a hole ended: every hole inside `[start, start +
16886
+ * length)`, pending or expired, becomes a repair-less span. Returns those
16887
+ * spans with the held sources they placed, for the caller to feed
16888
+ * (MmtpRouter).
16234
16889
  */
16235
16890
  closeIsoHoles(packetId, catalogTrackName, start, length) {
16236
16891
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -16246,17 +16901,37 @@ var FECManager = class _FECManager {
16246
16901
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
16247
16902
  * SS_ID of which vanished resolves through its deadline like any vanished
16248
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).
16249
16915
  */
16250
16916
  #openIsoSpan(span, packetId, catalogTrackName) {
16251
16917
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
16252
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
16918
+ if (!this.#blockAuthoredLengths.has(key)) {
16919
+ this.#blockAuthoredLengths.set(key, span.block.length);
16920
+ this.#isoSpanKeys.add(key);
16921
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
16922
+ }
16253
16923
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
16254
16924
  }
16255
16925
  /**
16256
16926
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
16257
16927
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
16258
16928
  * that could hold them is pending or not yet stated by a repair, else the
16259
- * 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).
16260
16935
  *
16261
16936
  * `untracked` reads as the release gate reads it (MmtpRouter
16262
16937
  * #createFecReleaseGate): a block holding either released frame's SS_ID
@@ -16269,7 +16944,16 @@ var FECManager = class _FECManager {
16269
16944
  isoSpanResolution(packetId, catalogTrackName, fromSsId, toSsId) {
16270
16945
  if (!serial32Precedes(fromSsId, toSsId) || serial32Distance(fromSsId, toSsId) <= 1) return [];
16271
16946
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
16272
- 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;
16273
16957
  const highest = this.highestSbn(packetId, catalogTrackName);
16274
16958
  const lost = [];
16275
16959
  for (const block of locator.blocksBetween(fromSsId, toSsId)) {
@@ -16287,6 +16971,162 @@ var FECManager = class _FECManager {
16287
16971
  }
16288
16972
  return lost;
16289
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
+ }
16290
17130
  /**
16291
17131
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
16292
17132
  * the sources held now for a block no repair has stated yet, and the held
@@ -16340,11 +17180,31 @@ var FECManager = class _FECManager {
16340
17180
  * it does not. A stream with no classifier yet has shown nothing against it,
16341
17181
  * and neither has a stream without catalog timing until it releases two
16342
17182
  * RAPs inside one MPU.
16343
- */
16344
- 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) {
16345
17194
  const streamKey = this.#streamKey(packetId, catalogTrackName);
16346
17195
  if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
16347
- 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);
16348
17208
  }
16349
17209
  /** A block's class now, or frozen at its resolution. */
16350
17210
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -16367,9 +17227,11 @@ var FECManager = class _FECManager {
16367
17227
  }
16368
17228
  /**
16369
17229
  * Record a RAP frame released in order, for the classifier's RAP-spacing
16370
- * 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).
16371
17233
  */
16372
- noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
17234
+ noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale, decodeTime) {
16373
17235
  if (!this.#trackConfigs.has(packetId)) return;
16374
17236
  if (!this.#hasCatalogTimingForPacket(packetId)) {
16375
17237
  const streamKey = this.#streamKey(packetId, catalogTrackName);
@@ -16384,7 +17246,8 @@ var FECManager = class _FECManager {
16384
17246
  this.#classifierFor(packetId, catalogTrackName).noteReleasedRap(
16385
17247
  mpu,
16386
17248
  presentationTime,
16387
- mediaTimescale
17249
+ mediaTimescale,
17250
+ decodeTime
16388
17251
  )
16389
17252
  );
16390
17253
  }
@@ -16590,11 +17453,14 @@ var FECManager = class _FECManager {
16590
17453
  });
16591
17454
  client.onCleanupComplete((sbn) => {
16592
17455
  if (this.#releasedWorkerClients.has(client)) return;
16593
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
17456
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
17457
+ const cleanupKeys = owed.filter((key) => {
16594
17458
  const block = this.#parseBlockKey(key);
16595
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
17459
+ return block.packetId === packetId && block.sbn === sbn;
16596
17460
  });
16597
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
17461
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
17462
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
17463
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
16598
17464
  });
16599
17465
  client.onError((msg, code) => {
16600
17466
  const requestedKind = code ?? msg;
@@ -16664,9 +17530,11 @@ var FECManager = class _FECManager {
16664
17530
  * fail deadline already passed, so failing it is the decision that deadline
16665
17531
  * made. A late ack then finds nothing owed and is a no-op.
16666
17532
  */
16667
- #boundOwedCleanup(key, packetId, client) {
17533
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
16668
17534
  this.#clearOwedCleanupBound(key);
16669
17535
  const bound = {
17536
+ dueAtMs,
17537
+ askedAtMs: performance.now(),
16670
17538
  handle: setTimeout(() => {
16671
17539
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
16672
17540
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -16764,7 +17632,15 @@ var FECManager = class _FECManager {
16764
17632
  this.#isoSourceOversizeCount++;
16765
17633
  return null;
16766
17634
  }
16767
- const sbn = located.block.start;
17635
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
17636
+ }
17637
+ /**
17638
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
17639
+ * answers through onFrame (null here), or its synchronous decoder, whose
17640
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
17641
+ * stated for `ssId`.
17642
+ */
17643
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
16768
17644
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
16769
17645
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
16770
17646
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -16793,6 +17669,74 @@ var FECManager = class _FECManager {
16793
17669
  }
16794
17670
  return recovered;
16795
17671
  }
17672
+ /**
17673
+ * Feed a source symbol of this stream that another FEC instance over the
17674
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
17675
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
17676
+ * BLO-52085). It joins its block's decoder as a received source would, so
17677
+ * it reduces the erasures the block still has to solve, but it is not a
17678
+ * network arrival: no transport accounting, no classification evidence,
17679
+ * no deadline refresh, and it never makes a block clean.
17680
+ *
17681
+ * Only a block a repair stated takes one (a repair-less span has no
17682
+ * decoder block). A block that is terminal, or already holds that source,
17683
+ * does not. The symbol is the exact protected packet, unpadded, as
17684
+ * feedSourceSymbol takes it.
17685
+ *
17686
+ * `recovered` is the block the synchronous decoder completed with it; the
17687
+ * caller routes it and completes the block, as for any recovery. When
17688
+ * every source of the block is then present, received or rebuilt, and no
17689
+ * decoder returned it (a Worker answers asynchronously, and reports such a
17690
+ * block as clean on its own side), the block is completed here as
17691
+ * recovered, with nothing left to route.
17692
+ */
17693
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
17694
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
17695
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
17696
+ if (located === null || located.block.span) return NOT_TAKEN;
17697
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
17698
+ const sbn = located.block.start;
17699
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
17700
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
17701
+ let rebuilt = this.#blockRebuiltEsis.get(key);
17702
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
17703
+ if (rebuilt === void 0) {
17704
+ rebuilt = /* @__PURE__ */ new Set();
17705
+ this.#blockRebuiltEsis.set(key, rebuilt);
17706
+ }
17707
+ const config = this.#trackConfigs.get(packetId);
17708
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
17709
+ rebuilt.add(located.esi);
17710
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
17711
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
17712
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
17713
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
17714
+ }
17715
+ }
17716
+ return { taken: true, recovered };
17717
+ }
17718
+ /**
17719
+ * A block that holds every one of its `length` sources, received or
17720
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
17721
+ * every packet of it was delivered, by its own arrival or by the instance
17722
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
17723
+ */
17724
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
17725
+ const rebuilt = this.#blockRebuiltEsis.get(key);
17726
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
17727
+ let present = rebuilt.size;
17728
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
17729
+ if (present < length) return false;
17730
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
17731
+ this.countRecovery(packetId, sbn, catalogTrackName);
17732
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17733
+ if (catalogTrackName === void 0) {
17734
+ this.onBlockComplete?.(sbn, packetId);
17735
+ } else {
17736
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
17737
+ }
17738
+ return true;
17739
+ }
16796
17740
  /**
16797
17741
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
16798
17742
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -16854,7 +17798,10 @@ var FECManager = class _FECManager {
16854
17798
  this.#layerAnchorHorizon(packetId),
16855
17799
  this.#sourceFrontiers.get(streamKey)?.sbn
16856
17800
  );
16857
- if (verdict === "discard") return false;
17801
+ if (verdict === "discard") {
17802
+ this.#unlistedRepairTrackRefusals++;
17803
+ return false;
17804
+ }
16858
17805
  if (verdict !== void 0) {
16859
17806
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName);
16860
17807
  return false;
@@ -17003,15 +17950,17 @@ var FECManager = class _FECManager {
17003
17950
  * its sources in send order, so one that moves the stream's newest source
17004
17951
  * position past a block leaves the sources that block still misses
17005
17952
  * reordered behind it at best: it shortens the wait of every block it
17006
- * passed that only a late source can complete. MoQ is left out: its streams
17007
- * can overtake one another, so a MoQ source shows nothing about the sources
17008
- * 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.
17009
17958
  */
17010
17959
  #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
17011
17960
  const previous = locator.newestSource;
17012
17961
  if (!locator.noteSource(ssId) || previous === void 0) return;
17013
17962
  for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
17014
- if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17963
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17015
17964
  this.#shortenUnrecoverableWait(
17016
17965
  this.#blockKey(block.start, packetId, catalogTrackName),
17017
17966
  block.start,
@@ -17029,18 +17978,61 @@ var FECManager = class _FECManager {
17029
17978
  * covers repair symbols paced after its sources, buys it nothing: it waits
17030
17979
  * the late-symbol allowance alone, the multicast wait less the span (the
17031
17980
  * catalog tolerance or the measured delivery gap). Undefined for any other
17032
- * 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).
17033
17988
  */
17034
17989
  #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
17990
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
17035
17991
  const authoredLength = this.#blockAuthoredLengths.get(key);
17036
- const rsbLength = this.#blockRsbLengths.get(key);
17037
- if (authoredLength === void 0 || rsbLength === void 0) return void 0;
17038
- if ((this.#blockSourceCounts.get(key) ?? 0) + rsbLength >= authoredLength) return void 0;
17039
17992
  const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
17040
17993
  if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
17041
17994
  return void 0;
17042
17995
  }
17043
- 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;
17044
18036
  }
17045
18037
  /**
17046
18038
  * Bring an open block's wait in to its late-source wait, when it has one.
@@ -17158,12 +18150,13 @@ var FECManager = class _FECManager {
17158
18150
  * the inactivity deadline on each symbol, records the symbol's in-band
17159
18151
  * classification evidence, and marks the block clean when all of its
17160
18152
  * authored source symbols arrived: the SSB_length a repair symbol declared,
17161
- * otherwise K.
18153
+ * otherwise K. `held` marks a source held unplaced since it arrived and
18154
+ * placed only now (see #noteSbnSeen).
17162
18155
  *
17163
18156
  * Throws for a packetId that was never configured, so a classified block
17164
18157
  * never reads the manager-global K or timeout.
17165
18158
  */
17166
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
18159
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
17167
18160
  const trackConfig = this.#trackConfigs.get(packetId);
17168
18161
  if (trackConfig === void 0) {
17169
18162
  throw new Error(
@@ -17179,7 +18172,8 @@ var FECManager = class _FECManager {
17179
18172
  catalogTrackName,
17180
18173
  "source",
17181
18174
  evidence.packetSequenceNumber,
17182
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
18175
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
18176
+ held
17183
18177
  );
17184
18178
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
17185
18179
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -17215,6 +18209,15 @@ var FECManager = class _FECManager {
17215
18209
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
17216
18210
  return;
17217
18211
  }
18212
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
18213
+ key,
18214
+ sbn,
18215
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
18216
+ packetId,
18217
+ catalogTrackName
18218
+ )) {
18219
+ return;
18220
+ }
17218
18221
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
17219
18222
  }
17220
18223
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -17223,7 +18226,9 @@ var FECManager = class _FECManager {
17223
18226
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17224
18227
  this.#blockSourceCounts.delete(key);
17225
18228
  this.#blockSourceEsis.delete(key);
18229
+ this.#blockRebuiltEsis.delete(key);
17226
18230
  this.#blockAuthoredLengths.delete(key);
18231
+ this.#isoSpanKeys.delete(key);
17227
18232
  this.#blockRepairRsIds.delete(key);
17228
18233
  this.#blockRsbLengths.delete(key);
17229
18234
  this.#markTerminal(key, sbn, packetId, true);
@@ -17254,6 +18259,19 @@ var FECManager = class _FECManager {
17254
18259
  #receiptNow() {
17255
18260
  return this.#receiptAtMs ?? performance.now();
17256
18261
  }
18262
+ /**
18263
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
18264
+ * scope: counted from the receipt time, as the timer of a symbol fed when
18265
+ * it was received was, less the whole ms since. So it fires on the tick
18266
+ * that timer would have, never later than a delay counted from now, and
18267
+ * its handler still re-arms a timer that fires before its deadline.
18268
+ * Counted from now, a deadline set from the receipt time is rounded up
18269
+ * from another fraction of a ms (BLO-52085).
18270
+ */
18271
+ #receiptTimerDelayMs(deadlineMs, minMs) {
18272
+ const receivedAtMs = this.#receiptAtMs;
18273
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
18274
+ }
17257
18275
  /**
17258
18276
  * A held packet admitted late arms from its (earlier) receipt time; that
17259
18277
  * never pulls in a deadline later activity already armed. Outside a
@@ -17302,6 +18320,7 @@ var FECManager = class _FECManager {
17302
18320
  }
17303
18321
  #failBlock(sbn, packetId, catalogTrackName) {
17304
18322
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
18323
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
17305
18324
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
17306
18325
  this.#clearRepairDeadline(key);
17307
18326
  this.#clearBlockTimer(key);
@@ -17311,6 +18330,7 @@ var FECManager = class _FECManager {
17311
18330
  }
17312
18331
  this.#blockSourceCounts.delete(key);
17313
18332
  this.#blockSourceEsis.delete(key);
18333
+ this.#blockRebuiltEsis.delete(key);
17314
18334
  this.#blockAuthoredLengths.delete(key);
17315
18335
  this.#blockRepairRsIds.delete(key);
17316
18336
  this.#blockRsbLengths.delete(key);
@@ -17320,7 +18340,8 @@ var FECManager = class _FECManager {
17320
18340
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
17321
18341
  this.#fecStats.blocksFailed++;
17322
18342
  this.#statsForPacket(packetId).blocksFailed++;
17323
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18343
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18344
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
17324
18345
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
17325
18346
  }
17326
18347
  /**
@@ -17349,7 +18370,9 @@ var FECManager = class _FECManager {
17349
18370
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
17350
18371
  this.#blockSourceCounts.delete(key);
17351
18372
  this.#blockSourceEsis.delete(key);
18373
+ this.#blockRebuiltEsis.delete(key);
17352
18374
  this.#blockAuthoredLengths.delete(key);
18375
+ this.#isoSpanKeys.delete(key);
17353
18376
  this.#blockRepairRsIds.delete(key);
17354
18377
  this.#blockRsbLengths.delete(key);
17355
18378
  this.#clearBlockTimer(key);
@@ -17398,7 +18421,7 @@ var FECManager = class _FECManager {
17398
18421
  blockDeliveryProvenance(sbn, packetId, catalogTrackName) {
17399
18422
  const counts = this.blockPathCount(sbn, packetId, catalogTrackName);
17400
18423
  if (!counts) return "unknown";
17401
- if (counts.moqSymbols > 0) return "mixed";
18424
+ if (counts.moqSymbols > 0 || counts.datagramSymbols > 0) return "mixed";
17402
18425
  if (counts.multicastSymbols > 0) return "multicast";
17403
18426
  return "unknown";
17404
18427
  }
@@ -17425,7 +18448,7 @@ var FECManager = class _FECManager {
17425
18448
  this.#activeBlockDeadlinesMs.clear();
17426
18449
  this.#blockWaitDeadlinesMs.clear();
17427
18450
  this.#repairHoldUntilMs.clear();
17428
- this.#deliveryGaps.reset();
18451
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.reset();
17429
18452
  this.#pendingWorkerCleanups.clear();
17430
18453
  this.#pendingWorkerCleanupClients.clear();
17431
18454
  for (const bound of this.#pendingWorkerCleanupBounds.values()) clearTimeout(bound.handle);
@@ -17440,7 +18463,9 @@ var FECManager = class _FECManager {
17440
18463
  this.#blockKeysBySbn.clear();
17441
18464
  this.#blockSourceCounts.clear();
17442
18465
  this.#blockSourceEsis.clear();
18466
+ this.#blockRebuiltEsis.clear();
17443
18467
  this.#blockAuthoredLengths.clear();
18468
+ this.#isoSpanKeys.clear();
17444
18469
  this.#blockRepairRsIds.clear();
17445
18470
  this.#blockRsbLengths.clear();
17446
18471
  this.#heldLayerStates.clear();
@@ -17474,6 +18499,7 @@ var FECManager = class _FECManager {
17474
18499
  this.#highestSbn.clear();
17475
18500
  this.#sourceFrontiers.clear();
17476
18501
  this.#isoLocators.clear();
18502
+ this.#runAnchors.clear();
17477
18503
  this.#sourceAnchors.clear();
17478
18504
  this.#trackConfigs.clear();
17479
18505
  this.#fecDecoders.clear();
@@ -18342,6 +19368,9 @@ function authoredGap(before, after) {
18342
19368
  function ssIdAfter(a, b) {
18343
19369
  return (a - b | 0) > 0;
18344
19370
  }
19371
+ function holdsRebuilt(stream) {
19372
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
19373
+ }
18345
19374
  var FecReleaseSequencer = class {
18346
19375
  #streams = /* @__PURE__ */ new Map();
18347
19376
  #gate;
@@ -18404,6 +19433,7 @@ var FecReleaseSequencer = class {
18404
19433
  stream.lastSbn = void 0;
18405
19434
  stream.discontinuity = false;
18406
19435
  stream.rapSsId = void 0;
19436
+ stream.sourced = false;
18407
19437
  }
18408
19438
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
18409
19439
  this.#recordStat("droppedStale");
@@ -18430,6 +19460,7 @@ var FecReleaseSequencer = class {
18430
19460
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
18431
19461
  else hi = mid;
18432
19462
  }
19463
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
18433
19464
  stream.buf.splice(lo, 0, frame);
18434
19465
  this.#drainUnlessDeferred(stream);
18435
19466
  }
@@ -18465,6 +19496,41 @@ var FecReleaseSequencer = class {
18465
19496
  }
18466
19497
  return false;
18467
19498
  }
19499
+ /**
19500
+ * These streams' sink is being replaced by one that has seen no source
19501
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
19502
+ * release to the sink being replaced the frames the unanchored path had
19503
+ * already released to it (#cursorPassed): there they waited in its queue,
19504
+ * which its replacement flushes. A stream that holds none is not drained:
19505
+ * it holds nothing the anchor kept back, and a drain would still force out
19506
+ * a frame held past the hold limit, which before the anchor waited for the
19507
+ * next push. Then treat the streams as unsourced until a source frame is
19508
+ * released.
19509
+ */
19510
+ unsource(packetId, catalogTrackName) {
19511
+ for (const stream of this.#streams.values()) {
19512
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
19513
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
19514
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
19515
+ else this.#drain(stream, true);
19516
+ }
19517
+ stream.sourced = false;
19518
+ }
19519
+ }
19520
+ }
19521
+ /**
19522
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
19523
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
19524
+ * packetId.
19525
+ */
19526
+ holdsRebuilt(packetId, catalogTrackName) {
19527
+ for (const stream of this.#streams.values()) {
19528
+ if (stream.packetId !== packetId) continue;
19529
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
19530
+ if (holdsRebuilt(stream)) return true;
19531
+ }
19532
+ return false;
19533
+ }
18468
19534
  /** Re-evaluate held gaps after FEC state changed. */
18469
19535
  poke(streamKey) {
18470
19536
  if (streamKey !== void 0) {
@@ -18556,16 +19622,32 @@ var FecReleaseSequencer = class {
18556
19622
  last: null,
18557
19623
  lastSbn: void 0,
18558
19624
  discontinuity: false,
18559
- rapSsId: void 0
19625
+ rapSsId: void 0,
19626
+ sourced: false,
19627
+ draining: 0
18560
19628
  };
18561
19629
  this.#streams.set(streamKey, stream);
18562
19630
  }
18563
19631
  return stream;
18564
19632
  }
18565
- #drain(stream) {
19633
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
19634
+ #drain(stream, asUnanchored = false) {
19635
+ stream.draining++;
19636
+ try {
19637
+ this.#drainLoop(stream, asUnanchored);
19638
+ } finally {
19639
+ stream.draining--;
19640
+ }
19641
+ }
19642
+ #drainLoop(stream, asUnanchored) {
18566
19643
  while (stream.buf.length > 0 && stream.last !== null) {
18567
19644
  const head = stream.buf[0];
18568
19645
  const last = stream.last;
19646
+ if (compareFrameOrder(head, last) <= 0) {
19647
+ stream.buf.shift();
19648
+ this.#release(stream, head, void 0);
19649
+ continue;
19650
+ }
18569
19651
  if (stream.discontinuity) {
18570
19652
  stream.discontinuity = false;
18571
19653
  stream.buf.shift();
@@ -18579,9 +19661,10 @@ var FecReleaseSequencer = class {
18579
19661
  }
18580
19662
  const headSbn = head.meta.fecSbn;
18581
19663
  const from = stream.lastSbn ?? headSbn;
18582
- const to = headSbn ?? stream.lastSbn;
19664
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
18583
19665
  let lost = [];
18584
19666
  const unanchored = from === void 0 && to === void 0;
19667
+ let unresolved = false;
18585
19668
  if (from !== void 0 && to !== void 0) {
18586
19669
  const resolved = this.#gate.resolvedLoss(
18587
19670
  stream.packetId,
@@ -18590,7 +19673,8 @@ var FecReleaseSequencer = class {
18590
19673
  Math.max(from, to),
18591
19674
  from
18592
19675
  );
18593
- if (resolved === null) {
19676
+ unresolved = resolved === null;
19677
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
18594
19678
  const heldMs = performance.now() - head.arrivedAtMs;
18595
19679
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
18596
19680
  this.#recordStat("forcedWindowFlushes");
@@ -18598,22 +19682,69 @@ var FecReleaseSequencer = class {
18598
19682
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
18599
19683
  continue;
18600
19684
  }
18601
- lost = resolved;
19685
+ lost = resolved ?? [];
18602
19686
  }
18603
19687
  stream.buf.shift();
18604
19688
  this.#release(
18605
19689
  stream,
18606
19690
  head,
18607
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
19691
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
18608
19692
  );
18609
19693
  }
18610
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
+ }
19708
+ /**
19709
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
19710
+ * source cursor holds it unanchored, and neither does a later frame behind
19711
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
19712
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
19713
+ * like each frame that arrived in front of it since (stale there). The head
19714
+ * then goes, decided as it would be unanchored, once a frame the base path
19715
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
19716
+ * marked one: the base path has passed that one, so a frame still missing
19717
+ * before it can only come from a repair. It also goes while no source frame
19718
+ * has been released, when the direct path shows a recovered frame at once.
19719
+ * And it goes at once while a staged switch decides on when frames arrive
19720
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
19721
+ * sink being replaced: unanchored, it had already reached the sink.
19722
+ * The scan also writes: the `passed` marks it sets stay on the frames,
19723
+ * and push marks a frame it inserts in front of a marked one from them.
19724
+ */
19725
+ #cursorPassed(stream, asUnanchored) {
19726
+ let at2 = -1;
19727
+ for (let i = 0; i < stream.buf.length; i++) {
19728
+ const frame = stream.buf[i];
19729
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
19730
+ frame.passed = true;
19731
+ if (at2 < 0) at2 = i;
19732
+ } else if (frame.passed !== true) break;
19733
+ }
19734
+ if (at2 < 0) return false;
19735
+ return asUnanchored || !stream.sourced || this.#gate.releaseUnanchored?.(stream.packetId, stream.catalogTrackName) === true || stream.buf.some(({ meta }, i) => i > at2 && meta.fecSbnFirst === void 0 && (meta.recovered !== true || meta.fecSbn !== void 0));
19736
+ }
18611
19737
  #release(stream, frame, decision) {
19738
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
19739
+ if (stale) this.#recordStat("droppedStale");
18612
19740
  if (decision) frame.meta.gapBefore = decision;
18613
19741
  stream.last = frame;
18614
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
19742
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
19743
+ stream.lastSbn = frame.meta.fecSbn;
19744
+ }
19745
+ if (frame.meta.recovered !== true) stream.sourced = true;
18615
19746
  this.#gate.onReleased?.(frame.data, frame.meta);
18616
- this.#emit(frame.data, frame.meta);
19747
+ if (!stale) this.#emit(frame.data, frame.meta);
18617
19748
  }
18618
19749
  };
18619
19750
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -18874,11 +20005,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18874
20005
  /**
18875
20006
  * Typed view of the ISO-BMFF timing-sample budget.
18876
20007
  *
18877
- * This is the acceptance signal for the budget ratchet: `pending` walking
18878
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
18879
- * and it is observable here rather than only as media silently stopping.
18880
- * Per repo policy this is a producer-owned counter -- never infer budget
18881
- * state by parsing logs.
20008
+ * Each stream admits timing against its own window of `capacity` slots
20009
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
20010
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
20011
+ * timing a stream declared and never delivered shows up there. `pending`
20012
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
20013
+ * a producer-owned counter -- never infer budget state by parsing logs.
18882
20014
  */
18883
20015
  get timingBudgetStats() {
18884
20016
  return {
@@ -18938,6 +20070,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
18938
20070
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
18939
20071
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
18940
20072
  }
20073
+ /** See FecReleaseSequencer.unsource. */
20074
+ unsourceFecRelease(packetId, catalogTrackName) {
20075
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
20076
+ }
20077
+ /** See FecReleaseSequencer.holdsRebuilt. */
20078
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
20079
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
20080
+ }
18941
20081
  /** Re-evaluate held gaps after FEC block state changed. */
18942
20082
  pokeFecRelease(packetId, catalogTrackName) {
18943
20083
  if (!this.#fecSequencer) return;
@@ -19191,7 +20331,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19191
20331
  if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
19192
20332
  const pendingBefore = resolver2.pendingSampleCount;
19193
20333
  const evictedBefore = resolver2.evictedSampleCount;
19194
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
20334
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
19195
20335
  const admitted = resolver2.addMovieFragment(
19196
20336
  mpu.mpuSequenceNumber,
19197
20337
  data,
@@ -19264,7 +20404,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19264
20404
  info,
19265
20405
  resolver,
19266
20406
  options?.recovered === true,
19267
- options?.fecSbn
20407
+ options?.fecSbn,
20408
+ options?.fecSbnFirst
19268
20409
  );
19269
20410
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
19270
20411
  }
@@ -19357,7 +20498,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19357
20498
  info,
19358
20499
  resolver,
19359
20500
  options?.recovered === true,
19360
- options?.fecSbn
20501
+ options?.fecSbn,
20502
+ options?.fecSbnFirst
19361
20503
  );
19362
20504
  if (outcome.record !== void 0) return outcome.record;
19363
20505
  return this.#drop(outcome.reason);
@@ -19377,7 +20519,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19377
20519
  * attribution exists to keep readable. Leaving the choice at the call site
19378
20520
  * is what keeps both true.
19379
20521
  */
19380
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
20522
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
19381
20523
  const timing = resolver.sampleTiming(
19382
20524
  combined.mpuSequenceNumber,
19383
20525
  combined.movieFragmentSequenceNumber,
@@ -19394,6 +20536,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19394
20536
  );
19395
20537
  if (!meta) return { reason: "combined-meta-build-failed" };
19396
20538
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
20539
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
19397
20540
  if (!resolver.consumeSample(
19398
20541
  combined.mpuSequenceNumber,
19399
20542
  combined.movieFragmentSequenceNumber,
@@ -20827,12 +21970,12 @@ function validPort(value) {
20827
21970
  return Number.isInteger(value) && value >= 0 && value <= 65535;
20828
21971
  }
20829
21972
  function parseIpv42(address) {
20830
- const fields = address.split(".");
20831
- 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))) {
20832
21975
  throw new Error(`invalid IPv4 address ${address}`);
20833
21976
  }
20834
- const values = fields.map(Number);
20835
- 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])) {
20836
21979
  throw new Error(`invalid IPv4 address ${address}`);
20837
21980
  }
20838
21981
  return Uint8Array.from(values);
@@ -21046,7 +22189,7 @@ function bitLen(n) {
21046
22189
  return len;
21047
22190
  }
21048
22191
  var bitMask = (n) => (_1n << BigInt(n)) - _1n;
21049
- function _validateObject(object2, fields, optFields = {}) {
22192
+ function _validateObject(object2, fields2, optFields = {}) {
21050
22193
  if (!object2 || typeof object2 !== "object")
21051
22194
  throw new Error("expected valid options object");
21052
22195
  function checkField2(fieldName, expectedType, isOpt) {
@@ -21057,7 +22200,7 @@ function _validateObject(object2, fields, optFields = {}) {
21057
22200
  if (current !== expectedType || val === null)
21058
22201
  throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
21059
22202
  }
21060
- Object.entries(fields).forEach(([k, v]) => checkField2(k, v, false));
22203
+ Object.entries(fields2).forEach(([k, v]) => checkField2(k, v, false));
21061
22204
  Object.entries(optFields).forEach(([k, v]) => checkField2(k, v, true));
21062
22205
  }
21063
22206
  var notImplemented = () => {
@@ -22899,7 +24042,18 @@ function keyframeOverlaySsId(header) {
22899
24042
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
22900
24043
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
22901
24044
  }
24045
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
24046
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
24047
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
24048
+ }
24049
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
24050
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
24051
+ return headerPsn + offset >>> 0;
24052
+ }
24053
+ var OVERLAY_ROUTED_LIMIT = 1024;
24054
+ var OVERLAY_PENDING_LIMIT = 256;
22902
24055
  var OVERLAY_OFFSET_MPUS = 16;
24056
+ var OVERLAY_REBUILT_LIMIT = 256;
22903
24057
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
22904
24058
  function assertStreamIdentity(role, stream) {
22905
24059
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -23010,6 +24164,7 @@ var MmtpRouter = class {
23010
24164
  #provenance = /* @__PURE__ */ new Map();
23011
24165
  #onFlowProtected = null;
23012
24166
  #unadmittedListedDrops = 0;
24167
+ #admittedSourceDatagrams = 0;
23013
24168
  #unlistedRepairSetAside = 0;
23014
24169
  #assistBlocks = /* @__PURE__ */ new Map();
23015
24170
  #assistFailures = /* @__PURE__ */ new Map();
@@ -23026,6 +24181,20 @@ var MmtpRouter = class {
23026
24181
  /** The flow whose receiver admitted a stream's source datagrams, by packetId then catalog track name: recovered packets answer to it. */
23027
24182
  #provenanceStreamFlow = /* @__PURE__ */ new Map();
23028
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;
23029
24198
  #ambiguousRecoveredDrops = 0;
23030
24199
  // Temp state set by #processMMTP before calling parser.feed(),
23031
24200
  // read by the parser's onFrame callback for CMAF assembly + dedup.
@@ -23066,6 +24235,26 @@ var MmtpRouter = class {
23066
24235
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
23067
24236
  */
23068
24237
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
24238
+ /**
24239
+ * Per stream, the SS_ID offset at which a base recovery last showed the
24240
+ * sender's own packet_sequence_number: a recovered packet's header psn
24241
+ * equal to its SS_ID minus that offset. While it equals the stream's
24242
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
24243
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
24244
+ * an MPU no member of which arrived).
24245
+ */
24246
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
24247
+ /**
24248
+ * The same, shown by the overlay alone, before any base recovery did: a
24249
+ * packet it rebuilt whose base copy carries its protected psn
24250
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
24251
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
24252
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
24253
+ * make the base drop a late base copy of a keyframe the overlay never
24254
+ * finished, and lift a block's late-source cut, which nothing before
24255
+ * this offset did.
24256
+ */
24257
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23069
24258
  /**
23070
24259
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
23071
24260
  * not parsed, typically because its overlap copy was parsed first
@@ -23111,6 +24300,8 @@ var MmtpRouter = class {
23111
24300
  // end: a synchronous recovery completes its block BEFORE routing the
23112
24301
  // recovered frames, and releasing a held gap in between would strand them.
23113
24302
  #fecPokeDepth = 0;
24303
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
24304
+ #fecWakes = /* @__PURE__ */ new Map();
23114
24305
  #pendingFecPokes = /* @__PURE__ */ new Map();
23115
24306
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
23116
24307
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -23135,7 +24326,9 @@ var MmtpRouter = class {
23135
24326
  recovered: 0,
23136
24327
  restarts: 0,
23137
24328
  unsequencedDropped: 0,
23138
- protectedDropped: 0
24329
+ protectedDropped: 0,
24330
+ baseFed: 0,
24331
+ baseUndetermined: 0
23139
24332
  };
23140
24333
  /** Callback fired when a delta-track FEC block completes or fails. */
23141
24334
  #onDeltaBlockCompleteCb = null;
@@ -23341,13 +24534,18 @@ var MmtpRouter = class {
23341
24534
  this.#onDeltaBlockCompleteCb?.(packetId, false);
23342
24535
  }
23343
24536
  };
23344
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
24537
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
23345
24538
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
23346
24539
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
23347
24540
  this.#onDeltaBlockCompleteCb?.(packetId, true);
23348
24541
  }
23349
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23350
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
24542
+ if (span === void 0) {
24543
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
24544
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
24545
+ } else {
24546
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
24547
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
24548
+ }
23351
24549
  };
23352
24550
  }
23353
24551
  }
@@ -23372,10 +24570,11 @@ var MmtpRouter = class {
23372
24570
  const blockLifetimeMs = fec.blockLifetimeMsForPacket(packetId);
23373
24571
  if (blockSpanMs === void 0 || blockLifetimeMs === void 0) return NO_FEC_GEOMETRY_HORIZON;
23374
24572
  if (blockSpanMs === 0) return NO_BLOCK_SPAN_HORIZON;
23375
- return {
23376
- kind: "fec-horizon",
23377
- retentionMs: duplicateRetentionMs({ blockSpanMs, blockLifetimeMs })
23378
- };
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 };
23379
24578
  }
23380
24579
  /**
23381
24580
  * Init segments rejected since construction because their packetId had no
@@ -23392,8 +24591,9 @@ var MmtpRouter = class {
23392
24591
  }
23393
24592
  /**
23394
24593
  * FEC-recovered source symbols whose reconstructed header named a
23395
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
23396
- * a hop re-stamped the sequence after the sender protected the packet.
24594
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
24595
+ * or, rebuilt by the overlay, than their base copy carries: a hop
24596
+ * re-stamped the sequence after the sender protected the packet.
23397
24597
  */
23398
24598
  get restampedRecoveredSequenceCount() {
23399
24599
  return this.#restampedRecoveredSeqs;
@@ -23572,6 +24772,7 @@ var MmtpRouter = class {
23572
24772
  enableMseAssembler(packetId, config, catalogTrackName) {
23573
24773
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
23574
24774
  const previous = this.#mseAssemblers.get(assemblerKey);
24775
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
23575
24776
  if (previous) {
23576
24777
  previous.flush();
23577
24778
  previous.dispose();
@@ -23722,7 +24923,8 @@ var MmtpRouter = class {
23722
24923
  fec,
23723
24924
  k,
23724
24925
  offsets: /* @__PURE__ */ new Map(),
23725
- moqBlocks: /* @__PURE__ */ new Set()
24926
+ moqBlocks: /* @__PURE__ */ new Set(),
24927
+ rebuilt: /* @__PURE__ */ new Map()
23726
24928
  };
23727
24929
  this.#overlays.set(repairPacketId, inst);
23728
24930
  return () => {
@@ -23752,12 +24954,18 @@ var MmtpRouter = class {
23752
24954
  */
23753
24955
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
23754
24956
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
24957
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
24958
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
24959
+ stream.overlayToBase.routed.clear();
24960
+ stream.overlayToBase.pending.clear();
24961
+ }
23755
24962
  }
23756
24963
  #resetOverlay(inst) {
23757
24964
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
23758
24965
  inst.last = void 0;
23759
24966
  inst.offsets.clear();
23760
24967
  inst.moqBlocks.clear();
24968
+ inst.rebuilt.clear();
23761
24969
  }
23762
24970
  #overlaysForSource(sourcePacketId, catalogTrackName) {
23763
24971
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -23789,7 +24997,7 @@ var MmtpRouter = class {
23789
24997
  const blockStart = placement.block.start;
23790
24998
  if (placement.span !== void 0) this.#replayOverlaySources(inst, placement.span.block.start, placement.span.placed);
23791
24999
  this.#replayOverlaySources(inst, blockStart, placement.placed);
23792
- if (source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
25000
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
23793
25001
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
23794
25002
  const recovered = fec.feedRepairSymbol(pid, repair.ssStart, repair.ssbLength, repair.rsId, repair.symbolData, name);
23795
25003
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, blockStart, recovered);
@@ -23797,7 +25005,7 @@ var MmtpRouter = class {
23797
25005
  #replayOverlaySources(inst, blockStart, placed) {
23798
25006
  const { fec, repairPacketId: pid, streamName: name } = inst;
23799
25007
  for (const { ssId, payload } of placed) {
23800
- if (payload.source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
25008
+ if (payload.source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
23801
25009
  if (payload.oversized) continue;
23802
25010
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
23803
25011
  const recovered = fec.feedSourceSymbol(pid, ssId, payload.symbolData, name);
@@ -23808,18 +25016,33 @@ var MmtpRouter = class {
23808
25016
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
23809
25017
  * every overlay installed for its source, at that SS_ID, with the bytes the
23810
25018
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
23811
- * included (7.1, 7.4.3).
23812
- */
23813
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
25019
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
25020
+ * FEC reads it.
25021
+ *
25022
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
25023
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
25024
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
25025
+ * the stream unstamped at the SS_ID offset it states, for the release gate
25026
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
25027
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
25028
+ */
25029
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
23814
25030
  if (this.#overlays.size === 0) return;
23815
25031
  const ssId = keyframeOverlaySsId(header);
23816
25032
  if (ssId === void 0) return;
25033
+ let rebuiltPsn;
23817
25034
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
23818
25035
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
25036
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
25037
+ inst.rebuilt.delete(ssId);
23819
25038
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
23820
25039
  if (identity !== null) {
23821
25040
  inst.offsets.delete(identity.mpuSequenceNumber);
23822
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
25041
+ inst.offsets.set(identity.mpuSequenceNumber, {
25042
+ psnOffset: ssId - sequenceNumber >>> 0,
25043
+ overlaySsId: ssId,
25044
+ ...baseSsId === void 0 ? {} : { baseSsId }
25045
+ });
23823
25046
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
23824
25047
  }
23825
25048
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23835,12 +25058,20 @@ var MmtpRouter = class {
23835
25058
  });
23836
25059
  continue;
23837
25060
  }
23838
- if (source === "moq") this.#noteOverlayMoqBlock(inst, coords.sbn);
25061
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, coords.sbn);
23839
25062
  if (oversized) continue;
23840
25063
  const alreadyCompleted = fec.isBlockCompleted(coords.sbn, pid, name);
23841
25064
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
23842
25065
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
23843
25066
  }
25067
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
25068
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
25069
+ if (rebuiltPsn !== sequenceNumber) {
25070
+ this.#restampedRecoveredSeqs++;
25071
+ } else if (baseSsId !== void 0) {
25072
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
25073
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
25074
+ }
23844
25075
  }
23845
25076
  #noteOverlayMoqBlock(inst, blockStart) {
23846
25077
  inst.moqBlocks.add(blockStart);
@@ -23874,11 +25105,16 @@ var MmtpRouter = class {
23874
25105
  }
23875
25106
  /**
23876
25107
  * Route an overlay-recovered block's packets as source media of the
23877
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
23878
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
23879
- * base re-stamp, no block advance. Each packet's wire sequence is restored
23880
- * from its keyframe's own offset; without one, a stream the base never
23881
- * re-stamped keeps the header's sequence and any other drops the packet.
25108
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
25109
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
25110
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
25111
+ * base FEC recovered does, so it waits behind base frames still in flight,
25112
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
25113
+ * longer than unanchored; one whose base SS_ID is undetermined has no
25114
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
25115
+ * advance. Each packet's wire sequence is restored from its keyframe's own
25116
+ * offset; without one, a stream the base never re-stamped keeps the
25117
+ * header's sequence and any other drops the packet.
23882
25118
  */
23883
25119
  #routeOverlayRecovered(inst, blockStart, recovered) {
23884
25120
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23898,22 +25134,139 @@ var MmtpRouter = class {
23898
25134
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
23899
25135
  const restamped = this.#restampedStreams.has(streamKey);
23900
25136
  const restored = /* @__PURE__ */ new Set();
25137
+ const baseSsIds = /* @__PURE__ */ new Map();
25138
+ const gateOnly = /* @__PURE__ */ new Set();
23901
25139
  const symbols = result.symbols.flatMap((sym) => {
23902
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
23903
- if (offset !== void 0) {
23904
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
25140
+ const overlaySsId = serial32Add(blockStart, sym.index);
25141
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
25142
+ if (anchor !== void 0) {
25143
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
23905
25144
  restored.add(packetSequenceNumber);
23906
- return [{ ...sym, packetSequenceNumber }];
25145
+ const out = { ...sym, packetSequenceNumber };
25146
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
25147
+ if (baseSsId !== void 0) {
25148
+ baseSsIds.set(sym.index, baseSsId);
25149
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
25150
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
25151
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
25152
+ }
25153
+ }
25154
+ return [out];
25155
+ }
25156
+ if (!restamped) {
25157
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
25158
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
25159
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
25160
+ if (baseSsId !== void 0) {
25161
+ baseSsIds.set(sym.index, baseSsId);
25162
+ if (fedSsId === void 0) gateOnly.add(sym.index);
25163
+ } else {
25164
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
25165
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
25166
+ }
25167
+ return [sym];
23907
25168
  }
23908
- if (!restamped) return [sym];
23909
25169
  this.#overlayStats.unsequencedDropped++;
23910
25170
  return [];
23911
25171
  });
23912
25172
  this.#overlayStats.recovered++;
25173
+ const mpuFirst = /* @__PURE__ */ new Map();
25174
+ for (const sym of symbols) {
25175
+ const ssId = baseSsIds.get(sym.index);
25176
+ const mpu = sym.fragment.mpuSequenceNumber;
25177
+ const first = mpuFirst.get(mpu);
25178
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
25179
+ }
25180
+ const firstSsIds = /* @__PURE__ */ new Map();
25181
+ for (const sym of symbols) {
25182
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
25183
+ }
23913
25184
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
23914
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
25185
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
25186
+ baseSsIds,
25187
+ firstSsIds
23915
25188
  });
23916
25189
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
25190
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
25191
+ }
25192
+ /**
25193
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
25194
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
25195
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
25196
+ * base recovery showed; `baseSsIds` holds no other),
25197
+ * so it is fed to the base decoder as a rebuilt source
25198
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
25199
+ * fewer to solve, and its repair can recover the block's other packets.
25200
+ * A base block no repair has stated yet takes it when one does
25201
+ * (#feedPendingRebuilt).
25202
+ *
25203
+ * The overlay route already handled each packet fed (delivered it, or
25204
+ * held an untimed head for its FT=1), so a base recovery routes none of
25205
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
25206
+ * held head would wait in the parser for timing its first copy consumed.
25207
+ * Only an overlay block decoded from multicast symbols alone is fed: with
25208
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
25209
+ * that crossed no multicast socket, which the provenance counted from the
25210
+ * block's own arrivals cannot show.
25211
+ */
25212
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
25213
+ const fec = this.#fecManager;
25214
+ const owner = inst.leg.sourcePacketId;
25215
+ const name = inst.leg.sourceCatalogTrackName;
25216
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
25217
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
25218
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
25219
+ const feeds = [];
25220
+ for (const sym of symbols) {
25221
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
25222
+ const ssId = baseSsIds.get(sym.index);
25223
+ if (ssId === void 0) {
25224
+ this.#overlayStats.baseUndetermined++;
25225
+ continue;
25226
+ }
25227
+ routed.delete(ssId);
25228
+ routed.add(ssId);
25229
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
25230
+ feeds.push([ssId, sym.rawSymbol]);
25231
+ }
25232
+ for (const [ssId, symbolData] of feeds) {
25233
+ if (this.#classifyPacketId(owner) === null) return;
25234
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
25235
+ }
25236
+ }
25237
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
25238
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
25239
+ const fec = this.#fecManager;
25240
+ if (!fec?.feedRebuiltSourceSymbol) return;
25241
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
25242
+ if (coords == null) {
25243
+ const pending = this.#stream(owner, name).overlayToBase.pending;
25244
+ pending.delete(ssId);
25245
+ pending.set(ssId, symbolData.slice());
25246
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
25247
+ return;
25248
+ }
25249
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
25250
+ if (!fed.taken) return;
25251
+ this.#overlayStats.baseFed++;
25252
+ if (fed.recovered === null) return;
25253
+ const sbn = coords.sbn;
25254
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
25255
+ fec.cancelBlockTimeout(sbn, owner, name);
25256
+ fec.countRecovery(owner, sbn, name);
25257
+ fec.markBlockCompleted(sbn, owner, name);
25258
+ });
25259
+ }
25260
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
25261
+ #feedPendingRebuilt(owner, name, block) {
25262
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
25263
+ if (pending === void 0 || pending.size === 0) return;
25264
+ for (const [ssId, symbolData] of [...pending]) {
25265
+ if (this.#classifyPacketId(owner) === null) return;
25266
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
25267
+ pending.delete(ssId);
25268
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
25269
+ }
23917
25270
  }
23918
25271
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
23919
25272
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -24053,6 +25406,10 @@ var MmtpRouter = class {
24053
25406
  get unadmittedListedDropCount() {
24054
25407
  return this.#unadmittedListedDrops;
24055
25408
  }
25409
+ /** Source datagrams (multicast or MoQ) a protected flow's bc-provenance v2 receiver released: admitted at once or held, then admitted by a record. Repair symbols and user-agent-admitted datagrams are not counted. Counted at release, before this router's own track checks: a released datagram those drop, which only a track change between hold and release can cause, still counts, so this is not a count of routed media. */
25410
+ get admittedSourceDatagramCount() {
25411
+ return this.#admittedSourceDatagrams;
25412
+ }
24056
25413
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
24057
25414
  get unlistedRepairSetAsideCount() {
24058
25415
  return this.#unlistedRepairSetAside;
@@ -24290,6 +25647,46 @@ var MmtpRouter = class {
24290
25647
  get unregisteredFlowDropCount() {
24291
25648
  return this.#unregisteredFlowDrops;
24292
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
+ }
24293
25690
  /** Recovered packets dropped because more than one protected flow could own their stream. */
24294
25691
  get ambiguousRecoveredDropCount() {
24295
25692
  return this.#ambiguousRecoveredDrops;
@@ -24307,6 +25704,10 @@ var MmtpRouter = class {
24307
25704
  * caller that forgot it silently attributed its bytes to a multicast socket
24308
25705
  * they may never have crossed — and that attribution is what the physical-
24309
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).
24310
25711
  */
24311
25712
  feedPacket(packet, source, ingress) {
24312
25713
  if (this.#disposed) return;
@@ -24356,15 +25757,18 @@ var MmtpRouter = class {
24356
25757
  }
24357
25758
  /**
24358
25759
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
24359
- * 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`).
24360
25764
  */
24361
- feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
25765
+ feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source = "moq") {
24362
25766
  if (this.#disposed) return;
24363
25767
  this.#withDeferredFecPokes(() => {
24364
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
25768
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source);
24365
25769
  });
24366
25770
  }
24367
- #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, admitted = false) {
25771
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source, admitted = false) {
24368
25772
  let header;
24369
25773
  try {
24370
25774
  header = parseMMTPHeader(packet);
@@ -24374,7 +25778,7 @@ var MmtpRouter = class {
24374
25778
  const repairPacketId = header.packetId;
24375
25779
  const overlay = this.#overlayRepairTarget(repairPacketId, repairTrackName);
24376
25780
  if (overlay !== void 0) {
24377
- this.#routeOverlayRepair(overlay, repairPacketId, packet, header, "moq");
25781
+ this.#routeOverlayRepair(overlay, repairPacketId, packet, header, source);
24378
25782
  return;
24379
25783
  }
24380
25784
  const hintedOwner = ownerPacketIdHint != null && this.#classifyPacketId(ownerPacketIdHint) !== null ? ownerPacketIdHint : null;
@@ -24386,7 +25790,7 @@ var MmtpRouter = class {
24386
25790
  }
24387
25791
  let unlisted = false;
24388
25792
  if (ownerPacketId != null && !admitted) {
24389
- 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));
24390
25794
  if (admit === "held" || admit === "dropped") return;
24391
25795
  unlisted = admit === "unlisted";
24392
25796
  }
@@ -24407,7 +25811,7 @@ var MmtpRouter = class {
24407
25811
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
24408
25812
  return;
24409
25813
  }
24410
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
25814
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, source, repairTrackName);
24411
25815
  }
24412
25816
  }
24413
25817
  // ── Packet FEC geometry and block profile ───────────────────────
@@ -24539,6 +25943,8 @@ var MmtpRouter = class {
24539
25943
  )) return;
24540
25944
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
24541
25945
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
25946
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
25947
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
24542
25948
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
24543
25949
  const recovered = fec.feedRepairSymbol(
24544
25950
  ownerPacketId,
@@ -24589,7 +25995,7 @@ var MmtpRouter = class {
24589
25995
  catalogTrackName
24590
25996
  )) continue;
24591
25997
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
24592
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
25998
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
24593
25999
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
24594
26000
  }
24595
26001
  if (payload.oversized) continue;
@@ -24610,6 +26016,7 @@ var MmtpRouter = class {
24610
26016
  debugRouter(
24611
26017
  `[MmtpRouter] Dropping repair packet pid=${packetId}: physical PID is unregistered`
24612
26018
  );
26019
+ this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
24613
26020
  return null;
24614
26021
  }
24615
26022
  const registeredOwners = this.#repairOwnersByPacketId.get(packetId) ?? /* @__PURE__ */ new Set();
@@ -24618,6 +26025,7 @@ var MmtpRouter = class {
24618
26025
  debugRouter(
24619
26026
  `[MmtpRouter] Dropping repair packet pid=${packetId}: catalog owner is ${owners.length === 0 ? "absent" : "ambiguous"}`
24620
26027
  );
26028
+ this.#fecManager?.countUnresolvedRepairOwner?.(owners.length === 0 ? "ownerAbsent" : "ownerAmbiguous");
24621
26029
  return null;
24622
26030
  }
24623
26031
  /** Route a recovered FEC block through the parser + dedup pipeline.
@@ -24667,6 +26075,8 @@ var MmtpRouter = class {
24667
26075
  }
24668
26076
  this.#parser.resetTrack(packetId, catalogTrackName);
24669
26077
  this.resetKeyframeOverlays(packetId, catalogTrackName);
26078
+ const legNames = this.#datagramLegStreams.get(packetId);
26079
+ if (legNames?.delete(catalogTrackName) && legNames.size === 0) this.#datagramLegStreams.delete(packetId);
24670
26080
  this.#restampedStreams.delete(this.#mediaStreamKey(packetId, catalogTrackName));
24671
26081
  const assistPrefix = assistKey(packetId, catalogTrackName, 0).slice(0, -1);
24672
26082
  for (const key of this.#assistBlocks.keys()) if (key.startsWith(assistPrefix)) this.#assistBlocks.delete(key);
@@ -24676,6 +26086,8 @@ var MmtpRouter = class {
24676
26086
  this.#droppedPreSyncVideo.delete(streamKey);
24677
26087
  this.#latestVideoSeqByStream.delete(streamKey);
24678
26088
  this.#ssIdSeqOffsetByStream.delete(streamKey);
26089
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
26090
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
24679
26091
  this.#multicastRapTwinByStream.delete(streamKey);
24680
26092
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
24681
26093
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -24802,6 +26214,12 @@ var MmtpRouter = class {
24802
26214
  * the outgoing stream stops. The hold is bounded by the incoming stream's
24803
26215
  * own RAP cadence, so no timer is involved.
24804
26216
  *
26217
+ * While the switch is staged, the FEC release gate lets a keyframe the
26218
+ * overlay rebuilt reach it, on either side, when the keyframe did before
26219
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
26220
+ * decides on what each side delivered, and the commit discards the gate's
26221
+ * frames of the outgoing stream.
26222
+ *
24805
26223
  * The commit is one synchronous transition inside the frame path: the
24806
26224
  * outgoing stream's already-admitted frames are released (its queued FEC
24807
26225
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -24852,6 +26270,9 @@ var MmtpRouter = class {
24852
26270
  droppedIncomingFrames: 0
24853
26271
  };
24854
26272
  this.#staged = state;
26273
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
26274
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
26275
+ }
24855
26276
  return {
24856
26277
  cancel: () => {
24857
26278
  if (this.#staged !== state) return false;
@@ -24934,7 +26355,17 @@ var MmtpRouter = class {
24934
26355
  */
24935
26356
  #routeParsedFrame(data, meta) {
24936
26357
  if (this.#classifyPacketId(meta.packetId) === null) return;
24937
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
26358
+ if (this.#staged !== null) {
26359
+ let consumed = false;
26360
+ this.#fecPokeDepth++;
26361
+ try {
26362
+ consumed = this.#interceptSwitchFrame(data, meta);
26363
+ } finally {
26364
+ this.#fecPokeDepth--;
26365
+ this.#flushPendingFecPokes();
26366
+ }
26367
+ if (consumed) return;
26368
+ }
24938
26369
  this.#deliverParsedFrame(data, meta);
24939
26370
  }
24940
26371
  #commitStreamSwitch(state, rap, reason) {
@@ -24983,8 +26414,11 @@ var MmtpRouter = class {
24983
26414
  this.#disposed = true;
24984
26415
  this.#staged = null;
24985
26416
  this.cancelKeyframeLostTimer();
26417
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
26418
+ this.#fecWakes.clear();
24986
26419
  this.#parser.dispose();
24987
26420
  this.#streams.clear();
26421
+ this.endDatagramLeg();
24988
26422
  this.#trackPacketCallbacks.clear();
24989
26423
  this.#latestVideoSeqByStream.clear();
24990
26424
  this.#lastDirectSourceVideoTsByStream.clear();
@@ -25086,12 +26520,16 @@ var MmtpRouter = class {
25086
26520
  this.#parser.deferFecRelease(work);
25087
26521
  } finally {
25088
26522
  this.#fecPokeDepth--;
25089
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
25090
- const pokes = [...this.#pendingFecPokes.values()];
25091
- this.#pendingFecPokes.clear();
25092
- for (const poke of pokes) {
25093
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
25094
- }
26523
+ this.#flushPendingFecPokes();
26524
+ }
26525
+ }
26526
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
26527
+ #flushPendingFecPokes() {
26528
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
26529
+ const pokes = [...this.#pendingFecPokes.values()];
26530
+ this.#pendingFecPokes.clear();
26531
+ for (const poke of pokes) {
26532
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
25095
26533
  }
25096
26534
  }
25097
26535
  }
@@ -25160,6 +26598,38 @@ var MmtpRouter = class {
25160
26598
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
25161
26599
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
25162
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
+ },
25163
26633
  decide: (before, after, lostBlocks, discontinuity) => {
25164
26634
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
25165
26635
  this.#onFrameGap?.(decision);
@@ -25169,6 +26639,28 @@ var MmtpRouter = class {
25169
26639
  onRap: (packetId, catalogTrackName, ssId) => {
25170
26640
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
25171
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
+ },
26656
+ // A staged switch commits on when each side's frames reach it
26657
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
26658
+ // they did unanchored.
26659
+ releaseUnanchored: (packetId, catalogTrackName) => {
26660
+ const staged = this.#staged;
26661
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
26662
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
26663
+ },
25172
26664
  onReleased: (data, meta) => {
25173
26665
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
25174
26666
  const timing = meta.authoredTiming;
@@ -25178,7 +26670,8 @@ var MmtpRouter = class {
25178
26670
  meta.catalogTrackName,
25179
26671
  meta.mpuSequenceNumber,
25180
26672
  timing.presentationTime,
25181
- timing.mediaTimescale
26673
+ timing.mediaTimescale,
26674
+ timing.decodeTime
25182
26675
  );
25183
26676
  }
25184
26677
  };
@@ -25196,8 +26689,20 @@ var MmtpRouter = class {
25196
26689
  #decideGap(before, after, lostBlocks, discontinuity) {
25197
26690
  const { packetId, catalogTrackName } = after.meta;
25198
26691
  const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
25199
- const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying";
25200
- 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;
25201
26706
  const evidence = (frame) => {
25202
26707
  const timing = frame.meta.authoredTiming;
25203
26708
  const sampleNumber = frame.meta.sampleNumber;
@@ -25310,20 +26815,37 @@ var MmtpRouter = class {
25310
26815
  const parsed = this.#parser.parsePacket(packet);
25311
26816
  if (!parsed) return;
25312
26817
  const info = parsed.info;
26818
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
25313
26819
  if (source === "multicast" && !manifestAdmitted) {
25314
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);
25315
26823
  }
25316
- 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
+ }
25317
26829
  debugRouter(
25318
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: absent from ingress tracks`
26830
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: absent from ingress tracks`
25319
26831
  );
25320
26832
  return;
25321
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
+ }
25322
26843
  const packetRole = this.#packetIdRoles.get(info.packetId);
25323
- 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")) {
25324
26845
  debugRouter(
25325
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: physical PID is unregistered`
26846
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: physical PID is unregistered`
25326
26847
  );
26848
+ if (info.isRepair) this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
25327
26849
  return;
25328
26850
  }
25329
26851
  if (!info.isRepair && hasAmbiguousCatalogTrackName(ingress, info.packetId)) {
@@ -25359,7 +26881,7 @@ var MmtpRouter = class {
25359
26881
  }
25360
26882
  return;
25361
26883
  }
25362
- if (source === "moq" && !manifestAdmitted) {
26884
+ if (source !== "multicast" && !manifestAdmitted) {
25363
26885
  const admit = this.#admitUnicast(info.packetId, packet, () => this.#processMMTP(packet, source, true, ingress, overlapCopy, true), overlapCopy);
25364
26886
  if (admit !== "unlisted") {
25365
26887
  if (admit === "admitted") this.#processMMTP(packet, source, true, ingress, overlapCopy);
@@ -25388,7 +26910,7 @@ var MmtpRouter = class {
25388
26910
  );
25389
26911
  if (!repair) return;
25390
26912
  if (ownerPacketId != null && this.#fecManager) {
25391
- 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;
25392
26914
  this.#repairPidCounts[info.packetId] = (this.#repairPidCounts[info.packetId] || 0) + 1;
25393
26915
  const count = this.#repairPidCounts[info.packetId];
25394
26916
  if (count <= 2 || count % 500 === 0) {
@@ -25427,7 +26949,7 @@ var MmtpRouter = class {
25427
26949
  const fecSource = this.#fecManager !== null && fecPayloadId != null;
25428
26950
  const coords = fecSource && fecPayloadId ? this.#locateFecSource(info.packetId, catalogTrackName, fecPayloadId.ssId) ?? void 0 : void 0;
25429
26951
  duplicates.advance(coords?.sbn);
25430
- 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)) {
25431
26953
  this.#publisherRestarts++;
25432
26954
  console.warn(
25433
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`
@@ -25488,6 +27010,7 @@ var MmtpRouter = class {
25488
27010
  evidence: sourceSymbolEvidence(packet, parsed.header, info.rapFlag, info.sequenceNumber),
25489
27011
  oversized: !(this.#fecManager.isoSourceFits?.(info.packetId, rawSymbol.length) ?? false)
25490
27012
  }) ?? false;
27013
+ if (held) this.#requestFecPoke(info.packetId, catalogTrackName);
25491
27014
  parseSourceSymbol = held && !duplicates.parsedSymbols.has(ssId);
25492
27015
  }
25493
27016
  } else if (fecUnreadable && info.fecPayloadId) {
@@ -25591,7 +27114,8 @@ var MmtpRouter = class {
25591
27114
  parsed.header,
25592
27115
  info.sequenceNumber,
25593
27116
  info.rapFlag,
25594
- source
27117
+ source,
27118
+ fecPayloadId?.ssId
25595
27119
  );
25596
27120
  }
25597
27121
  }
@@ -25614,10 +27138,13 @@ var MmtpRouter = class {
25614
27138
  const feedOptions = {
25615
27139
  skipFecPayloadId: parserOptions?.skipFecPayloadId,
25616
27140
  recovered: parserOptions?.recovered,
25617
- 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,
25618
27144
  deliveryProvenance: parserOptions?.deliveryProvenance,
25619
27145
  catalogTrackName: parserOptions?.catalogTrackName,
25620
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
27146
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
27147
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
25621
27148
  };
25622
27149
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
25623
27150
  else this.#parser.feed(packet, feedOptions);
@@ -25741,7 +27268,8 @@ var MmtpRouter = class {
25741
27268
  if (stream === void 0) {
25742
27269
  stream = {
25743
27270
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
25744
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
27271
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
27272
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
25745
27273
  };
25746
27274
  byName.set(catalogTrackName, stream);
25747
27275
  }
@@ -26019,6 +27547,13 @@ var MmtpRouter = class {
26019
27547
  * frames by epoch only if pre-protection input ever matters.
26020
27548
  */
26021
27549
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
27550
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
27551
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
27552
+ result = {
27553
+ ...result,
27554
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
27555
+ };
27556
+ }
26022
27557
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
26023
27558
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
26024
27559
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -26075,7 +27610,12 @@ var MmtpRouter = class {
26075
27610
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
26076
27611
  if (ownerPacketId == null) return;
26077
27612
  if (this.#classifyPacketId(ownerPacketId) === null) return;
26078
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
27613
+ const fecSbnOf = (index) => {
27614
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
27615
+ const fecSbn = overlay.baseSsIds.get(index);
27616
+ const fecSbnFirst = overlay.firstSsIds.get(index);
27617
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
27618
+ };
26079
27619
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
26080
27620
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
26081
27621
  if (ssIdSeqOffset !== void 0) {
@@ -26083,7 +27623,10 @@ var MmtpRouter = class {
26083
27623
  ...result,
26084
27624
  symbols: result.symbols.map((sym) => {
26085
27625
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
26086
- if (wire === sym.packetSequenceNumber) return sym;
27626
+ if (wire === sym.packetSequenceNumber) {
27627
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
27628
+ return sym;
27629
+ }
26087
27630
  this.#restampedRecoveredSeqs++;
26088
27631
  this.#restampedStreams.add(streamKey);
26089
27632
  return { ...sym, packetSequenceNumber: wire };
@@ -26857,14 +28400,14 @@ function createWasmMmtpContainerParser(config) {
26857
28400
  var JOIN_SUCCEEDED = Object.freeze({ ok: true });
26858
28401
  function providerErrorOf(error) {
26859
28402
  if (typeof error !== "object" || error === null) return void 0;
26860
- const fields = error;
28403
+ const fields2 = error;
26861
28404
  let name;
26862
28405
  let message;
26863
28406
  let code;
26864
28407
  try {
26865
- name = fields.name;
26866
- message = fields.message;
26867
- code = fields.code;
28408
+ name = fields2.name;
28409
+ message = fields2.message;
28410
+ code = fields2.code;
26868
28411
  } catch {
26869
28412
  return void 0;
26870
28413
  }
@@ -27762,6 +29305,7 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
27762
29305
  stalls: 0,
27763
29306
  concealedBlocks: 0,
27764
29307
  concealedGaps: 0,
29308
+ undelimitedRunGaps: 0,
27765
29309
  concealedFrames: 0,
27766
29310
  concealedAudioMs: 0,
27767
29311
  vanishedBlocks: 0
@@ -27868,6 +29412,12 @@ function isNonNegativeSafeInteger(value) {
27868
29412
  function isSymbolCounts(value) {
27869
29413
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
27870
29414
  }
29415
+ function isSpanFailure(value) {
29416
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
29417
+ const length = value["length"];
29418
+ const sources = value["sources"];
29419
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
29420
+ }
27871
29421
  function isNullableNonNegative(value) {
27872
29422
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
27873
29423
  }
@@ -27887,7 +29437,10 @@ function isRepairLifecycleEvent(value) {
27887
29437
  case "recovered":
27888
29438
  return hasExactKeys(value, ["version", "type", "block", "blockClass", "via", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && (value["via"] === "inband" || value["via"] === "quic") && isSymbolCounts(value["symbols"]);
27889
29439
  case "failed":
27890
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
29440
+ return hasExactKeys(
29441
+ value,
29442
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
29443
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
27891
29444
  case "repair-preempted":
27892
29445
  case "repair-deferred":
27893
29446
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -28096,6 +29649,8 @@ var MulticastManager = class {
28096
29649
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
28097
29650
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
28098
29651
  #repairReleases = /* @__PURE__ */ new Map();
29652
+ /** Protected repair flows owned by each live repair-endpoint release. */
29653
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
28099
29654
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
28100
29655
  #overlayBindings = /* @__PURE__ */ new Map();
28101
29656
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -28153,7 +29708,7 @@ var MulticastManager = class {
28153
29708
  onPublisherRestart: (packetId, catalogTrackName) => {
28154
29709
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
28155
29710
  },
28156
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
29711
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
28157
29712
  const pathCount = this.#fec.blockPathCount(
28158
29713
  sbn,
28159
29714
  packetId,
@@ -28171,7 +29726,8 @@ var MulticastManager = class {
28171
29726
  symbols: {
28172
29727
  multicast: pathCount?.multicastSymbols ?? 0,
28173
29728
  moq: pathCount?.moqSymbols ?? 0
28174
- }
29729
+ },
29730
+ ...span === void 0 ? {} : { span }
28175
29731
  });
28176
29732
  },
28177
29733
  onFrameGap: (decision) => {
@@ -28256,9 +29812,17 @@ var MulticastManager = class {
28256
29812
  reason
28257
29813
  });
28258
29814
  };
29815
+ this.#fec.onUndelimitedRunGap = (packetId, catalogTrackName) => {
29816
+ this.#statsFor(packetId, catalogTrackName).undelimitedRunGaps++;
29817
+ };
28259
29818
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
28260
29819
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
28261
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
+ };
28262
29826
  this.#fec.onDecoderUnavailable = (event) => {
28263
29827
  this.#emitRepairLifecycle({
28264
29828
  version: 2,
@@ -28555,6 +30119,7 @@ var MulticastManager = class {
28555
30119
  assertPositiveGeometry("timescale", config.timescale);
28556
30120
  assertPositiveGeometry("keyframeIntervalTicks", config.keyframeIntervalTicks);
28557
30121
  assertPositiveGeometry("keyframeIntervalMs", config.keyframeIntervalMs);
30122
+ assertPositiveGeometry("groupDurationMs", config.groupDurationMs);
28558
30123
  assertNonNegativeGeometry("fecRepairSymbols", config.fecRepairSymbols);
28559
30124
  assertNonNegativeGeometry(
28560
30125
  "fecReorderToleranceMs",
@@ -28587,7 +30152,8 @@ var MulticastManager = class {
28587
30152
  timeoutMs: deliveryWindowMs,
28588
30153
  ...trackKind === void 0 ? {} : { trackKind },
28589
30154
  ...config.codec === void 0 ? {} : { codec: config.codec },
28590
- ...geometry2 === void 0 ? {} : { geometry: geometry2 }
30155
+ ...geometry2 === void 0 ? {} : { geometry: geometry2 },
30156
+ ...config.groupDurationMs === void 0 ? {} : { groupDurationMs: config.groupDurationMs }
28591
30157
  };
28592
30158
  this.#fec.configureTrack(packetId, fecConfig, catalogTrackName);
28593
30159
  this.#configureTrackMapper(packetId, fecConfig);
@@ -28761,6 +30327,9 @@ var MulticastManager = class {
28761
30327
  this.#transport.onFailback((reason) => {
28762
30328
  const joined = this.#provenanceJoin;
28763
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
+ }
28764
30333
  this.#onFailback?.(reason);
28765
30334
  });
28766
30335
  }
@@ -28795,6 +30364,12 @@ var MulticastManager = class {
28795
30364
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
28796
30365
  );
28797
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
+ }
28798
30373
  const staged = this.#renditionSwitch;
28799
30374
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
28800
30375
  this.configureFec(config);
@@ -28802,8 +30377,8 @@ var MulticastManager = class {
28802
30377
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
28803
30378
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
28804
30379
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
28805
- this.#releaseProvenanceJoin();
28806
30380
  const provenance = config.provenance;
30381
+ this.#releaseProvenanceJoin();
28807
30382
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
28808
30383
  const ingress = protectedTracks === void 0 ? void 0 : {
28809
30384
  tracks: Object.freeze(
@@ -28856,8 +30431,13 @@ var MulticastManager = class {
28856
30431
  * feeds the flow's receiver; media datagrams are held until one admits them.
28857
30432
  */
28858
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) {
28859
30439
  const { flow, auth } = provenance;
28860
- const receiver = new BcProvenanceV2Receiver({
30440
+ return new BcProvenanceV2Receiver({
28861
30441
  ...provenance.receiver,
28862
30442
  // The caller's ctx when it passes one, else the catalog's: an explicit
28863
30443
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -28874,9 +30454,6 @@ var MulticastManager = class {
28874
30454
  maxAuthDelayMs: flow.maxAuthDelayMs,
28875
30455
  manifestTimerMs: flow.manifestTimerMs
28876
30456
  });
28877
- this.#router.registerProvenanceFlow(ingress, receiver);
28878
- this.#hookFailback();
28879
- this.#provenanceJoin = { flow: ingress.flow };
28880
30457
  }
28881
30458
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
28882
30459
  #releaseProvenanceJoin() {
@@ -28907,8 +30484,25 @@ var MulticastManager = class {
28907
30484
  * callback delivers must come from a subscription opened on
28908
30485
  * `options.gateway`. A callback that also merges another source (a MoQ or
28909
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.
28910
30493
  */
28911
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
+ }
28912
30506
  const releases = [];
28913
30507
  let released = false;
28914
30508
  const safely = (each) => {
@@ -28918,17 +30512,36 @@ var MulticastManager = class {
28918
30512
  console.warn("[MulticastManager] repair group release failed", error);
28919
30513
  }
28920
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 = [];
28921
30526
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
28922
30527
  ...owner,
28923
30528
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
28924
30529
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
28925
30530
  }));
28926
30531
  this.#applyRepairOwners(repairOwners);
28927
- 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);
28928
30534
  const ingress = {
28929
30535
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
28930
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
30536
+ ...flow === void 0 ? {} : { flow }
28931
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
+ }
28932
30545
  let sender;
28933
30546
  const feed = (packet, sourceAddress, ingressToFeed) => {
28934
30547
  if (released) return;
@@ -28958,7 +30571,7 @@ var MulticastManager = class {
28958
30571
  packetIds: endpoint.packetIds,
28959
30572
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
28960
30573
  // A protected repair group's records ride in band on its port (7.2.3).
28961
- ...endpoint.flow === void 0 ? {} : { protected: true }
30574
+ ...flow === void 0 ? {} : { protected: true }
28962
30575
  }, ingress).then((joined) => {
28963
30576
  if (!joined && !released) fail(transport.lastJoinOutcome);
28964
30577
  });
@@ -28967,9 +30580,12 @@ var MulticastManager = class {
28967
30580
  if (released) return;
28968
30581
  released = true;
28969
30582
  this.#repairReleases.delete(release);
30583
+ this.#repairProvenanceFlows.delete(release);
28970
30584
  for (const each of releases.splice(0)) safely(each);
28971
30585
  };
28972
30586
  this.#repairReleases.set(release, repairOwners);
30587
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
30588
+ if (provenanceFlows.length) this.#hookFailback();
28973
30589
  return release;
28974
30590
  }
28975
30591
  #applyRepairOwners(owners) {
@@ -29238,6 +30854,70 @@ var MulticastManager = class {
29238
30854
  feedPacket(data, ingress, sourceAddress) {
29239
30855
  this.#transport.feedPacket(data, ingress, sourceAddress);
29240
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
+ }
29241
30921
  /**
29242
30922
  * Declare how packets given to feedPacket() reach this manager. A consumer
29243
30923
  * that owns the multicast socket itself declares its own leg; join()
@@ -29455,7 +31135,8 @@ var MulticastManager = class {
29455
31135
  blockProfile: parseFecBlockProfile(
29456
31136
  geometry2.blockProfile,
29457
31137
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
29458
- )
31138
+ ),
31139
+ geometry: geometry2
29459
31140
  });
29460
31141
  }
29461
31142
  }
@@ -29494,7 +31175,7 @@ var MulticastManager = class {
29494
31175
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
29495
31176
  const before = this.#overlayBindings.get(sourcePacketId);
29496
31177
  const after = overlayBindings.get(sourcePacketId);
29497
- 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]);
29498
31179
  if (!same) install.dispose();
29499
31180
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
29500
31181
  else install.reattach();
@@ -29551,10 +31232,12 @@ var MulticastManager = class {
29551
31232
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
29552
31233
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
29553
31234
  * pending hole and reported here, and `closeIsoHoles` must be called for it
29554
- * once its range FETCH ends (or none is sent).
31235
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
31236
+ * pending hole the stream runs past the locator's horizon: returning true,
31237
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
29555
31238
  */
29556
- onUndelimitedLoss(cb) {
29557
- this.#fec.setUndelimitedLossHandler(cb);
31239
+ onUndelimitedLoss(cb, onExpired) {
31240
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
29558
31241
  }
29559
31242
  /**
29560
31243
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -29790,7 +31473,8 @@ var MulticastManager = class {
29790
31473
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
29791
31474
  ...event,
29792
31475
  block: Object.freeze({ ...event.block }),
29793
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
31476
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
31477
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
29794
31478
  }
29795
31479
  );
29796
31480
  if (this.#logRepairLifecycle) {
@@ -30603,15 +32287,15 @@ function asSeconds(n) {
30603
32287
  }
30604
32288
  return n;
30605
32289
  }
30606
- function groupIdForTicks(ticks, groupDurationTicks, presentationAnchorTicks = 0) {
32290
+ function groupIdForTicks(ticks, groupDurationTicks2, presentationAnchorTicks = 0) {
30607
32291
  if (!Number.isInteger(ticks)) {
30608
32292
  throw new Error(
30609
32293
  `[align] groupIdForTicks: ticks must be an integer, got ${ticks}`
30610
32294
  );
30611
32295
  }
30612
- if (!Number.isInteger(groupDurationTicks) || groupDurationTicks <= 0) {
32296
+ if (!Number.isInteger(groupDurationTicks2) || groupDurationTicks2 <= 0) {
30613
32297
  throw new Error(
30614
- `[align] groupIdForTicks: groupDurationTicks must be a positive integer, got ${groupDurationTicks}`
32298
+ `[align] groupIdForTicks: groupDurationTicks must be a positive integer, got ${groupDurationTicks2}`
30615
32299
  );
30616
32300
  }
30617
32301
  if (!Number.isInteger(presentationAnchorTicks)) {
@@ -30630,7 +32314,7 @@ function groupIdForTicks(ticks, groupDurationTicks, presentationAnchorTicks = 0)
30630
32314
  `[align] groupIdForTicks: ticks ${ticks} precede presentationAnchorTicks ${presentationAnchorTicks}; the publisher must reject this MPU (moq-mmt-01 4.4.1)`
30631
32315
  );
30632
32316
  }
30633
- return Math.floor(relativeTicks / groupDurationTicks);
32317
+ return Math.floor(relativeTicks / groupDurationTicks2);
30634
32318
  }
30635
32319
  function groupIdFor(mediaTimeSec, groupDurationSec) {
30636
32320
  if (!Number.isFinite(mediaTimeSec)) {
@@ -31855,6 +33539,22 @@ function resolveCatalogTrackFec(catalog, tracks) {
31855
33539
  };
31856
33540
  }
31857
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
+
31858
33558
  // src/mmtp-fec-session.ts
31859
33559
  var PATH_BITS = { moq: 1, multicast: 2 };
31860
33560
  var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
@@ -32462,6 +34162,7 @@ var RepairLayerSubscriptions = class {
32462
34162
 
32463
34163
  // src/repair-fetch.ts
32464
34164
  var MOQT_PRIORITY_MAX = 255;
34165
+ var WALK_LEAD_MS = 3;
32465
34166
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
32466
34167
  function isMoqtPriority(value) {
32467
34168
  return Number.isSafeInteger(value) && value >= 0 && value <= MOQT_PRIORITY_MAX;
@@ -32512,8 +34213,17 @@ function wireRepairFetch(mc, opts) {
32512
34213
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
32513
34214
  };
32514
34215
  const clearEntry = (entry) => {
32515
- if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
32516
- else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
34216
+ const { range } = entry;
34217
+ if (range) {
34218
+ atReport(range, () => mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, range.holeLength));
34219
+ } else {
34220
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
34221
+ }
34222
+ };
34223
+ const atReport = (range, work) => {
34224
+ const fec = mc.fecManager;
34225
+ if (range.groups !== null || fec.withReceiptTime === void 0) work();
34226
+ else fec.withReceiptTime(range.reportedAt, work);
32517
34227
  };
32518
34228
  const releaseHold = (entry) => {
32519
34229
  if (entry.range) return;
@@ -32525,7 +34235,7 @@ function wireRepairFetch(mc, opts) {
32525
34235
  if (!run) return;
32526
34236
  entry.running = null;
32527
34237
  run.stopped = reason;
32528
- run.controller.abort();
34238
+ run.controller.abort(reason);
32529
34239
  if (reason === "preempted") releaseHold(entry);
32530
34240
  mc.noteRepairStopped?.(reason, entry.sbn, entry.packetId, entry.catalogTrackName);
32531
34241
  };
@@ -32580,21 +34290,42 @@ function wireRepairFetch(mc, opts) {
32580
34290
  const admit = (entry, now) => {
32581
34291
  const budgetMs = entry.deadlineAt - now;
32582
34292
  const rttMs = readRtt();
32583
- const reason = !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < budgetMs ? null : "rtt-exceeds-budget";
34293
+ const reason = refusal(entry, now, rttMs);
32584
34294
  if (reason === null) return rttMs;
32585
34295
  skip(entry, reason, rttMs, budgetMs);
32586
34296
  return null;
32587
34297
  };
34298
+ const refusal = (entry, now, rttMs) => !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < entry.deadlineAt - now ? null : "rtt-exceeds-budget";
32588
34299
  const retire = (entry) => {
32589
34300
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
32590
34301
  if (entry.expiry !== void 0) clearTimeout(entry.expiry);
32591
34302
  };
32592
- const outstandingBelow = (priority) => {
34303
+ const holdsBack = (entry, priority, videoWalks = true) => {
34304
+ if (entry.priority >= priority) return false;
34305
+ const { walk } = entry;
34306
+ if (walk === void 0) return true;
34307
+ if (entry.priority !== 0 || !videoWalks) return false;
34308
+ return entry.running === null || walk.group !== null && !walk.group.controller.signal.aborted;
34309
+ };
34310
+ const outstandingBelow = (priority, videoWalks = true) => {
32593
34311
  for (const entry of entries.values()) {
32594
- if (entry.priority < priority) return true;
34312
+ if (holdsBack(entry, priority, videoWalks)) return true;
32595
34313
  }
32596
34314
  return false;
32597
34315
  };
34316
+ const yieldVideoWalks = (queued) => {
34317
+ const now = performance.now();
34318
+ const rttMs = readRtt();
34319
+ const due = queued.some((entry) => entry.priority !== 0 && entry.walk === void 0 && !outstandingBelow(entry.priority, false) && refusal(entry, now, rttMs) === null);
34320
+ if (!due) return;
34321
+ for (const entry of entries.values()) {
34322
+ const walk = entry.walk;
34323
+ if (entry.priority !== 0 || walk === void 0 || walk.group === null) continue;
34324
+ if (walk.group.controller.signal.aborted) continue;
34325
+ walk.yielded = true;
34326
+ walk.group.controller.abort();
34327
+ }
34328
+ };
32598
34329
  const preemptBestEffort = () => {
32599
34330
  for (const entry of entries.values()) {
32600
34331
  if (entry.priority === 0 || !entry.running) continue;
@@ -32623,7 +34354,8 @@ function wireRepairFetch(mc, opts) {
32623
34354
  }
32624
34355
  const rttMs = admit(entry, now);
32625
34356
  if (rttMs === null) return;
32626
- if (entry.priority === 0) preemptBestEffort();
34357
+ if (entry.priority === 0 && entry.walk === void 0) preemptBestEffort();
34358
+ if (entry.range === void 0) leaveWalkedGroup(entry);
32627
34359
  if (counted) entry.attempts++;
32628
34360
  mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
32629
34361
  rttMs,
@@ -32645,6 +34377,14 @@ function wireRepairFetch(mc, opts) {
32645
34377
  }
32646
34378
  void execute(entry, run);
32647
34379
  };
34380
+ const leaveWalkedGroup = (block) => {
34381
+ for (const entry of entries.values()) {
34382
+ const group = entry.walk?.group;
34383
+ if (group?.sbn === block.sbn && entry.packetId === block.packetId && entry.catalogTrackName === block.catalogTrackName) {
34384
+ group.controller.abort();
34385
+ }
34386
+ }
34387
+ };
32648
34388
  const dispatch = () => {
32649
34389
  if (disposed) return;
32650
34390
  const now = performance.now();
@@ -32669,6 +34409,7 @@ function wireRepairFetch(mc, opts) {
32669
34409
  for (const entry of queued) {
32670
34410
  if (entry.priority === 0) start(entry);
32671
34411
  }
34412
+ yieldVideoWalks(queued);
32672
34413
  if (outstandingBelow(1)) return;
32673
34414
  for (const entry of queued) {
32674
34415
  if (entry.priority === 1) start(entry);
@@ -32695,6 +34436,16 @@ function wireRepairFetch(mc, opts) {
32695
34436
  }
32696
34437
  return counts.sources + counts.repairGroupLength >= counts.authoredLength;
32697
34438
  };
34439
+ const groupServed = (sbn, packetId, catalogTrackName) => {
34440
+ if (mc.fecManager.blockSymbolCounts === void 0) return false;
34441
+ const counts = symbolCounts(sbn, packetId, catalogTrackName);
34442
+ if (counts === void 0 || counts.authoredLength === void 0) return true;
34443
+ return counts.sources + counts.repairs >= counts.authoredLength || !groupCanComplete(sbn, packetId, catalogTrackName);
34444
+ };
34445
+ const statedEnd = (sbn, packetId, catalogTrackName) => {
34446
+ const length = symbolCounts(sbn, packetId, catalogTrackName)?.authoredLength;
34447
+ return length === void 0 ? void 0 : serial32Add(sbn, length);
34448
+ };
32698
34449
  const finish = (entry, run, fed, error) => {
32699
34450
  if (run.stopped !== null || entry.running !== run || entries.get(entry.key) !== entry) {
32700
34451
  return;
@@ -32739,27 +34490,81 @@ function wireRepairFetch(mc, opts) {
32739
34490
  signal: run.controller.signal,
32740
34491
  subscriberPriority: entry.subscriberPriority
32741
34492
  };
34493
+ const { range } = entry;
34494
+ const feed = (packet) => {
34495
+ if (entry.catalogTrackName === void 0) {
34496
+ mc.processRepairFromMoQ(packet, entry.packetId);
34497
+ } else {
34498
+ mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
34499
+ }
34500
+ };
32742
34501
  try {
32743
- const packets = entry.range ? opts.rangeTransport({
34502
+ const packets = range === void 0 ? opts.transport({ ...common, sbn: entry.sbn }) : entry.walk !== void 0 ? walkHole(entry, entry.walk, range, common) : opts.rangeTransport({
32744
34503
  ...common,
32745
- startGroup: entry.range.startGroup,
32746
- endGroup: entry.range.endGroup,
32747
- lostSsId: entry.range.lostSsId
32748
- }) : opts.transport({ ...common, sbn: entry.sbn });
34504
+ startGroup: range.groups.startGroup,
34505
+ endGroup: range.groups.endGroup,
34506
+ lostSsId: range.lostSsId
34507
+ });
32749
34508
  for await (const packet of packets) {
32750
34509
  if (run.stopped !== null || entry.running !== run) break;
32751
34510
  fed++;
32752
- if (entry.catalogTrackName === void 0) {
32753
- mc.processRepairFromMoQ(packet, entry.packetId);
32754
- } else {
32755
- mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
32756
- }
34511
+ if (range === void 0) feed(packet);
34512
+ else atReport(range, () => feed(packet));
32757
34513
  }
32758
34514
  finish(entry, run, fed, void 0);
32759
34515
  } catch (error) {
32760
34516
  finish(entry, run, fed, error ?? new Error("repair transport rejected"));
32761
34517
  }
32762
34518
  };
34519
+ async function* walkHole(entry, walk, hole, common) {
34520
+ const lostAt = serial32Distance(entry.sbn, hole.lostSsId);
34521
+ for (let first = true; !common.signal.aborted; first = false) {
34522
+ if (!first && entry.priority !== 0 && outstandingBelow(1)) {
34523
+ stop(entry, "preempted");
34524
+ note("repair-preempted", entry);
34525
+ return;
34526
+ }
34527
+ if (!first && entry.priority === 0) {
34528
+ dispatch();
34529
+ if (common.signal.aborted) return;
34530
+ }
34531
+ const sbn = walk.next;
34532
+ let next;
34533
+ if (entries.get(requestKey(sbn, entry.packetId, entry.catalogTrackName))?.running == null) {
34534
+ const rsIds = /* @__PURE__ */ new Set();
34535
+ const group = new AbortController();
34536
+ const cancel = () => group.abort(common.signal.reason);
34537
+ common.signal.addEventListener("abort", cancel, { once: true });
34538
+ walk.group = { sbn, controller: group };
34539
+ try {
34540
+ for await (const packet of opts.transport({ ...common, sbn, signal: group.signal })) {
34541
+ yield packet;
34542
+ const id = extractRepairFecPayloadId(packet);
34543
+ if (id === null || id.ssStart !== sbn || id.ssbLength === 0) continue;
34544
+ next ??= serial32Add(sbn, id.ssbLength);
34545
+ rsIds.add(id.rsId);
34546
+ if (rsIds.size >= id.rsbLength || groupServed(sbn, entry.packetId, entry.catalogTrackName)) {
34547
+ group.abort();
34548
+ break;
34549
+ }
34550
+ }
34551
+ } catch (error) {
34552
+ if (!group.signal.aborted || common.signal.aborted) throw error;
34553
+ } finally {
34554
+ common.signal.removeEventListener("abort", cancel);
34555
+ walk.group = null;
34556
+ }
34557
+ if (walk.yielded) {
34558
+ walk.yielded = false;
34559
+ continue;
34560
+ }
34561
+ }
34562
+ next ??= statedEnd(sbn, entry.packetId, entry.catalogTrackName);
34563
+ if (next === void 0) return;
34564
+ if (serial32Distance(entry.sbn, next) > lostAt) return;
34565
+ walk.next = next;
34566
+ }
34567
+ }
32763
34568
  const removeResetObserver = mc.addTrackResetObserver((packetId, catalogTrackName) => {
32764
34569
  for (const entry of [...entries.values()]) {
32765
34570
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
@@ -32808,6 +34613,22 @@ function wireRepairFetch(mc, opts) {
32808
34613
  dispatch();
32809
34614
  return;
32810
34615
  }
34616
+ if (event.type === "gap") {
34617
+ if (event.action !== "stall" || event.reason !== "discontinuity") return;
34618
+ const now = performance.now();
34619
+ let expired = false;
34620
+ for (const entry2 of [...entries.values()]) {
34621
+ if (entry2.packetId !== event.stream.packetId) continue;
34622
+ if (entry2.catalogTrackName !== (event.stream.catalogTrackName ?? void 0)) continue;
34623
+ if (!entry2.running || entry2.deadlineAt > now) continue;
34624
+ stop(entry2, "expired");
34625
+ retire(entry2);
34626
+ clearEntry(entry2);
34627
+ expired = true;
34628
+ }
34629
+ if (expired) dispatch();
34630
+ return;
34631
+ }
32811
34632
  if (event.type !== "recovered" && event.type !== "failed") return;
32812
34633
  const entry = entries.get(
32813
34634
  requestKey(event.block.sbn, event.block.packetId, event.block.catalogTrackName ?? void 0)
@@ -32955,7 +34776,37 @@ function wireRepairFetch(mc, opts) {
32955
34776
  throw error;
32956
34777
  }
32957
34778
  };
32958
- if (opts.rangeTransport !== void 0) {
34779
+ const trackKind = (packetId) => {
34780
+ try {
34781
+ return mc.fecManager.trackKindFor?.(packetId);
34782
+ } catch {
34783
+ return void 0;
34784
+ }
34785
+ };
34786
+ const walkDeadlineAt = (packetId, now, deadlineAt) => {
34787
+ let repairDeadlineMs;
34788
+ try {
34789
+ repairDeadlineMs = mc.fecManager.repairDeadlineMsForPacket?.(packetId);
34790
+ } catch {
34791
+ repairDeadlineMs = void 0;
34792
+ }
34793
+ if (repairDeadlineMs === void 0 || !Number.isFinite(repairDeadlineMs)) return deadlineAt;
34794
+ return Math.min(deadlineAt, now + repairDeadlineMs - WALK_LEAD_MS);
34795
+ };
34796
+ const onHoleExpired = (hole) => {
34797
+ if (disposed) return false;
34798
+ const entry = [...entries.values()].find((candidate) => candidate.walk !== void 0 && candidate.packetId === hole.packetId && candidate.catalogTrackName === hole.catalogTrackName && serial32Distance(candidate.sbn, hole.holeStart) < candidate.range.holeLength);
34799
+ if (entry === void 0) return false;
34800
+ queueMicrotask(() => {
34801
+ if (entries.get(entry.key) !== entry) return;
34802
+ retire(entry);
34803
+ stop(entry, "expired");
34804
+ clearEntry(entry);
34805
+ dispatch();
34806
+ });
34807
+ return true;
34808
+ };
34809
+ if (mc.onUndelimitedLoss !== void 0 && mc.closeIsoHoles !== void 0) {
32959
34810
  mc.onUndelimitedLoss((loss) => {
32960
34811
  const { packetId, catalogTrackName, holeStart, holeLength } = loss;
32961
34812
  const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
@@ -32963,9 +34814,11 @@ function wireRepairFetch(mc, opts) {
32963
34814
  const blockProfile = blockProfileOf(packetId);
32964
34815
  const target = opts.resolveTarget(packetId, catalogTrackName);
32965
34816
  if (!target) return close();
32966
- const priority = repairPriorityForClass("unknown");
32967
- const range = rangeFor(loss, target.repairTrack);
32968
- if (range === null) {
34817
+ const walked = opts.rangeTransport === void 0;
34818
+ const holeClass = walked && trackKind(packetId) === "audio" ? "audio" : "unknown";
34819
+ const priority = repairPriorityForClass(holeClass);
34820
+ const groups = walked ? null : rangeFor(loss, target.repairTrack);
34821
+ if (!walked && groups === null) {
32969
34822
  close();
32970
34823
  mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
32971
34824
  return;
@@ -32976,8 +34829,10 @@ function wireRepairFetch(mc, opts) {
32976
34829
  packetId,
32977
34830
  ...catalogTrackName === void 0 ? {} : { catalogTrackName }
32978
34831
  };
32979
- const wire = wirePriority(identity, "unknown");
32980
- const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
34832
+ const wire = wirePriority(identity, holeClass);
34833
+ if (wire === null) return close();
34834
+ const now = performance.now();
34835
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, now, holeClass);
32981
34836
  if (deadline === null) {
32982
34837
  close();
32983
34838
  mc.noteRepairSkipped(
@@ -32989,6 +34844,7 @@ function wireRepairFetch(mc, opts) {
32989
34844
  );
32990
34845
  return;
32991
34846
  }
34847
+ const deadlineAt = walked ? walkDeadlineAt(packetId, now, deadline.deadlineAt) : deadline.deadlineAt;
32992
34848
  const entry = {
32993
34849
  key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
32994
34850
  ...identity,
@@ -32996,15 +34852,16 @@ function wireRepairFetch(mc, opts) {
32996
34852
  blockProfile,
32997
34853
  priority,
32998
34854
  subscriberPriority: wire.subscriberPriority,
32999
- deadlineAt: deadline.deadlineAt,
33000
- playoutDeadlineAt: deadline.deadlineAt - deadline.extensionMs,
34855
+ deadlineAt,
34856
+ playoutDeadlineAt: deadlineAt - deadline.extensionMs,
33001
34857
  anchorAt: deadline.anchorAt,
33002
34858
  delayMs: deadline.delayMs,
33003
34859
  bound: deadline.bound,
33004
34860
  order: enqueueOrder++,
33005
34861
  attempts: 0,
33006
34862
  running: null,
33007
- range: { ...range, lostSsId: loss.lostSsId, holeLength }
34863
+ range: { lostSsId: loss.lostSsId, holeLength, groups, reportedAt: now },
34864
+ ...walked ? { walk: { next: holeStart, group: null, yielded: false } } : {}
33008
34865
  };
33009
34866
  const previous = entries.get(entry.key);
33010
34867
  if (previous) {
@@ -33014,7 +34871,7 @@ function wireRepairFetch(mc, opts) {
33014
34871
  entries.set(entry.key, entry);
33015
34872
  entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
33016
34873
  dispatch();
33017
- });
34874
+ }, onHoleExpired);
33018
34875
  }
33019
34876
  const removeRapObserver = mc.addRapCompleteObserver?.((packetId) => {
33020
34877
  queueMicrotask(() => {
@@ -33202,6 +35059,7 @@ export {
33202
35059
  mfuReassemblyTimeoutMs,
33203
35060
  mmtpFrameReorderWindowFrames,
33204
35061
  mmtpTimestampToMicros,
35062
+ mmtpTrackIssues,
33205
35063
  multicastFromConfig,
33206
35064
  multicastFromEnv,
33207
35065
  normalizeDeliveryCatalog,
@@ -33228,7 +35086,9 @@ export {
33228
35086
  resolveGroupDurationMs,
33229
35087
  resolveGroupDurationTicks,
33230
35088
  resolveRepairLayers,
35089
+ runtimeFecCatalogReport,
33231
35090
  secondsFromTicks,
35091
+ selectMmtpMode,
33232
35092
  setupFecWorkerForTrack,
33233
35093
  setupTrackPipeline,
33234
35094
  splitAnnexBNalUnits,