@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
@@ -954,13 +954,17 @@ function fecCatalogTracks(catalog) {
954
954
  });
955
955
  return { tracks, pointers };
956
956
  }
957
- function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
957
+ function runtimeView(catalog, receiver) {
958
958
  const { tracks, pointers } = fecCatalogTracks(catalog);
959
959
  const report = validateFecCatalog({ tracks }, receiver);
960
960
  const at = (path) => {
961
961
  const m = /^\/tracks\/(\d+)(.*)$/.exec(path);
962
962
  return m ? pointers[Number(m[1])] + m[2] : path;
963
963
  };
964
+ return { tracks, pointers, report, at };
965
+ }
966
+ function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
967
+ const { tracks, pointers, report, at } = runtimeView(catalog, receiver);
964
968
  const trackAt = (i) => recordOf(tracks[i]) ?? {};
965
969
  const nameAt = (i) => i === null ? void 0 : trackAt(i)["name"];
966
970
  const why = (i) => Object.freeze({
@@ -1058,6 +1062,40 @@ function geometry(o, instanceId, symbolTrack) {
1058
1062
  });
1059
1063
  }
1060
1064
 
1065
+ // ../mmt-base/dist/mmtp-siblings.js
1066
+ var MMTP_MODES = Object.freeze(["mfu", "mfu-datagram"]);
1067
+ var MMTP_SIBLING_HARD_FIELDS = Object.freeze([
1068
+ "namespace",
1069
+ "timescale",
1070
+ "presentationAnchorTicks",
1071
+ "groupDuration"
1072
+ ]);
1073
+ var MMTP_SIBLING_RENDITION_FIELDS = Object.freeze([
1074
+ "codec",
1075
+ "width",
1076
+ "height",
1077
+ "framerate",
1078
+ "bitrate",
1079
+ "samplerate",
1080
+ "channelConfig",
1081
+ "lang"
1082
+ ]);
1083
+ var MMTP_SIBLING_SOFT_FIELDS = Object.freeze([
1084
+ "initRef",
1085
+ "keyframeIntervalMs",
1086
+ "keyframeIntervalTicks",
1087
+ "isLive",
1088
+ "altGroup"
1089
+ ]);
1090
+
1091
+ // ../mmt-base/dist/datagram-leg-size.js
1092
+ var DATAGRAM_LEG_UDP_FLOOR = 1200;
1093
+ var DATAGRAM_LEG_QUIC_WT_FRAMING = 48;
1094
+ var DATAGRAM_LEG_OBJECT_HEADER = 13;
1095
+ var DATAGRAM_LEG_RELAY_ROOM = 16;
1096
+ var DATAGRAM_LEG_DATAGRAM_MAX = DATAGRAM_LEG_UDP_FLOOR - DATAGRAM_LEG_QUIC_WT_FRAMING;
1097
+ var DATAGRAM_LEG_BODY_MAX = DATAGRAM_LEG_DATAGRAM_MAX - DATAGRAM_LEG_OBJECT_HEADER - DATAGRAM_LEG_RELAY_ROOM;
1098
+
1061
1099
  // src/track-session.ts
1062
1100
  import { fecBlockBudgetMs } from "@blockcast/mmt-fec";
1063
1101
  function computeFecDeliveryWindowMs(config) {
@@ -1189,6 +1227,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1189
1227
  this.#heldEvicted = 0;
1190
1228
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
1191
1229
  this.#holes = [];
1230
+ /** Holes the horizon passed while pending: sources held until closed. */
1231
+ this.#expired = [];
1232
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
1233
+ this.#newlyExpired = [];
1234
+ /**
1235
+ * Spans closed from expired holes: behind the horizon, so kept only for
1236
+ * `locate` while their sources are fed, until the next retirement.
1237
+ */
1238
+ this.#closedBehind = [];
1192
1239
  /**
1193
1240
  * Keep a gap that is missing a source as a pending hole rather than a span,
1194
1241
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -1212,6 +1259,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
1212
1259
  #newest;
1213
1260
  #newestSource;
1214
1261
  #holes;
1262
+ #expired;
1263
+ #newlyExpired;
1264
+ #closedBehind;
1215
1265
  static #checkedRetention(retentionBlocks) {
1216
1266
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
1217
1267
  throw new Error(
@@ -1281,17 +1331,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
1281
1331
  }
1282
1332
  /** The known block or span containing `ssId`, with its ESI. */
1283
1333
  locate(ssId) {
1284
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
1285
- const block = this.#blocks[i];
1286
- if (isoBlockContains(block.start, block.length, ssId)) {
1287
- return { block, esi: serial32Distance(block.start, ssId) };
1334
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
1335
+ for (let i = blocks.length - 1; i >= 0; i--) {
1336
+ const block = blocks[i];
1337
+ if (isoBlockContains(block.start, block.length, ssId)) {
1338
+ return { block, esi: serial32Distance(block.start, ssId) };
1339
+ }
1288
1340
  }
1289
1341
  }
1290
1342
  return null;
1291
1343
  }
1292
- /** Number of pending holes. */
1344
+ /** Number of holes not closed yet, pending or past the horizon. */
1293
1345
  get holeCount() {
1294
- return this.#holes.length;
1346
+ return this.#holes.length + this.#expired.length;
1347
+ }
1348
+ /**
1349
+ * The pending holes the horizon has passed since the last call, in the
1350
+ * order it passed them. Each is no longer pending: no repair states a block
1351
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
1352
+ * release gate does not wait for it. Its owner must close it
1353
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
1354
+ */
1355
+ takeExpiredHoles() {
1356
+ return this.#newlyExpired.splice(0);
1295
1357
  }
1296
1358
  /** The stated block (never a span) ending exactly at `end`. */
1297
1359
  blockEndingAt(end) {
@@ -1344,12 +1406,42 @@ var IsoBlockLocator = class _IsoBlockLocator {
1344
1406
  isHeld(ssId) {
1345
1407
  return this.#held.has(ssId);
1346
1408
  }
1409
+ /** The payload held unplaced for `ssId`, if any. */
1410
+ heldSource(ssId) {
1411
+ return this.#held.get(ssId);
1412
+ }
1413
+ /**
1414
+ * The SS_IDs strictly between `a` and `b` that no repair has delimited a
1415
+ * block of yet: those from the coverage end on, or all of them before the
1416
+ * first repair. `missing` is the highest of them no source is held for;
1417
+ * absent, every one of them arrived (C.5.2: SS_IDs are consecutive). Null
1418
+ * when none lies past coverage. `flagged` is whether a source held among
1419
+ * them satisfies `flag` (a RAP fragment, say): the held packets read as
1420
+ * fec-multicast-00 Block Classification item 1 reads bounding packets.
1421
+ */
1422
+ undelimitedBetween(a, b, flag) {
1423
+ if (!serial32Precedes(a, b) || serial32Distance(a, b) <= 1) return null;
1424
+ const first = a + 1 >>> 0;
1425
+ const end = this.#coverageEnd;
1426
+ const start = end !== void 0 && serial32Precedes(first, end) ? end : first;
1427
+ if (!serial32Precedes(start, b)) return null;
1428
+ const length = serial32Distance(start, b);
1429
+ const missing = this.#highestMissing(start, length);
1430
+ let flagged = false;
1431
+ for (let i = 0; flag !== void 0 && !flagged && i < length; i++) {
1432
+ const payload = this.#held.get(serial32Add(start, i));
1433
+ flagged = payload !== void 0 && flag(payload);
1434
+ }
1435
+ return missing === void 0 ? { start, flagged } : { start, missing, flagged };
1436
+ }
1347
1437
  /**
1348
1438
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
1349
1439
  * block states its range and places every held source in it; later repair
1350
- * symbols of the same block change nothing. A range that contradicts a
1351
- * known block (a different length, or an overlap with another block or a
1352
- * span) fails closed: the repair symbol is dropped and no block changes.
1440
+ * symbols of the same block change nothing. A repair whose range is exactly
1441
+ * a repair-less span states that span's one block. A range that contradicts
1442
+ * a known block (a different length, or an overlap with another block or
1443
+ * with part of a span) fails closed: the repair symbol is dropped and no
1444
+ * block changes.
1353
1445
  * A newly stated block retires behind its SS_Start (see the class note).
1354
1446
  * A block so far past `newest` that stating it would retire the position
1355
1447
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -1368,7 +1460,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
1368
1460
  const known = this.blockAt(start);
1369
1461
  if (known !== void 0) {
1370
1462
  if (known.span) {
1371
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
1463
+ if (known.length === length) {
1464
+ const block2 = { start, length, span: false };
1465
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
1466
+ return { status: "placed", block: block2, placed: [] };
1467
+ }
1468
+ return length < known.length ? {
1469
+ status: "overlap",
1470
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
1471
+ ofSpan: known
1472
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
1372
1473
  }
1373
1474
  if (known.length !== length) {
1374
1475
  return {
@@ -1436,18 +1537,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
1436
1537
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
1437
1538
  }
1438
1539
  /**
1439
- * Turn every pending hole inside `[start, start + length)` into a
1440
- * repair-less span, claiming its held sources: its range FETCH ended, so
1441
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
1540
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
1541
+ * claiming its held sources: its range FETCH ended, so nothing more will
1542
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
1543
+ * span that is not kept among the blocks, as the horizon would retire it at
1544
+ * once; only `locate` finds it, until the next retirement, so its sources
1545
+ * can be fed. Returns the spans, in SS_ID order.
1442
1546
  */
1443
1547
  closeHolesWithin(start, length) {
1444
1548
  const closed = [];
1445
- for (const hole of [...this.#holes]) {
1446
- if (!isoBlockContains(start, length, hole.start)) continue;
1447
- this.#holes.splice(this.#holes.indexOf(hole), 1);
1448
- const spanBlock = { start: hole.start, length: hole.length, span: true };
1449
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
1450
- this.#blocks.push(spanBlock);
1549
+ for (const holes of [this.#holes, this.#expired]) {
1550
+ for (const hole of [...holes]) {
1551
+ if (!isoBlockContains(start, length, hole.start)) continue;
1552
+ holes.splice(holes.indexOf(hole), 1);
1553
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
1554
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
1555
+ if (holes === this.#holes) {
1556
+ this.#blocks.push(spanBlock);
1557
+ } else {
1558
+ this.#closedBehind.push(spanBlock);
1559
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
1560
+ }
1561
+ }
1451
1562
  }
1452
1563
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
1453
1564
  }
@@ -1461,15 +1572,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
1461
1572
  return void 0;
1462
1573
  }
1463
1574
  /**
1464
- * Retire every block and span whose last SS_ID, and every held source,
1465
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
1466
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
1467
- * horizon uses. Returns the retired block starts.
1575
+ * Retire every block and span whose last SS_ID, and every held source
1576
+ * outside a hole, lies more than `retentionBlocks` blocks behind
1577
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
1578
+ * every ISO interleave horizon uses; a pending hole so far behind expires
1579
+ * (`takeExpiredHoles`). Returns the retired block starts.
1468
1580
  */
1469
1581
  retireBehind(position) {
1470
1582
  this.observe(position);
1471
1583
  const horizon = this.#retentionBlocks;
1472
1584
  const retired = [];
1585
+ this.#closedBehind.length = 0;
1473
1586
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
1474
1587
  const block = this.#blocks[i];
1475
1588
  const last = serial32Add(block.start, block.length - 1);
@@ -1481,10 +1594,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1481
1594
  for (let i = this.#holes.length - 1; i >= 0; i--) {
1482
1595
  const hole = this.#holes[i];
1483
1596
  const last = serial32Add(hole.start, hole.length - 1);
1484
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
1597
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
1598
+ this.#holes.splice(i, 1);
1599
+ this.#expired.push(hole);
1600
+ this.#newlyExpired.push(hole);
1485
1601
  }
1486
1602
  for (const ssId of [...this.#held.keys()]) {
1487
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
1603
+ 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))) {
1604
+ this.#held.delete(ssId);
1605
+ }
1488
1606
  }
1489
1607
  return retired;
1490
1608
  }
@@ -1492,6 +1610,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
1492
1610
  reset() {
1493
1611
  this.#blocks.length = 0;
1494
1612
  this.#holes.length = 0;
1613
+ this.#expired.length = 0;
1614
+ this.#newlyExpired.length = 0;
1615
+ this.#closedBehind.length = 0;
1495
1616
  this.#held.clear();
1496
1617
  this.#coverageEnd = void 0;
1497
1618
  this.#newest = void 0;
@@ -1558,31 +1679,26 @@ function deriveBlockClassifierGeometry(input) {
1558
1679
  );
1559
1680
  }
1560
1681
  if (input.trackKind === "audio") return { trackKind: "audio" };
1561
- if (!isPositiveFinite(input.framerate)) {
1562
- return { trackKind: "video", mode: "all-protected", reason: "framerate-absent" };
1563
- }
1564
- const framerate = input.framerate;
1565
1682
  let keyframeInterval;
1566
1683
  if (isPositiveFinite(input.keyframeIntervalTicks) && isPositiveFinite(input.timescale)) {
1567
1684
  keyframeInterval = { ticks: input.keyframeIntervalTicks, timescale: input.timescale };
1568
1685
  } else if (isPositiveFinite(input.keyframeIntervalMs)) {
1569
1686
  keyframeInterval = { ticks: input.keyframeIntervalMs, timescale: 1e3 };
1570
- } else {
1571
- return { trackKind: "video", mode: "all-protected", reason: "keyframe-cadence-absent" };
1572
1687
  }
1688
+ const protect = (reason) => ({
1689
+ trackKind: "video",
1690
+ mode: "all-protected",
1691
+ reason,
1692
+ ...keyframeInterval === void 0 ? {} : { keyframeInterval }
1693
+ });
1694
+ if (!isPositiveFinite(input.framerate)) return protect("framerate-absent");
1695
+ const framerate = input.framerate;
1696
+ if (keyframeInterval === void 0) return protect("keyframe-cadence-absent");
1573
1697
  const gopFrames = exactInteger(keyframeInterval.ticks * framerate, keyframeInterval.timescale);
1574
- if (gopFrames === null) {
1575
- return {
1576
- trackKind: "video",
1577
- mode: "all-protected",
1578
- reason: "keyframe-interval-not-integral"
1579
- };
1580
- }
1698
+ if (gopFrames === null) return protect("keyframe-interval-not-integral");
1581
1699
  const frameDurationMs = 1e3 / framerate;
1582
1700
  const interleaveUnits = deriveFecInterleaveDepth(input.interleaveDepthMs, frameDurationMs);
1583
- if (interleaveUnits >= gopFrames) {
1584
- return { trackKind: "video", mode: "all-protected", reason: "block-spans-gop" };
1585
- }
1701
+ if (interleaveUnits >= gopFrames) return protect("block-spans-gop");
1586
1702
  return {
1587
1703
  trackKind: "video",
1588
1704
  mode: "classifying",
@@ -1593,7 +1709,7 @@ function deriveBlockClassifierGeometry(input) {
1593
1709
  };
1594
1710
  }
1595
1711
  function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
1596
- if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return null;
1712
+ if (geometry2.trackKind !== "video" || geometry2.keyframeInterval === void 0) return null;
1597
1713
  if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0) return null;
1598
1714
  const { ticks, timescale } = geometry2.keyframeInterval;
1599
1715
  if (!Number.isSafeInteger(ticks) || !Number.isSafeInteger(timescale)) return null;
@@ -1602,9 +1718,15 @@ function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
1602
1718
  if (scaled % divisor !== 0n) return null;
1603
1719
  return scaled / divisor;
1604
1720
  }
1721
+ function keyframeInstantBetween(start, interval, from, to) {
1722
+ const k = from >= start ? (from - start) / interval + 1n : 1n;
1723
+ return start + k * interval <= to;
1724
+ }
1605
1725
  function compareDataUnitStarts(a, b) {
1606
- return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset;
1726
+ return a.movieFragment - b.movieFragment | 0 || a.idx - b.idx || a.offset - b.offset;
1607
1727
  }
1728
+ var LATE_RAP_MAX_MPUS_BACK = 64;
1729
+ var UNPLACED = { rapNotMpuStart: false };
1608
1730
  var BlockClassifier = class {
1609
1731
  #geometry;
1610
1732
  #mode;
@@ -1627,8 +1749,24 @@ var BlockClassifier = class {
1627
1749
  #mpuSbnSpans = /* @__PURE__ */ new Map();
1628
1750
  #dataUnitStarts = /* @__PURE__ */ new Map();
1629
1751
  #highestMpu = null;
1630
- /** MPU → movie_fragment_sequence_number observed in it. */
1631
- #mpuFragments = /* @__PURE__ */ new Map();
1752
+ /**
1753
+ * P3 layout, kept for the MPUs within the classification horizon and valid
1754
+ * within one continuous SBN sequence (`noteSourceDiscontinuity`).
1755
+ */
1756
+ #mpus = /* @__PURE__ */ new Map();
1757
+ /** An MPU of this sequence showed two movie fragments: each frame is one. */
1758
+ #fragmentPerFrame = false;
1759
+ /** A DU header of this sequence stated sample_number above 1. */
1760
+ #multiSampleFragment = false;
1761
+ /**
1762
+ * The anchor received last, whether or not its MPU is still in the
1763
+ * horizon. Each new anchor, and the anchor of every DU header's MPU, is
1764
+ * checked against it.
1765
+ */
1766
+ #lastAnchor = null;
1767
+ /** Two anchors were exactly G fragments per MPU apart. */
1768
+ #fragmentsProven = false;
1769
+ /** The first RAP released of the latest MPU a RAP was released in, recorded in every mode. */
1632
1770
  #lastRap = null;
1633
1771
  constructor(geometry2) {
1634
1772
  this.#geometry = geometry2;
@@ -1658,7 +1796,7 @@ var BlockClassifier = class {
1658
1796
  this.#geometry = geometry2;
1659
1797
  this.#blocks.clear();
1660
1798
  this.#clearContiguityLedger();
1661
- this.#mpuFragments.clear();
1799
+ this.#clearMpuLayout();
1662
1800
  this.#lastRap = null;
1663
1801
  this.#mpuBoundsRaps = true;
1664
1802
  if (geometry2.trackKind === "video" && geometry2.mode === "all-protected") {
@@ -1692,11 +1830,14 @@ var BlockClassifier = class {
1692
1830
  /**
1693
1831
  * The stream's SBN sequence restarted (FECManager source discontinuity:
1694
1832
  * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
1695
- * order are comparable only within one continuous sequence, so the P1
1696
- * ledger starts again.
1833
+ * order are comparable only within one continuous sequence, and a
1834
+ * restarted publisher numbers MPUs and movie fragments again, so the P1
1835
+ * ledger and the P3 layout start again.
1697
1836
  */
1698
1837
  noteSourceDiscontinuity() {
1699
1838
  this.#clearContiguityLedger();
1839
+ this.#clearMpuLayout();
1840
+ this.#lastRap = null;
1700
1841
  }
1701
1842
  /** Register a block that exists without evidence (a vanished block). */
1702
1843
  touch(sbn) {
@@ -1715,16 +1856,16 @@ var BlockClassifier = class {
1715
1856
  if (this.#geometry.trackKind === "audio") return [];
1716
1857
  const changes = [];
1717
1858
  const block = this.#blockFor(sbn);
1859
+ const placement = this.#place(evidence);
1718
1860
  if (evidence.rap) block.rapSeen = true;
1719
1861
  if (evidence.mpu !== void 0) block.mpus.add(evidence.mpu);
1720
- if (evidence.idx !== void 0) {
1721
- block.idxMin = block.idxMin === void 0 ? evidence.idx : Math.min(block.idxMin, evidence.idx);
1722
- block.idxMax = block.idxMax === void 0 ? evidence.idx : Math.max(block.idxMax, evidence.idx);
1862
+ const { position } = placement;
1863
+ if (position !== void 0) {
1864
+ block.positionMin = block.positionMin === void 0 ? position : Math.min(block.positionMin, position);
1865
+ block.positionMax = block.positionMax === void 0 ? position : Math.max(block.positionMax, position);
1723
1866
  }
1724
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
1725
- this.#mpuBoundsRaps = false;
1726
- }
1727
- const violation = this.#checkInvariants(sbn, block, evidence);
1867
+ if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false;
1868
+ const violation = this.#checkInvariants(sbn, block, evidence, placement);
1728
1869
  if (violation !== null) changes.push(...this.#disable(violation));
1729
1870
  const next = this.#classify(block);
1730
1871
  if (next !== block.cls && this.#allowed(block.cls, next)) {
@@ -1749,18 +1890,35 @@ var BlockClassifier = class {
1749
1890
  * RAP-bearing block is the one a wrong G calls delta), because the next
1750
1891
  * released RAP then belongs to m+2. Every MPU is one interval long, so the
1751
1892
  * span to any later released RAP proves or refutes all MPUs in between.
1752
- */
1753
- noteReleasedRap(mpu, presentationTime, mediaTimescale) {
1754
- if (this.#geometry.trackKind === "audio" || this.#mode === "all-protected") {
1755
- return [];
1756
- }
1757
- const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
1758
- if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
1893
+ *
1894
+ * In every mode it keeps each MPU's first released RAP, with its decode
1895
+ * time, as the start keyframeFreeBetween measures the catalog interval
1896
+ * from, and a second RAP released inside one MPU refutes `mpuBoundsRaps`
1897
+ * when it lies off the catalog lattice (not a whole number of intervals
1898
+ * after the first; draft-ramadan-moq-mmt-02 4.4.3 binds every keyframe to
1899
+ * it): with no repair, released RAPs are the only evidence of where they
1900
+ * lie. Without a usable interval, or a decode time on either, any second
1901
+ * RAP with another presentation time refutes.
1902
+ */
1903
+ noteReleasedRap(mpu, presentationTime, mediaTimescale, decodeTime) {
1904
+ if (this.#geometry.trackKind === "audio") return [];
1759
1905
  const previous = this.#lastRap;
1760
1906
  if (previous !== null && previous.mpu === mpu && previous.mediaTimescale === mediaTimescale) {
1907
+ if (presentationTime === previous.presentationTime) return [];
1908
+ const interval2 = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
1909
+ if (interval2 === null || decodeTime === void 0 || previous.decodeTime === void 0 || (decodeTime - previous.decodeTime) % interval2 !== 0n) {
1910
+ this.#mpuBoundsRaps = false;
1911
+ }
1761
1912
  return [];
1762
1913
  }
1763
- this.#lastRap = { mpu, presentationTime, mediaTimescale };
1914
+ if (previous !== null && previous.mediaTimescale === mediaTimescale) {
1915
+ const back = previous.mpu - mpu >>> 0;
1916
+ if (back !== 0 && back <= LATE_RAP_MAX_MPUS_BACK && presentationTime < previous.presentationTime) return [];
1917
+ }
1918
+ this.#lastRap = { mpu, presentationTime, mediaTimescale, ...decodeTime === void 0 ? {} : { decodeTime } };
1919
+ if (this.#mode === "all-protected") return [];
1920
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
1921
+ if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
1764
1922
  if (previous === null || mpu < previous.mpu || previous.mediaTimescale !== mediaTimescale) {
1765
1923
  return [];
1766
1924
  }
@@ -1769,6 +1927,22 @@ var BlockClassifier = class {
1769
1927
  }
1770
1928
  return this.#disable("rap-spacing-mismatch");
1771
1929
  }
1930
+ /**
1931
+ * Whether a gap inside MPU `mpu`, between the decode times `from` and `to`
1932
+ * of the frames on either side, holds no keyframe: MPU boundaries still
1933
+ * bound RAPs, the catalog states an interval exact in this timescale, and
1934
+ * none of its instants after the MPU's first released RAP lies in
1935
+ * `(from, to]` (fec-multicast-00 Block Classification item 3). Anything
1936
+ * unknown counts as a keyframe.
1937
+ */
1938
+ keyframeFreeBetween(mpu, from, to, mediaTimescale) {
1939
+ const rap = this.#lastRap;
1940
+ if (!this.#mpuBoundsRaps || rap?.mpu !== mpu || rap.mediaTimescale !== mediaTimescale || rap.decodeTime === void 0) {
1941
+ return false;
1942
+ }
1943
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
1944
+ return interval !== null && !keyframeInstantBetween(rap.decodeTime, interval, from, to);
1945
+ }
1772
1946
  #blockFor(sbn) {
1773
1947
  let block = this.#blocks.get(sbn);
1774
1948
  if (!block) {
@@ -1777,35 +1951,89 @@ var BlockClassifier = class {
1777
1951
  }
1778
1952
  return block;
1779
1953
  }
1780
- #checkInvariants(sbn, block, evidence) {
1954
+ #checkInvariants(sbn, block, evidence, placement) {
1781
1955
  if (this.#mode === "all-protected" || this.#geometry.trackKind !== "video") return null;
1782
1956
  const geometry2 = this.#geometry;
1783
1957
  if (geometry2.mode !== "classifying") return null;
1784
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
1785
- return "rap-not-mpu-start";
1786
- }
1787
- if (evidence.idx !== void 0 && evidence.idx >= geometry2.gopFrames) {
1958
+ if (placement.rapNotMpuStart) return "rap-not-mpu-start";
1959
+ if (placement.position !== void 0 && placement.position >= geometry2.gopFrames) {
1788
1960
  return "mpu-longer-than-gop";
1789
1961
  }
1790
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0 && block.idxMax - block.idxMin >= geometry2.interleaveUnits) {
1962
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0 && block.positionMax - block.positionMin >= geometry2.interleaveUnits) {
1791
1963
  return "block-wider-than-interleave";
1792
1964
  }
1793
- if (evidence.mpu !== void 0 && evidence.movieFragment !== void 0) {
1794
- const fragment = this.#mpuFragments.get(evidence.mpu);
1795
- if (fragment === void 0) {
1796
- this.#mpuFragments.set(evidence.mpu, evidence.movieFragment);
1797
- for (const mpu of this.#mpuFragments.keys()) {
1798
- if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu);
1799
- }
1800
- } else if (fragment !== evidence.movieFragment) {
1801
- return "mpu-multiple-fragments";
1802
- }
1803
- }
1965
+ if (placement.violation !== void 0) return placement.violation;
1804
1966
  if (evidence.mpu !== void 0 && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
1805
1967
  return "block-not-contiguous";
1806
1968
  }
1807
1969
  return null;
1808
1970
  }
1971
+ /**
1972
+ * The MPU position a source symbol's DU header proves (P3), and what it
1973
+ * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.
1974
+ */
1975
+ #place(evidence) {
1976
+ const { mpu, idx, movieFragment: fragment } = evidence;
1977
+ if (idx === void 0) return UNPLACED;
1978
+ const bySample = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 };
1979
+ if (mpu === void 0 || fragment === void 0) {
1980
+ return this.#fragmentPerFrame && !this.#multiSampleFragment ? { rapNotMpuStart: bySample.rapNotMpuStart } : bySample;
1981
+ }
1982
+ let layout = this.#mpus.get(mpu);
1983
+ if (layout === void 0) {
1984
+ layout = { low: fragment };
1985
+ this.#mpus.set(mpu, layout);
1986
+ for (const other of this.#mpus.keys()) {
1987
+ if (other + 1 < mpu) this.#mpus.delete(other);
1988
+ }
1989
+ } else if (fragment !== layout.low) {
1990
+ this.#fragmentPerFrame = true;
1991
+ if ((fragment - layout.low | 0) < 0) layout.low = fragment;
1992
+ }
1993
+ if (idx !== 0) this.#multiSampleFragment = true;
1994
+ let arrival;
1995
+ if (evidence.rap && layout.anchor === void 0) {
1996
+ layout.anchor = fragment;
1997
+ arrival = this.#anchorDrift(mpu, fragment);
1998
+ if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true;
1999
+ this.#lastAnchor = { mpu, fragment };
2000
+ }
2001
+ if (!this.#fragmentPerFrame) return bySample;
2002
+ if (this.#multiSampleFragment) return { ...bySample, violation: "mpu-multiple-fragments" };
2003
+ const { anchor } = layout;
2004
+ if (anchor === void 0) return UNPLACED;
2005
+ const drift = arrival ?? this.#anchorDrift(mpu, anchor);
2006
+ const offset = fragment - anchor | 0;
2007
+ return {
2008
+ ...offset === 0 || offset > 0 && this.#fragmentsProven ? { position: offset } : {},
2009
+ rapNotMpuStart: evidence.rap && offset !== 0 || (layout.low - anchor | 0) < 0 || // Fragments count frames: an anchor arriving past the spacing is a
2010
+ // RAP inside its MPU, or an earlier MPU outran G.
2011
+ arrival !== void 0 && arrival > 0 && this.#fragmentsProven,
2012
+ ...drift === void 0 || drift === 0 ? {} : { violation: "rap-spacing-mismatch" }
2013
+ };
2014
+ }
2015
+ /**
2016
+ * How many fragments MPU m's anchor `fragment` lies past the start that
2017
+ * the anchor received last predicts for MPU m: one frame per fragment and
2018
+ * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')
2019
+ * fragments apart, modulo 2^32. Undefined without a last anchor, a
2020
+ * cadence, or this layout.
2021
+ */
2022
+ #anchorDrift(mpu, fragment) {
2023
+ const geometry2 = this.#geometry;
2024
+ const last = this.#lastAnchor;
2025
+ if (last === null || !this.#fragmentPerFrame || this.#multiSampleFragment || geometry2.trackKind !== "video" || geometry2.mode !== "classifying") {
2026
+ return void 0;
2027
+ }
2028
+ return fragment - last.fragment - geometry2.gopFrames * (mpu - last.mpu) | 0;
2029
+ }
2030
+ #clearMpuLayout() {
2031
+ this.#mpus.clear();
2032
+ this.#fragmentPerFrame = false;
2033
+ this.#multiSampleFragment = false;
2034
+ this.#lastAnchor = null;
2035
+ this.#fragmentsProven = false;
2036
+ }
1809
2037
  #clearContiguityLedger() {
1810
2038
  this.#mpuSbnSpans.clear();
1811
2039
  this.#dataUnitStarts.clear();
@@ -1905,9 +2133,9 @@ var BlockClassifier = class {
1905
2133
  if (this.#mode === "all-protected") return "unknown";
1906
2134
  const geometry2 = this.#geometry;
1907
2135
  if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return "unknown";
1908
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0) {
2136
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0) {
1909
2137
  const span = geometry2.interleaveUnits - 1;
1910
- if (block.idxMax - span >= 1 && block.idxMin + span <= geometry2.gopFrames - 1) {
2138
+ if (block.positionMax - span >= 1 && block.positionMin + span <= geometry2.gopFrames - 1) {
1911
2139
  return "delta";
1912
2140
  }
1913
2141
  }
@@ -2084,6 +2312,7 @@ var WORKER_ERROR_LOG_CAP = 5;
2084
2312
  var WORKER_ERROR_KIND_CAP = 32;
2085
2313
  var WORKER_ERROR_OVERFLOW_KIND = "other";
2086
2314
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
2315
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
2087
2316
  function isMulticastSymbolDelivery(value) {
2088
2317
  return value === "datagram" || value === "ordered-relay";
2089
2318
  }
@@ -2165,7 +2394,12 @@ var FECManager = class _FECManager {
2165
2394
  this.#repairHoldUntilMs = /* @__PURE__ */ new Map();
2166
2395
  // Receiver-measured multicast delivery gap: the late-symbol wait's jitter
2167
2396
  // term (see DeliveryGapEstimator for the statistic and why).
2168
- this.#deliveryGaps = new DeliveryGapEstimator();
2397
+ // One estimator per lossy path, so a hybrid session never lets one leg's
2398
+ // stall widen the other's wait; the wait reads the larger peak.
2399
+ this.#deliveryGaps = {
2400
+ multicast: new DeliveryGapEstimator(),
2401
+ "moq-datagram": new DeliveryGapEstimator()
2402
+ };
2169
2403
  this.#lifecycleTrace = [];
2170
2404
  // Worker-backed timeouts enqueue cleanup behind all prior symbol messages.
2171
2405
  // Failure remains pending until cleanupComplete acknowledges that queue drain.
@@ -2177,10 +2411,18 @@ var FECManager = class _FECManager {
2177
2411
  // 'pending' forever, which would park every later frame of its stream in
2178
2412
  // the in-order release gate. Each entry owns its handle; the callback
2179
2413
  // checks it still owns the key, so a settled or reset key is never touched.
2414
+ /**
2415
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
2416
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
2417
+ */
2180
2418
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
2181
2419
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
2182
2420
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
2183
2421
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
2422
+ // Source ESIs per block that another FEC instance rebuilt and fed in
2423
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
2424
+ // not network arrivals and never make a block clean.
2425
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
2184
2426
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
2185
2427
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
2186
2428
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -2189,10 +2431,14 @@ var FECManager = class _FECManager {
2189
2431
  // SSB_length source arrivals and recoverable from SSB_length received
2190
2432
  // symbols; waiting for K fails every one of them.
2191
2433
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
2434
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
2435
+ // a repair states the block there or the span resolves.
2436
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
2192
2437
  this.#ssbLengthConflictCount = 0;
2193
2438
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
2194
2439
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
2195
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
2440
+ // symbols its repair group carries; 0 for a repair-less span no repair can
2441
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
2196
2442
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
2197
2443
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
2198
2444
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -2345,6 +2591,14 @@ var FECManager = class _FECManager {
2345
2591
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
2346
2592
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
2347
2593
  this.#isoLocators = /* @__PURE__ */ new Map();
2594
+ // The ts of the run behind the gap the release gate last asked about, per
2595
+ // stream (isoRepairlessWaitMs), keyed on the frame before the gap: kept, as
2596
+ // the source it came from may retire before the run's deadline, and the
2597
+ // earliest found wins, so a late frame that becomes the head restarts
2598
+ // nothing. It stays until the next run gap: a source discontinuity drops
2599
+ // it, and one older than twice the hold ceiling is not this gap's.
2600
+ // `counted` once the deadline passed (onUndelimitedRunGap).
2601
+ this.#runAnchors = /* @__PURE__ */ new Map();
2348
2602
  this.#deferIsoGaps = false;
2349
2603
  this.#isoRepairRefusedCount = 0;
2350
2604
  this.#isoSourceOversizeCount = 0;
@@ -2380,13 +2634,18 @@ var FECManager = class _FECManager {
2380
2634
  this.#workerErrorCounts = /* @__PURE__ */ new Map();
2381
2635
  this.#decoderUnavailableEvents = 0;
2382
2636
  this.#repairSymbolSizeMismatchCount = 0;
2637
+ this.#unlistedRepairTrackRefusals = 0;
2638
+ this.#unresolvedRepairOwnerDrops = { unregistered: 0, ownerAbsent: 0, ownerAmbiguous: 0 };
2383
2639
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
2384
2640
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
2385
2641
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
2386
2642
  // arrives via onBlockRecovered callback.
2387
2643
  this.onBlockStarted = null;
2388
2644
  this.onBlockComplete = null;
2389
- /** A block reached its fail bound. `blockClass` is its class at failure. */
2645
+ /**
2646
+ * A block reached its fail bound. `blockClass` is its class at failure.
2647
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
2648
+ */
2390
2649
  this.onBlockFailed = null;
2391
2650
  /**
2392
2651
  * Fired once per stream when its Worker decoder stops being routable.
@@ -2428,12 +2687,26 @@ var FECManager = class _FECManager {
2428
2687
  * for it, which it must be.
2429
2688
  */
2430
2689
  this.#onUndelimitedLoss = null;
2690
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
2691
+ this.#onIsoHoleExpired = null;
2431
2692
  /** A block every symbol of which vanished was created by SBN evidence. */
2432
2693
  this.onBlockVanished = null;
2433
2694
  /** A block reached a terminal state (completed, recovered, or failed). */
2434
2695
  this.onBlockResolved = null;
2435
2696
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
2436
2697
  this.onSourceDiscontinuity = null;
2698
+ /** The FEC deadline of a run no repair delimited passed, releasing the gap behind it (once per gap). */
2699
+ this.onUndelimitedRunGap = null;
2700
+ /**
2701
+ * The span and tolerance the catalog states for a keyframe overlay
2702
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
2703
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
2704
+ * undefined while none is installed. A stated block only a late source
2705
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
2706
+ * late source can fill, also wait for that overlay's repair
2707
+ * (#overlayLateWaitMs).
2708
+ */
2709
+ this.keyframeOverlayTiming = null;
2437
2710
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
2438
2711
  /**
2439
2712
  * A recovered source symbol. Return false when admission refused the
@@ -2470,7 +2743,9 @@ var FECManager = class _FECManager {
2470
2743
  #pendingWorkerCleanupBounds;
2471
2744
  #blockSourceCounts;
2472
2745
  #blockSourceEsis;
2746
+ #blockRebuiltEsis;
2473
2747
  #blockAuthoredLengths;
2748
+ #isoSpanKeys;
2474
2749
  #ssbLengthConflictCount;
2475
2750
  #blockRepairRsIds;
2476
2751
  #blockRsbLengths;
@@ -2522,6 +2797,7 @@ var FECManager = class _FECManager {
2522
2797
  #highestSbn;
2523
2798
  #sourceFrontiers;
2524
2799
  #isoLocators;
2800
+ #runAnchors;
2525
2801
  #deferIsoGaps;
2526
2802
  #isoRepairRefusedCount;
2527
2803
  #isoSourceOversizeCount;
@@ -2536,7 +2812,10 @@ var FECManager = class _FECManager {
2536
2812
  #workerErrorCounts;
2537
2813
  #decoderUnavailableEvents;
2538
2814
  #repairSymbolSizeMismatchCount;
2815
+ #unlistedRepairTrackRefusals;
2816
+ #unresolvedRepairOwnerDrops;
2539
2817
  #onUndelimitedLoss;
2818
+ #onIsoHoleExpired;
2540
2819
  #encodeTrackName(catalogTrackName) {
2541
2820
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
2542
2821
  if (encoded === void 0) {
@@ -3008,7 +3287,10 @@ var FECManager = class _FECManager {
3008
3287
  timer.handle = null;
3009
3288
  this.#requestRepair(sbn, packetId, catalogTrackName);
3010
3289
  };
3011
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
3290
+ timer.handle = setTimeout(
3291
+ onFire,
3292
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
3293
+ );
3012
3294
  this.#repairDeadlines.set(key, timer);
3013
3295
  }
3014
3296
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -3152,8 +3434,14 @@ var FECManager = class _FECManager {
3152
3434
  * Vanished blocks are not enumerated here: their starts are unknown until a
3153
3435
  * repair states them. The SS_IDs between two stated blocks become one
3154
3436
  * repair-less span when the later block's repair arrives (placeIsoRepair).
3437
+ *
3438
+ * A `held` source arrived before its block was known and is fed only now
3439
+ * that a repair, a span or a closed hole placed it: how far its block start
3440
+ * then lies behind the frontier measures how long the receiver held it, not
3441
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
3442
+ * it (BLO-52085).
3155
3443
  */
3156
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
3444
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
3157
3445
  const streamKey = this.#streamKey(packetId, catalogTrackName);
3158
3446
  const now = performance.now();
3159
3447
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -3175,6 +3463,7 @@ var FECManager = class _FECManager {
3175
3463
  const discontinuity = () => {
3176
3464
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
3177
3465
  this.#noSpanRaps.delete(streamKey);
3466
+ this.#runAnchors.delete(streamKey);
3178
3467
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
3179
3468
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
3180
3469
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -3192,7 +3481,7 @@ var FECManager = class _FECManager {
3192
3481
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
3193
3482
  };
3194
3483
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
3195
- 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))) {
3484
+ 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))) {
3196
3485
  discontinuity();
3197
3486
  return;
3198
3487
  }
@@ -3345,7 +3634,7 @@ var FECManager = class _FECManager {
3345
3634
  consider(geometry2, this.#parseStreamKey(streamKey).packetId);
3346
3635
  }
3347
3636
  for (const [packetId, config] of this.#trackConfigs) consider(config.geometry, packetId);
3348
- this.#deliveryGaps.setWindowMs(windowMs);
3637
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.setWindowMs(windowMs);
3349
3638
  }
3350
3639
  /**
3351
3640
  * The multicast late-symbol wait: the block span plus the larger of the
@@ -3358,14 +3647,14 @@ var FECManager = class _FECManager {
3358
3647
  * stream order and never feeds the estimator.
3359
3648
  */
3360
3649
  #multicastWaitMs(config) {
3361
- return this.#waitForGapMs(config, this.#deliveryGaps.peakGapMs(performance.now()));
3650
+ return this.#waitForGapMs(config, this.#peakDeliveryGapMs());
3362
3651
  }
3363
3652
  /**
3364
3653
  * The widest #multicastWaitMs can become: the estimator reports at most its
3365
3654
  * catalog window, so this is a catalog quantity that no measurement moves.
3366
3655
  */
3367
3656
  #maxMulticastWaitMs(config) {
3368
- return this.#waitForGapMs(config, this.#deliveryGaps.windowMs ?? 0);
3657
+ return this.#waitForGapMs(config, this.#deliveryGaps.multicast.windowMs ?? 0);
3369
3658
  }
3370
3659
  #waitForGapMs(config, gapMs) {
3371
3660
  if (!(gapMs > 0) || !(config.interleaveDepthMs > 0)) return config.timeoutMs;
@@ -3454,17 +3743,21 @@ var FECManager = class _FECManager {
3454
3743
  this.#blockWaitDeadlinesMs.delete(key);
3455
3744
  this.#repairHoldUntilMs.delete(key);
3456
3745
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
3457
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
3746
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
3458
3747
  };
3459
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
3748
+ timer.handle = setTimeout(
3749
+ onFire,
3750
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
3751
+ );
3460
3752
  this.#activeBlocks.set(key, timer);
3461
3753
  this.#indexBlockKey(key, sbn, packetId);
3462
3754
  }
3463
3755
  /**
3464
3756
  * Hand a block whose delivery is over to its decoder for finalization: the
3465
- * datagram deadline fired, or the ordered relay moved past it.
3757
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
3758
+ * is when it was due: its deadline, or now.
3466
3759
  */
3467
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
3760
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
3468
3761
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
3469
3762
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
3470
3763
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -3480,7 +3773,7 @@ var FECManager = class _FECManager {
3480
3773
  if (workerClient) {
3481
3774
  this.#pendingWorkerCleanups.add(key);
3482
3775
  this.#pendingWorkerCleanupClients.set(key, workerClient);
3483
- this.#boundOwedCleanup(key, packetId, workerClient);
3776
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
3484
3777
  workerClient.cleanup(sbn);
3485
3778
  } else {
3486
3779
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -3545,6 +3838,7 @@ var FECManager = class _FECManager {
3545
3838
  ...(config.trackKind ?? previous.trackKind) === void 0 ? {} : { trackKind: config.trackKind ?? previous.trackKind },
3546
3839
  ...(config.codec ?? previous.codec) === void 0 ? {} : { codec: config.codec ?? previous.codec },
3547
3840
  ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry },
3841
+ ...(config.groupDurationMs ?? previous.groupDurationMs) === void 0 ? {} : { groupDurationMs: config.groupDurationMs ?? previous.groupDurationMs },
3548
3842
  ...(config.repairLayers ?? previous.repairLayers) === void 0 ? {} : { repairLayers: config.repairLayers ?? previous.repairLayers },
3549
3843
  ...(config.heldLayers ?? previous.heldLayers) === void 0 ? {} : { heldLayers: config.heldLayers ?? previous.heldLayers }
3550
3844
  };
@@ -3651,6 +3945,10 @@ var FECManager = class _FECManager {
3651
3945
  lifecycleTrace: this.#lifecycleTrace.map((entry) => ({ ...entry }))
3652
3946
  };
3653
3947
  }
3948
+ /** Count a repair packet the router dropped for want of an owning track (BLO-55759). */
3949
+ countUnresolvedRepairOwner(reason) {
3950
+ this.#unresolvedRepairOwnerDrops[reason]++;
3951
+ }
3654
3952
  get fecStats() {
3655
3953
  const s = this.#fecStats;
3656
3954
  const affected = s.blocksRecovered + s.blocksFailed;
@@ -3690,6 +3988,8 @@ var FECManager = class _FECManager {
3690
3988
  packetId
3691
3989
  })),
3692
3990
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
3991
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
3992
+ unresolvedRepairOwnerDrops: { ...this.#unresolvedRepairOwnerDrops },
3693
3993
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
3694
3994
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
3695
3995
  };
@@ -3714,6 +4014,16 @@ var FECManager = class _FECManager {
3714
4014
  this.#startupRepairBoundaryCounts.clear();
3715
4015
  this.#startupRepairFailOpenPackets.clear();
3716
4016
  }
4017
+ /**
4018
+ * Start a new "mfu-datagram" leg (mmt-02 4.3.1) without discarding
4019
+ * track/decoder state: the same join-boundary rules as a multicast join,
4020
+ * since the leg starts at an arbitrary datagram too. It resets the whole
4021
+ * join boundary of this manager, a multicast ordered-relay frontier
4022
+ * included, so a host gives the leg a manager of its own.
4023
+ */
4024
+ beginLegJoin() {
4025
+ this.beginMulticastJoin();
4026
+ }
3717
4027
  /** How the multicast leg currently delivers symbols. */
3718
4028
  get multicastSymbolDelivery() {
3719
4029
  return this.#multicastSymbolDelivery;
@@ -3736,7 +4046,8 @@ var FECManager = class _FECManager {
3736
4046
  );
3737
4047
  }
3738
4048
  if (delivery === this.#multicastSymbolDelivery) return;
3739
- this.#deliveryGaps.reset();
4049
+ this.#deliveryGaps.multicast.reset();
4050
+ this.#runAnchors.clear();
3740
4051
  if (delivery === "ordered-relay") {
3741
4052
  for (const [packetId, config] of this.#trackConfigs) {
3742
4053
  this.#orderedHorizonBlocksFor(packetId, config);
@@ -3792,7 +4103,9 @@ var FECManager = class _FECManager {
3792
4103
  }
3793
4104
  resetMap(this.#blockSourceCounts);
3794
4105
  resetMap(this.#blockSourceEsis);
4106
+ resetMap(this.#blockRebuiltEsis);
3795
4107
  resetMap(this.#blockAuthoredLengths);
4108
+ resetSet(this.#isoSpanKeys);
3796
4109
  resetMap(this.#blockRepairRsIds);
3797
4110
  resetMap(this.#blockRsbLengths);
3798
4111
  resetMap(this.#heldLayerStates);
@@ -3823,6 +4136,7 @@ var FECManager = class _FECManager {
3823
4136
  resetMap(this.#highestSbn);
3824
4137
  resetMap(this.#sourceFrontiers);
3825
4138
  resetMap(this.#isoLocators);
4139
+ resetMap(this.#runAnchors);
3826
4140
  resetMap(this.#sourceAnchors);
3827
4141
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
3828
4142
  this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
@@ -3916,7 +4230,9 @@ var FECManager = class _FECManager {
3916
4230
  dropMap(this.#pendingWorkerCleanupClients);
3917
4231
  dropMap(this.#blockSourceCounts);
3918
4232
  dropMap(this.#blockSourceEsis);
4233
+ dropMap(this.#blockRebuiltEsis);
3919
4234
  dropMap(this.#blockAuthoredLengths);
4235
+ dropSet(this.#isoSpanKeys);
3920
4236
  dropMap(this.#blockRepairRsIds);
3921
4237
  dropMap(this.#blockRsbLengths);
3922
4238
  dropMap(this.#blockPathCounts);
@@ -3930,6 +4246,7 @@ var FECManager = class _FECManager {
3930
4246
  dropMap(this.#highestSbn);
3931
4247
  dropMap(this.#sourceFrontiers);
3932
4248
  dropMap(this.#isoLocators);
4249
+ dropMap(this.#runAnchors);
3933
4250
  dropMap(this.#sourceAnchors);
3934
4251
  dropMap(this.#classifiers);
3935
4252
  dropMap(this.#noSpanRaps);
@@ -3997,8 +4314,8 @@ var FECManager = class _FECManager {
3997
4314
  const sourceSymbols = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? this.#trackConfig(packetId).k;
3998
4315
  const isSourceSymbol = esi >= 0 && esi < sourceSymbols;
3999
4316
  const isStartupPartial = this.#startupPartialBlocks.has(blockKey);
4000
- const isReadyMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
4001
- const awaitingMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !this.#startupRepairReadyPackets.has(streamKey) && !this.#startupRepairFailOpenPackets.has(streamKey);
4317
+ const isReadyMulticastRepair = this.#startupRequireRepairReady && source !== "moq" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
4318
+ const awaitingMulticastRepair = this.#startupRequireRepairReady && source !== "moq" && !this.#startupRepairReadyPackets.has(streamKey) && !this.#startupRepairFailOpenPackets.has(streamKey);
4002
4319
  if (awaitingMulticastRepair) {
4003
4320
  if (!isSourceSymbol) {
4004
4321
  this.#startupRepairReadyPackets.add(streamKey);
@@ -4052,12 +4369,14 @@ var FECManager = class _FECManager {
4052
4369
  ...catalogTrackName === void 0 ? {} : { catalogTrackName },
4053
4370
  multicastSymbols: 0,
4054
4371
  moqSymbols: 0,
4372
+ datagramSymbols: 0,
4055
4373
  complete: false
4056
4374
  };
4057
4375
  const receivedAtMs = this.#receiptNow();
4058
4376
  const anchorMs = this.#blockAnchorsMs.get(blockKey);
4059
4377
  if (anchorMs === void 0 || receivedAtMs < anchorMs) this.#blockAnchorsMs.set(blockKey, receivedAtMs);
4060
4378
  if (source === "multicast") counts.multicastSymbols++;
4379
+ else if (source === "moq-datagram") counts.datagramSymbols++;
4061
4380
  else counts.moqSymbols++;
4062
4381
  this.#blockPathCounts.set(blockKey, counts);
4063
4382
  this.#observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName);
@@ -4078,7 +4397,7 @@ var FECManager = class _FECManager {
4078
4397
  this.#unindexBlockKey(key);
4079
4398
  }
4080
4399
  }
4081
- if (isSourceSymbol && source === "multicast") {
4400
+ if (isSourceSymbol && source !== "moq") {
4082
4401
  this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
4083
4402
  }
4084
4403
  return true;
@@ -4167,8 +4486,22 @@ var FECManager = class _FECManager {
4167
4486
  * DeliveryGapEstimator). Datagram delivery only.
4168
4487
  */
4169
4488
  noteMulticastArrival(packetId, packetSequenceNumber) {
4170
- if (this.#multicastSymbolDelivery !== "datagram") return;
4171
- this.#deliveryGaps.noteArrival(performance.now(), packetId, packetSequenceNumber);
4489
+ this.noteArrival("multicast", packetId, packetSequenceNumber);
4490
+ }
4491
+ /**
4492
+ * Record one MMTP packet arrival on a lossy path for that path's
4493
+ * delivery-gap measurement: the multicast leg (datagram delivery only; an
4494
+ * ordered relay settles by stream order) or an "mfu-datagram" leg, whose
4495
+ * datagrams are always a lossy path (#lossyDatagramPath).
4496
+ */
4497
+ noteArrival(path, packetId, packetSequenceNumber) {
4498
+ if (!this.#lossyDatagramPath(path)) return;
4499
+ this.#deliveryGaps[path].noteArrival(performance.now(), packetId, packetSequenceNumber);
4500
+ }
4501
+ /** The largest delivery gap any lossy path measured over its window. */
4502
+ #peakDeliveryGapMs() {
4503
+ const now = performance.now();
4504
+ return Math.max(...Object.values(this.#deliveryGaps).map((estimator) => estimator.peakGapMs(now)));
4172
4505
  }
4173
4506
  /**
4174
4507
  * Resolved per-track multicast late-symbol wait in milliseconds: the span
@@ -4182,16 +4515,18 @@ var FECManager = class _FECManager {
4182
4515
  * Largest multicast delivery gap measured over the current window (ms), and
4183
4516
  * that window (undefined: held since the last reset). Diagnostics.
4184
4517
  */
4185
- multicastDeliveryGap() {
4518
+ multicastDeliveryGap(path = "multicast") {
4186
4519
  return {
4187
- peakGapMs: this.#deliveryGaps.peakGapMs(performance.now()),
4188
- windowMs: this.#deliveryGaps.windowMs
4520
+ peakGapMs: this.#deliveryGaps[path].peakGapMs(performance.now()),
4521
+ windowMs: this.#deliveryGaps[path].windowMs
4189
4522
  };
4190
4523
  }
4191
4524
  /**
4192
4525
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
4193
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
4194
- * Undefined for a block that is not open.
4526
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
4527
+ * repair-less span states its length, and RSB_length 0 when it is longer
4528
+ * than K, since no repair can reach it). Undefined for a block that is not
4529
+ * open.
4195
4530
  */
4196
4531
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
4197
4532
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4259,8 +4594,9 @@ var FECManager = class _FECManager {
4259
4594
  return true;
4260
4595
  }
4261
4596
  /**
4262
- * Drop a block's repair hold: its FETCH ended without delivering. The block
4263
- * falls back to its multicast wait, which may already have passed.
4597
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
4598
+ * back only a repair that cannot complete it. The block falls back to its
4599
+ * multicast wait, which may already have passed.
4264
4600
  */
4265
4601
  releaseRepairHold(sbn, packetId, catalogTrackName) {
4266
4602
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4280,6 +4616,23 @@ var FECManager = class _FECManager {
4280
4616
  const config = this.#trackConfigs.get(packetId);
4281
4617
  return config === void 0 ? void 0 : this.#blockLifetimeMs(config);
4282
4618
  }
4619
+ /**
4620
+ * How long an "mfu-datagram" leg's duplicate ledgers must remember a packet
4621
+ * so a legal reorder never reads as a publisher restart: one block span,
4622
+ * the reorder tolerance (`timeoutMs` is span + tolerance) and one group,
4623
+ * since a datagram may trail the stream by a whole group behind a joining
4624
+ * FETCH (mmt-02 6.1 step 3). The group is the catalog group duration
4625
+ * (`groupDurationMs`), whatever the track kind; a video track configured
4626
+ * without one falls back to its keyframe interval (one GOP per group).
4627
+ * Undefined for an unconfigured packet id.
4628
+ */
4629
+ datagramLegLedgerRetentionMsForPacket(packetId) {
4630
+ const config = this.#trackConfigs.get(packetId);
4631
+ if (config === void 0) return void 0;
4632
+ const geometry2 = config.geometry;
4633
+ const groupMs = config.groupDurationMs ?? (geometry2?.trackKind === "video" && geometry2.mode === "classifying" ? geometry2.keyframeInterval.ticks / geometry2.keyframeInterval.timescale * 1e3 : 0);
4634
+ return config.timeoutMs + (Number.isFinite(groupMs) ? groupMs : 0);
4635
+ }
4283
4636
  /**
4284
4637
  * How long a terminal (clean, recovered or failed) block stays authoritative,
4285
4638
  * for late symbols and for the in-order release gate. It is also the gate's
@@ -4306,7 +4659,7 @@ var FECManager = class _FECManager {
4306
4659
  }
4307
4660
  const trackConfig = this.#trackConfigs.get(packetId);
4308
4661
  if (trackConfig === void 0) return void 0;
4309
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
4662
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
4310
4663
  }
4311
4664
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
4312
4665
  // -----------------------------------------------------------------------
@@ -4348,6 +4701,9 @@ var FECManager = class _FECManager {
4348
4701
  for (const key of [...this.#isoLocators.keys()]) {
4349
4702
  if (this.#belongsToPacket(key, packetId)) this.#isoLocators.delete(key);
4350
4703
  }
4704
+ for (const key of [...this.#runAnchors.keys()]) {
4705
+ if (this.#belongsToPacket(key, packetId)) this.#runAnchors.delete(key);
4706
+ }
4351
4707
  }
4352
4708
  /**
4353
4709
  * The iso-ssbg1-v1 locator horizon in blocks: every block the manager can
@@ -4397,8 +4753,9 @@ var FECManager = class _FECManager {
4397
4753
  holdIsoSource(packetId, catalogTrackName, ssId, source) {
4398
4754
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4399
4755
  const evictedBefore = locator.heldEvicted;
4400
- const held = locator.hold(ssId, source);
4401
- if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4756
+ const held = locator.hold(ssId, source.arrivedAtMs === void 0 ? { ...source, arrivedAtMs: this.#receiptNow() } : source);
4757
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4758
+ if (held && source.source !== "moq") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4402
4759
  const evicted = locator.heldEvicted - evictedBefore;
4403
4760
  if (evicted > 0) {
4404
4761
  const before = this.#isoHeldEvictedCount;
@@ -4419,17 +4776,20 @@ var FECManager = class _FECManager {
4419
4776
  * contradicts a known block is refused (counted) and must be dropped.
4420
4777
  */
4421
4778
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
4422
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
4779
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4780
+ const placement = locator.placeRepair(ssStart, ssbLength);
4781
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4423
4782
  if (placement.status !== "placed") {
4424
4783
  this.#isoRepairRefusedCount++;
4425
4784
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
4426
4785
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
4427
4786
  }
4787
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
4428
4788
  return placement;
4429
4789
  }
4790
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
4430
4791
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
4431
4792
  if (placement.hole !== void 0) {
4432
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
4433
4793
  const hole = placement.hole.block;
4434
4794
  const previous = locator.blockEndingAt(hole.start);
4435
4795
  const loss = {
@@ -4450,17 +4810,29 @@ var FECManager = class _FECManager {
4450
4810
  * `handler`, instead of a repair-less span; null restores spans. Set by the
4451
4811
  * range repair scheduler; applies to every stream from its next gap. The
4452
4812
  * handler and the deferral are one setting, so no hole is ever created with
4453
- * nobody to close it.
4813
+ * nobody to close it. `onExpired` is told of each pending hole the stream
4814
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
4815
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
4816
+ * reported; otherwise the hole is discarded with its sources.
4454
4817
  */
4455
- setUndelimitedLossHandler(handler) {
4818
+ setUndelimitedLossHandler(handler, onExpired = null) {
4456
4819
  this.#onUndelimitedLoss = handler;
4820
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
4457
4821
  this.#deferIsoGaps = handler !== null;
4458
4822
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
4459
4823
  }
4824
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
4825
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
4826
+ for (const hole of locator.takeExpiredHoles()) {
4827
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
4828
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
4829
+ }
4830
+ }
4460
4831
  /**
4461
- * The range repair for a hole ended: every hole still pending inside
4462
- * `[start, start + length)` becomes a repair-less span. Returns those spans
4463
- * with the held sources they placed, for the caller to feed (MmtpRouter).
4832
+ * The range repair for a hole ended: every hole inside `[start, start +
4833
+ * length)`, pending or expired, becomes a repair-less span. Returns those
4834
+ * spans with the held sources they placed, for the caller to feed
4835
+ * (MmtpRouter).
4464
4836
  */
4465
4837
  closeIsoHoles(packetId, catalogTrackName, start, length) {
4466
4838
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -4476,17 +4848,37 @@ var FECManager = class _FECManager {
4476
4848
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
4477
4849
  * SS_ID of which vanished resolves through its deadline like any vanished
4478
4850
  * block.
4851
+ *
4852
+ * A span longer than K holds more than one block (SSB_length <= K), and the
4853
+ * locator states no block inside a span, only one exactly its range
4854
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
4855
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
4856
+ * Group of it (group-cannot-complete). Every span still keeps its whole
4857
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
4858
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
4859
+ * gate lets those frames go once only a late source can fill the gap
4860
+ * before them, as long after they arrived as the gap's decision allows
4861
+ * (isoRepairlessWaitMs).
4479
4862
  */
4480
4863
  #openIsoSpan(span, packetId, catalogTrackName) {
4481
4864
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
4482
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
4865
+ if (!this.#blockAuthoredLengths.has(key)) {
4866
+ this.#blockAuthoredLengths.set(key, span.block.length);
4867
+ this.#isoSpanKeys.add(key);
4868
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
4869
+ }
4483
4870
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
4484
4871
  }
4485
4872
  /**
4486
4873
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
4487
4874
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
4488
4875
  * that could hold them is pending or not yet stated by a repair, else the
4489
- * starts of the blocks that failed or vanished.
4876
+ * starts of the blocks that failed or vanished. SS_IDs no repair has
4877
+ * delimited yet that all arrived lost nothing and wait for no repair, only
4878
+ * the late-source allowance after the datagram of a lossy path that clocks
4879
+ * them arrived (#lossFreeRunReadyAtMs), and not even that when none of them
4880
+ * came as one; one missing makes a run that waits as one block
4881
+ * (isoRepairlessWaitMs).
4490
4882
  *
4491
4883
  * `untracked` reads as the release gate reads it (MmtpRouter
4492
4884
  * #createFecReleaseGate): a block holding either released frame's SS_ID
@@ -4499,7 +4891,16 @@ var FECManager = class _FECManager {
4499
4891
  isoSpanResolution(packetId, catalogTrackName, fromSsId, toSsId) {
4500
4892
  if (!serial32Precedes(fromSsId, toSsId) || serial32Distance(fromSsId, toSsId) <= 1) return [];
4501
4893
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
4502
- if (!locator || !locator.coversBetween(fromSsId, toSsId)) return null;
4894
+ if (!locator) return null;
4895
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
4896
+ if (run?.missing !== void 0) return null;
4897
+ if (run !== null) {
4898
+ const config = this.#trackConfigs.get(packetId);
4899
+ const readyAtMs = config === void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
4900
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) return null;
4901
+ }
4902
+ if (locator.coverageEnd === void 0) return [];
4903
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return null;
4503
4904
  const highest = this.highestSbn(packetId, catalogTrackName);
4504
4905
  const lost = [];
4505
4906
  for (const block of locator.blocksBetween(fromSsId, toSsId)) {
@@ -4517,6 +4918,162 @@ var FECManager = class _FECManager {
4517
4918
  }
4518
4919
  return lost;
4519
4920
  }
4921
+ /**
4922
+ * When undelimited SS_IDs from `runStart` up to `toSsId` that all arrived
4923
+ * stop holding its frame: the late-source allowance after the receipt of
4924
+ * a datagram of a lossy path (#lossyDatagramPath: a multicast datagram, or
4925
+ * one of an "mfu-datagram" leg). Until then a frame between them may still
4926
+ * complete from a packet with no SS_ID (an untagged FT=0/FT=1 reordered
4927
+ * behind the next frame), and a repair may delimit them. The receipt is
4928
+ * `toSsId`'s own when it is held from such a datagram. Otherwise (its
4929
+ * packet came only as an overlap copy or from a MoQ stream, or was evicted
4930
+ * or retired) it is the newest among those SS_IDs, every one of which is
4931
+ * held and states its path. So the time moves at most once, when the
4932
+ * head's own datagram copy arrives while its frame waits or its held
4933
+ * source is dropped, and never on a later ask.
4934
+ *
4935
+ * Undefined, so the range releases at once, when no SS_ID of it came as
4936
+ * such a datagram: a MoQ arrival, an ordered relay's and the frame's own
4937
+ * are no clock for datagram reordering (#lossyReceiptMs). Undefined too
4938
+ * on a track with no catalog span, which states no allowance: the local
4939
+ * timeout is a cleanup bound, and isoRepairlessWaitMs arms no wake there,
4940
+ * so a wait would hold the frame until the next packet. The cost, on
4941
+ * multicast and on the leg too: an untagged FT=0/FT=1 reordered behind
4942
+ * the next frame of such a track is dropped stale.
4943
+ */
4944
+ #lossFreeRunReadyAtMs(config, locator, runStart, toSsId) {
4945
+ if (!_FECManager.#hasCatalogTiming(config)) return void 0;
4946
+ let clockMs = this.#lossyReceiptMs(locator.heldSource(toSsId));
4947
+ if (clockMs === void 0) {
4948
+ for (let ssId = runStart; ssId !== toSsId; ssId = ssId + 1 >>> 0) {
4949
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
4950
+ if (atMs !== void 0 && (clockMs === void 0 || atMs > clockMs)) clockMs = atMs;
4951
+ }
4952
+ }
4953
+ if (clockMs === void 0) return void 0;
4954
+ return clockMs + Math.max(0, this.#multicastWaitMs(config) - config.interleaveDepthMs);
4955
+ }
4956
+ /**
4957
+ * Receipt time of a held source that came as a datagram of a lossy path
4958
+ * (#lossyDatagramPath), else undefined: a MoQ stream and an ordered relay
4959
+ * deliver in order, so their arrivals clock no reorder allowance and no
4960
+ * FEC deadline. The path is the one the feed stated (IsoHeldSource.source,
4961
+ * and MulticastSymbolDelivery for a multicast source), never a guess.
4962
+ */
4963
+ #lossyReceiptMs(held) {
4964
+ return held !== void 0 && this.#lossyDatagramPath(held.source) ? held.arrivedAtMs : void 0;
4965
+ }
4966
+ /**
4967
+ * The one path predicate of the loss gates: whether a symbol fed as
4968
+ * `source` reached this manager as a datagram of its own, on a path that
4969
+ * loses and reorders (mmt-02 Section 2, a datagram leg). A multicast
4970
+ * symbol does unless its provider declared an ordered relay. An
4971
+ * "mfu-datagram" object always does (4.3.1): MulticastSymbolDelivery is
4972
+ * the multicast provider's statement and is never read for the leg. A MoQ
4973
+ * stream object never does, a stream copy of the leg included.
4974
+ */
4975
+ #lossyDatagramPath(source) {
4976
+ return source === "moq-datagram" || source === "multicast" && this.#multicastSymbolDelivery === "datagram";
4977
+ }
4978
+ /**
4979
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
4980
+ * between two released frames' SS_IDs once only a late source can still
4981
+ * fill them, else undefined. That is when every one missing (neither
4982
+ * arrived nor held) lies in a repair-less span longer than K, which no
4983
+ * repair can state a block of (#openIsoSpan), or in a stated block its
4984
+ * own repair group cannot complete every SS_ID of which it misses lies
4985
+ * between them (so the gap's decision covers all it lost), and a source of
4986
+ * a lossy leg (multicast, or an "mfu-datagram" leg's datagram) at or past
4987
+ * `toSsId` arrived, so each is lost or reordered behind it (a MoQ source
4988
+ * shows nothing: MoQ streams overtake one another). The span or block
4989
+ * itself keeps its own wait.
4990
+ *
4991
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
4992
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
4993
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
4994
+ * Then the frame waits as a stated block its group cannot complete does
4995
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
4996
+ * overlay's span plus the larger of the allowance and its tolerance, or,
4997
+ * for an overlay that states no span, the span's whole wait (undefined).
4998
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
4999
+ * the gap holds a stated block's loss.
5000
+ *
5001
+ * A run of SS_IDs no repair has delimited yet, one of which never arrived,
5002
+ * is one block of its own instead (draft-ramadan-moq-fec-multicast-00,
5003
+ * Receiver Repair Policy; on an "mfu-datagram" leg fec-core-00 9.3 and
5004
+ * mmt-02 5.3.3): the frame then waits for that block's FEC deadline,
5005
+ * whatever the flags: ts plus the whole multicast wait (fec-core-00 9.3),
5006
+ * ts the receipt of the lowest held source above the run that came as a
5007
+ * datagram of a lossy path (#lossyDatagramPath), up to the newest
5008
+ * (fec-multicast-00, Deadline Anchoring; under reordering at or after the
5009
+ * draft's first signal, never before). The wait returned counts from
5010
+ * `arrivedAtMs`, the frame's arrival; without it, it is the whole wait.
5011
+ * With no such source held (never arrived, retired, or evicted, or every
5012
+ * one from a MoQ stream or an ordered relay) the frame keeps the hold
5013
+ * ceiling: a stream arrival is no clock for a datagram deadline.
5014
+ */
5015
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false, arrivedAtMs) {
5016
+ const config = this.#trackConfigs.get(packetId);
5017
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
5018
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
5019
+ const locator = this.#isoLocators.get(streamKey);
5020
+ if (locator === void 0) return void 0;
5021
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
5022
+ const readyAtMs = run === null || run.missing !== void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
5023
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) {
5024
+ return Math.max(0, readyAtMs - (arrivedAtMs ?? this.#receiptNow()));
5025
+ }
5026
+ const newestSource = locator.newestSource;
5027
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
5028
+ if (run?.missing !== void 0) {
5029
+ if (this.isoSpanResolution(packetId, catalogTrackName, fromSsId, run.start) === null) return void 0;
5030
+ const kept = this.#runAnchors.get(streamKey);
5031
+ const anchor = kept?.fromSsId === fromSsId && this.#receiptNow() - kept.tsMs <= 2 * (config.interleaveDepthMs + 2 * this.#blockLifetimeMs(config)) ? kept : void 0;
5032
+ let tsMs = anchor?.tsMs;
5033
+ for (let ssId = run.missing + 1 >>> 0; !serial32Precedes(newestSource, ssId); ssId = ssId + 1 >>> 0) {
5034
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
5035
+ if (atMs === void 0) continue;
5036
+ if (tsMs === void 0 || atMs < tsMs) tsMs = atMs;
5037
+ break;
5038
+ }
5039
+ if (tsMs === void 0) return void 0;
5040
+ const waitMs2 = this.#multicastWaitMs(config);
5041
+ let counted = anchor?.counted === true;
5042
+ if (!counted && tsMs + waitMs2 <= this.#receiptNow()) {
5043
+ counted = true;
5044
+ this.onUndelimitedRunGap?.(packetId, catalogTrackName);
5045
+ }
5046
+ this.#runAnchors.set(streamKey, { fromSsId, tsMs, counted });
5047
+ return arrivedAtMs === void 0 ? waitMs2 : Math.max(0, tsMs + waitMs2 - arrivedAtMs);
5048
+ }
5049
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return void 0;
5050
+ let repairless = false;
5051
+ let stated = false;
5052
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
5053
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
5054
+ if (this.#completedBlocks.has(key)) continue;
5055
+ if (block.span && block.length > locator.kMax) {
5056
+ repairless = true;
5057
+ continue;
5058
+ }
5059
+ const received = this.#blockSourceEsis.get(key);
5060
+ const rebuilt = this.#blockRebuiltEsis.get(key);
5061
+ let missesInGap = false;
5062
+ let missesOutside = false;
5063
+ for (let esi = 0; esi < block.length; esi++) {
5064
+ const ssId = serial32Add(block.start, esi);
5065
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
5066
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
5067
+ else if (!rebuilt?.has(esi)) missesOutside = true;
5068
+ }
5069
+ if (!missesInGap) continue;
5070
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
5071
+ repairless = stated = true;
5072
+ }
5073
+ if (!repairless) return void 0;
5074
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
5075
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
5076
+ }
4520
5077
  /**
4521
5078
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
4522
5079
  * the sources held now for a block no repair has stated yet, and the held
@@ -4570,11 +5127,31 @@ var FECManager = class _FECManager {
4570
5127
  * it does not. A stream with no classifier yet has shown nothing against it,
4571
5128
  * and neither has a stream without catalog timing until it releases two
4572
5129
  * RAPs inside one MPU.
4573
- */
4574
- mpuBoundsRapsFor(packetId, catalogTrackName) {
5130
+ *
5131
+ * With catalog timing and a `gap` inside one MPU, between the authored
5132
+ * timing of the frames on either side, it also takes the catalog keyframe
5133
+ * interval to rule a keyframe out of the gap
5134
+ * (`BlockClassifier.keyframeFreeBetween`, fec-multicast-00 Block
5135
+ * Classification item 3), and no source held between the frames' SS_IDs
5136
+ * may carry the RAP flag or another MPU's number (item 1 read on the held
5137
+ * packets: a RAP the loss cut in two is never released, so the frames
5138
+ * alone cannot show it); anything unknown counts as a keyframe.
5139
+ */
5140
+ mpuBoundsRapsFor(packetId, catalogTrackName, gap) {
4575
5141
  const streamKey = this.#streamKey(packetId, catalogTrackName);
4576
5142
  if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
4577
- return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true;
5143
+ const classifier = this.#classifiers.get(streamKey);
5144
+ if (gap === void 0) return classifier?.mpuBoundsRaps ?? true;
5145
+ const { mpu, from, to, fromSsId, toSsId } = gap;
5146
+ if (fromSsId !== void 0 && toSsId !== void 0) {
5147
+ const run = this.#isoLocators.get(streamKey)?.undelimitedBetween(
5148
+ fromSsId,
5149
+ toSsId,
5150
+ ({ evidence }) => evidence.rap || evidence.mpu !== void 0 && evidence.mpu !== mpu
5151
+ );
5152
+ if (run?.flagged) return false;
5153
+ }
5154
+ return classifier !== void 0 && from !== void 0 && to !== void 0 && from.mediaTimescale === to.mediaTimescale && classifier.keyframeFreeBetween(mpu, from.decodeTime, to.decodeTime, from.mediaTimescale);
4578
5155
  }
4579
5156
  /** A block's class now, or frozen at its resolution. */
4580
5157
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -4597,9 +5174,11 @@ var FECManager = class _FECManager {
4597
5174
  }
4598
5175
  /**
4599
5176
  * Record a RAP frame released in order, for the classifier's RAP-spacing
4600
- * invariant (consecutive MPUs exactly one keyframe interval apart).
5177
+ * invariant (consecutive MPUs exactly one keyframe interval apart) and,
5178
+ * with its decode time, as the MPU start gap decisions measure the catalog
5179
+ * keyframe interval from (mpuBoundsRapsFor).
4601
5180
  */
4602
- noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
5181
+ noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale, decodeTime) {
4603
5182
  if (!this.#trackConfigs.has(packetId)) return;
4604
5183
  if (!this.#hasCatalogTimingForPacket(packetId)) {
4605
5184
  const streamKey = this.#streamKey(packetId, catalogTrackName);
@@ -4614,7 +5193,8 @@ var FECManager = class _FECManager {
4614
5193
  this.#classifierFor(packetId, catalogTrackName).noteReleasedRap(
4615
5194
  mpu,
4616
5195
  presentationTime,
4617
- mediaTimescale
5196
+ mediaTimescale,
5197
+ decodeTime
4618
5198
  )
4619
5199
  );
4620
5200
  }
@@ -4820,11 +5400,14 @@ var FECManager = class _FECManager {
4820
5400
  });
4821
5401
  client.onCleanupComplete((sbn) => {
4822
5402
  if (this.#releasedWorkerClients.has(client)) return;
4823
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
5403
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
5404
+ const cleanupKeys = owed.filter((key) => {
4824
5405
  const block = this.#parseBlockKey(key);
4825
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
5406
+ return block.packetId === packetId && block.sbn === sbn;
4826
5407
  });
4827
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
5408
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
5409
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
5410
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
4828
5411
  });
4829
5412
  client.onError((msg, code) => {
4830
5413
  const requestedKind = code ?? msg;
@@ -4894,9 +5477,11 @@ var FECManager = class _FECManager {
4894
5477
  * fail deadline already passed, so failing it is the decision that deadline
4895
5478
  * made. A late ack then finds nothing owed and is a no-op.
4896
5479
  */
4897
- #boundOwedCleanup(key, packetId, client) {
5480
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
4898
5481
  this.#clearOwedCleanupBound(key);
4899
5482
  const bound = {
5483
+ dueAtMs,
5484
+ askedAtMs: performance.now(),
4900
5485
  handle: setTimeout(() => {
4901
5486
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
4902
5487
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -4994,7 +5579,15 @@ var FECManager = class _FECManager {
4994
5579
  this.#isoSourceOversizeCount++;
4995
5580
  return null;
4996
5581
  }
4997
- const sbn = located.block.start;
5582
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
5583
+ }
5584
+ /**
5585
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
5586
+ * answers through onFrame (null here), or its synchronous decoder, whose
5587
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
5588
+ * stated for `ssId`.
5589
+ */
5590
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
4998
5591
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
4999
5592
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
5000
5593
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -5023,6 +5616,74 @@ var FECManager = class _FECManager {
5023
5616
  }
5024
5617
  return recovered;
5025
5618
  }
5619
+ /**
5620
+ * Feed a source symbol of this stream that another FEC instance over the
5621
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
5622
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
5623
+ * BLO-52085). It joins its block's decoder as a received source would, so
5624
+ * it reduces the erasures the block still has to solve, but it is not a
5625
+ * network arrival: no transport accounting, no classification evidence,
5626
+ * no deadline refresh, and it never makes a block clean.
5627
+ *
5628
+ * Only a block a repair stated takes one (a repair-less span has no
5629
+ * decoder block). A block that is terminal, or already holds that source,
5630
+ * does not. The symbol is the exact protected packet, unpadded, as
5631
+ * feedSourceSymbol takes it.
5632
+ *
5633
+ * `recovered` is the block the synchronous decoder completed with it; the
5634
+ * caller routes it and completes the block, as for any recovery. When
5635
+ * every source of the block is then present, received or rebuilt, and no
5636
+ * decoder returned it (a Worker answers asynchronously, and reports such a
5637
+ * block as clean on its own side), the block is completed here as
5638
+ * recovered, with nothing left to route.
5639
+ */
5640
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
5641
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
5642
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
5643
+ if (located === null || located.block.span) return NOT_TAKEN;
5644
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
5645
+ const sbn = located.block.start;
5646
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
5647
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
5648
+ let rebuilt = this.#blockRebuiltEsis.get(key);
5649
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
5650
+ if (rebuilt === void 0) {
5651
+ rebuilt = /* @__PURE__ */ new Set();
5652
+ this.#blockRebuiltEsis.set(key, rebuilt);
5653
+ }
5654
+ const config = this.#trackConfigs.get(packetId);
5655
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
5656
+ rebuilt.add(located.esi);
5657
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
5658
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
5659
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
5660
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
5661
+ }
5662
+ }
5663
+ return { taken: true, recovered };
5664
+ }
5665
+ /**
5666
+ * A block that holds every one of its `length` sources, received or
5667
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
5668
+ * every packet of it was delivered, by its own arrival or by the instance
5669
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
5670
+ */
5671
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
5672
+ const rebuilt = this.#blockRebuiltEsis.get(key);
5673
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
5674
+ let present = rebuilt.size;
5675
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
5676
+ if (present < length) return false;
5677
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
5678
+ this.countRecovery(packetId, sbn, catalogTrackName);
5679
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5680
+ if (catalogTrackName === void 0) {
5681
+ this.onBlockComplete?.(sbn, packetId);
5682
+ } else {
5683
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
5684
+ }
5685
+ return true;
5686
+ }
5026
5687
  /**
5027
5688
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
5028
5689
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -5084,7 +5745,10 @@ var FECManager = class _FECManager {
5084
5745
  this.#layerAnchorHorizon(packetId),
5085
5746
  this.#sourceFrontiers.get(streamKey)?.sbn
5086
5747
  );
5087
- if (verdict === "discard") return false;
5748
+ if (verdict === "discard") {
5749
+ this.#unlistedRepairTrackRefusals++;
5750
+ return false;
5751
+ }
5088
5752
  if (verdict !== void 0) {
5089
5753
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName);
5090
5754
  return false;
@@ -5233,15 +5897,17 @@ var FECManager = class _FECManager {
5233
5897
  * its sources in send order, so one that moves the stream's newest source
5234
5898
  * position past a block leaves the sources that block still misses
5235
5899
  * reordered behind it at best: it shortens the wait of every block it
5236
- * passed that only a late source can complete. MoQ is left out: its streams
5237
- * can overtake one another, so a MoQ source shows nothing about the sources
5238
- * sent before it.
5900
+ * passed that only a late source can complete. Reliable MoQ is left out:
5901
+ * its streams can overtake one another, so a MoQ source shows nothing
5902
+ * about the sources sent before it. An "mfu-datagram" leg is in: its
5903
+ * datagrams leave the publisher in send order and reorder only within the
5904
+ * path's tolerance, as multicast does.
5239
5905
  */
5240
5906
  #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
5241
5907
  const previous = locator.newestSource;
5242
5908
  if (!locator.noteSource(ssId) || previous === void 0) return;
5243
5909
  for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
5244
- if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5910
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5245
5911
  this.#shortenUnrecoverableWait(
5246
5912
  this.#blockKey(block.start, packetId, catalogTrackName),
5247
5913
  block.start,
@@ -5259,18 +5925,61 @@ var FECManager = class _FECManager {
5259
5925
  * covers repair symbols paced after its sources, buys it nothing: it waits
5260
5926
  * the late-symbol allowance alone, the multicast wait less the span (the
5261
5927
  * catalog tolerance or the measured delivery gap). Undefined for any other
5262
- * block.
5928
+ * block. While a keyframe overlay is installed, the block waits for its
5929
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
5930
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
5931
+ * resolution is what releases the frames behind it, and failing it early
5932
+ * released them past a keyframe the overlay was still rebuilding, which
5933
+ * then arrived stale. The release gate lets them go instead
5934
+ * (isoRepairlessWaitMs).
5263
5935
  */
5264
5936
  #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
5937
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
5265
5938
  const authoredLength = this.#blockAuthoredLengths.get(key);
5266
- const rsbLength = this.#blockRsbLengths.get(key);
5267
- if (authoredLength === void 0 || rsbLength === void 0) return void 0;
5268
- if ((this.#blockSourceCounts.get(key) ?? 0) + rsbLength >= authoredLength) return void 0;
5269
5939
  const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
5270
5940
  if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5271
5941
  return void 0;
5272
5942
  }
5273
- return this.#multicastWaitMs(config) - config.interleaveDepthMs;
5943
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
5944
+ }
5945
+ /**
5946
+ * A repair stated the block, and its sources plus every symbol its repair
5947
+ * group carries (RSB_length) are short of its SSB_length.
5948
+ */
5949
+ #groupCannotComplete(key) {
5950
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5951
+ const rsbLength = this.#blockRsbLengths.get(key);
5952
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
5953
+ let present = this.#blockSourceCounts.get(key) ?? 0;
5954
+ const received = this.#blockSourceEsis.get(key);
5955
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5956
+ return present + rsbLength < authoredLength;
5957
+ }
5958
+ /**
5959
+ * How long a loss only a late source or an installed keyframe overlay can
5960
+ * still fill waits once a later source passed it: the late-symbol
5961
+ * allowance alone (the multicast wait less the span) while no overlay is
5962
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
5963
+ * RAP packet the loss took: a second FEC instance over the same packets
5964
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
5965
+ * span, unrelated to the base's. That packet can complete a stated block
5966
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
5967
+ * first lets the release gate pass the keyframe, whose rebuild then lands
5968
+ * stale. The overlay repair of a packet the loss took goes out within the
5969
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
5970
+ * sent after it, so the loss waits that span plus the larger of the
5971
+ * allowance and the overlay's own tolerance. An overlay that states no
5972
+ * span (its block may then span keyframes), or one whose wait is not
5973
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
5974
+ */
5975
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
5976
+ const waitMs = this.#multicastWaitMs(config);
5977
+ const allowanceMs = waitMs - config.interleaveDepthMs;
5978
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
5979
+ if (overlay === void 0) return allowanceMs;
5980
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
5981
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
5982
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
5274
5983
  }
5275
5984
  /**
5276
5985
  * Bring an open block's wait in to its late-source wait, when it has one.
@@ -5388,12 +6097,13 @@ var FECManager = class _FECManager {
5388
6097
  * the inactivity deadline on each symbol, records the symbol's in-band
5389
6098
  * classification evidence, and marks the block clean when all of its
5390
6099
  * authored source symbols arrived: the SSB_length a repair symbol declared,
5391
- * otherwise K.
6100
+ * otherwise K. `held` marks a source held unplaced since it arrived and
6101
+ * placed only now (see #noteSbnSeen).
5392
6102
  *
5393
6103
  * Throws for a packetId that was never configured, so a classified block
5394
6104
  * never reads the manager-global K or timeout.
5395
6105
  */
5396
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
6106
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
5397
6107
  const trackConfig = this.#trackConfigs.get(packetId);
5398
6108
  if (trackConfig === void 0) {
5399
6109
  throw new Error(
@@ -5409,7 +6119,8 @@ var FECManager = class _FECManager {
5409
6119
  catalogTrackName,
5410
6120
  "source",
5411
6121
  evidence.packetSequenceNumber,
5412
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
6122
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
6123
+ held
5413
6124
  );
5414
6125
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
5415
6126
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -5445,6 +6156,15 @@ var FECManager = class _FECManager {
5445
6156
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
5446
6157
  return;
5447
6158
  }
6159
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
6160
+ key,
6161
+ sbn,
6162
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
6163
+ packetId,
6164
+ catalogTrackName
6165
+ )) {
6166
+ return;
6167
+ }
5448
6168
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
5449
6169
  }
5450
6170
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -5453,7 +6173,9 @@ var FECManager = class _FECManager {
5453
6173
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5454
6174
  this.#blockSourceCounts.delete(key);
5455
6175
  this.#blockSourceEsis.delete(key);
6176
+ this.#blockRebuiltEsis.delete(key);
5456
6177
  this.#blockAuthoredLengths.delete(key);
6178
+ this.#isoSpanKeys.delete(key);
5457
6179
  this.#blockRepairRsIds.delete(key);
5458
6180
  this.#blockRsbLengths.delete(key);
5459
6181
  this.#markTerminal(key, sbn, packetId, true);
@@ -5484,6 +6206,19 @@ var FECManager = class _FECManager {
5484
6206
  #receiptNow() {
5485
6207
  return this.#receiptAtMs ?? performance.now();
5486
6208
  }
6209
+ /**
6210
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
6211
+ * scope: counted from the receipt time, as the timer of a symbol fed when
6212
+ * it was received was, less the whole ms since. So it fires on the tick
6213
+ * that timer would have, never later than a delay counted from now, and
6214
+ * its handler still re-arms a timer that fires before its deadline.
6215
+ * Counted from now, a deadline set from the receipt time is rounded up
6216
+ * from another fraction of a ms (BLO-52085).
6217
+ */
6218
+ #receiptTimerDelayMs(deadlineMs, minMs) {
6219
+ const receivedAtMs = this.#receiptAtMs;
6220
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
6221
+ }
5487
6222
  /**
5488
6223
  * A held packet admitted late arms from its (earlier) receipt time; that
5489
6224
  * never pulls in a deadline later activity already armed. Outside a
@@ -5532,6 +6267,7 @@ var FECManager = class _FECManager {
5532
6267
  }
5533
6268
  #failBlock(sbn, packetId, catalogTrackName) {
5534
6269
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
6270
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
5535
6271
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
5536
6272
  this.#clearRepairDeadline(key);
5537
6273
  this.#clearBlockTimer(key);
@@ -5541,6 +6277,7 @@ var FECManager = class _FECManager {
5541
6277
  }
5542
6278
  this.#blockSourceCounts.delete(key);
5543
6279
  this.#blockSourceEsis.delete(key);
6280
+ this.#blockRebuiltEsis.delete(key);
5544
6281
  this.#blockAuthoredLengths.delete(key);
5545
6282
  this.#blockRepairRsIds.delete(key);
5546
6283
  this.#blockRsbLengths.delete(key);
@@ -5550,7 +6287,8 @@ var FECManager = class _FECManager {
5550
6287
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
5551
6288
  this.#fecStats.blocksFailed++;
5552
6289
  this.#statsForPacket(packetId).blocksFailed++;
5553
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
6290
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
6291
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
5554
6292
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
5555
6293
  }
5556
6294
  /**
@@ -5579,7 +6317,9 @@ var FECManager = class _FECManager {
5579
6317
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
5580
6318
  this.#blockSourceCounts.delete(key);
5581
6319
  this.#blockSourceEsis.delete(key);
6320
+ this.#blockRebuiltEsis.delete(key);
5582
6321
  this.#blockAuthoredLengths.delete(key);
6322
+ this.#isoSpanKeys.delete(key);
5583
6323
  this.#blockRepairRsIds.delete(key);
5584
6324
  this.#blockRsbLengths.delete(key);
5585
6325
  this.#clearBlockTimer(key);
@@ -5628,7 +6368,7 @@ var FECManager = class _FECManager {
5628
6368
  blockDeliveryProvenance(sbn, packetId, catalogTrackName) {
5629
6369
  const counts = this.blockPathCount(sbn, packetId, catalogTrackName);
5630
6370
  if (!counts) return "unknown";
5631
- if (counts.moqSymbols > 0) return "mixed";
6371
+ if (counts.moqSymbols > 0 || counts.datagramSymbols > 0) return "mixed";
5632
6372
  if (counts.multicastSymbols > 0) return "multicast";
5633
6373
  return "unknown";
5634
6374
  }
@@ -5655,7 +6395,7 @@ var FECManager = class _FECManager {
5655
6395
  this.#activeBlockDeadlinesMs.clear();
5656
6396
  this.#blockWaitDeadlinesMs.clear();
5657
6397
  this.#repairHoldUntilMs.clear();
5658
- this.#deliveryGaps.reset();
6398
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.reset();
5659
6399
  this.#pendingWorkerCleanups.clear();
5660
6400
  this.#pendingWorkerCleanupClients.clear();
5661
6401
  for (const bound of this.#pendingWorkerCleanupBounds.values()) clearTimeout(bound.handle);
@@ -5670,7 +6410,9 @@ var FECManager = class _FECManager {
5670
6410
  this.#blockKeysBySbn.clear();
5671
6411
  this.#blockSourceCounts.clear();
5672
6412
  this.#blockSourceEsis.clear();
6413
+ this.#blockRebuiltEsis.clear();
5673
6414
  this.#blockAuthoredLengths.clear();
6415
+ this.#isoSpanKeys.clear();
5674
6416
  this.#blockRepairRsIds.clear();
5675
6417
  this.#blockRsbLengths.clear();
5676
6418
  this.#heldLayerStates.clear();
@@ -5704,6 +6446,7 @@ var FECManager = class _FECManager {
5704
6446
  this.#highestSbn.clear();
5705
6447
  this.#sourceFrontiers.clear();
5706
6448
  this.#isoLocators.clear();
6449
+ this.#runAnchors.clear();
5707
6450
  this.#sourceAnchors.clear();
5708
6451
  this.#trackConfigs.clear();
5709
6452
  this.#fecDecoders.clear();
@@ -5984,6 +6727,40 @@ var RUNTIME_FEC_RECEIVER2 = Object.freeze({
5984
6727
  overlays: true
5985
6728
  });
5986
6729
 
6730
+ // node_modules/@blockcast/mmt-base/dist/mmtp-siblings.js
6731
+ var MMTP_MODES2 = Object.freeze(["mfu", "mfu-datagram"]);
6732
+ var MMTP_SIBLING_HARD_FIELDS2 = Object.freeze([
6733
+ "namespace",
6734
+ "timescale",
6735
+ "presentationAnchorTicks",
6736
+ "groupDuration"
6737
+ ]);
6738
+ var MMTP_SIBLING_RENDITION_FIELDS2 = Object.freeze([
6739
+ "codec",
6740
+ "width",
6741
+ "height",
6742
+ "framerate",
6743
+ "bitrate",
6744
+ "samplerate",
6745
+ "channelConfig",
6746
+ "lang"
6747
+ ]);
6748
+ var MMTP_SIBLING_SOFT_FIELDS2 = Object.freeze([
6749
+ "initRef",
6750
+ "keyframeIntervalMs",
6751
+ "keyframeIntervalTicks",
6752
+ "isLive",
6753
+ "altGroup"
6754
+ ]);
6755
+
6756
+ // node_modules/@blockcast/mmt-base/dist/datagram-leg-size.js
6757
+ var DATAGRAM_LEG_UDP_FLOOR2 = 1200;
6758
+ var DATAGRAM_LEG_QUIC_WT_FRAMING2 = 48;
6759
+ var DATAGRAM_LEG_OBJECT_HEADER2 = 13;
6760
+ var DATAGRAM_LEG_RELAY_ROOM2 = 16;
6761
+ var DATAGRAM_LEG_DATAGRAM_MAX2 = DATAGRAM_LEG_UDP_FLOOR2 - DATAGRAM_LEG_QUIC_WT_FRAMING2;
6762
+ var DATAGRAM_LEG_BODY_MAX2 = DATAGRAM_LEG_DATAGRAM_MAX2 - DATAGRAM_LEG_OBJECT_HEADER2 - DATAGRAM_LEG_RELAY_ROOM2;
6763
+
5987
6764
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
5988
6765
  var DEFAULT_DWELL_MS = 3e3;
5989
6766
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -7049,9 +7826,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
7049
7826
  } catch (error) {
7050
7827
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
7051
7828
  }
7052
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
7829
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
7053
7830
  await rx.close();
7054
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7831
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7055
7832
  }
7056
7833
  const events = new EventTarget();
7057
7834
  let state = "connected";
@@ -10387,9 +11164,10 @@ function isH264IntraSlice(nal) {
10387
11164
  const sliceType = readH264SliceType(nal);
10388
11165
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
10389
11166
  }
11167
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
10390
11168
  function readH264SliceType(nal) {
10391
11169
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10392
- const rbsp = removeEmulationPrevention(nal.subarray(1));
11170
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
10393
11171
  const state = { bitOffset: 0 };
10394
11172
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10395
11173
  return readUnsignedExpGolomb(rbsp, state);
@@ -10536,6 +11314,96 @@ if (void 0) {
10536
11314
  ]))).toBe(false);
10537
11315
  });
10538
11316
  });
11317
+ describe("readH264SliceType", () => {
11318
+ const wholeNalSliceType = (nal) => {
11319
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
11320
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
11321
+ const state = { bitOffset: 0 };
11322
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
11323
+ return readUnsignedExpGolomb(rbsp, state);
11324
+ };
11325
+ const hex2 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
11326
+ const ue = (value) => {
11327
+ const code = (value + 1).toString(2);
11328
+ return "0".repeat(code.length - 1) + code;
11329
+ };
11330
+ const sliceNal = (bits) => {
11331
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
11332
+ const nal = [1];
11333
+ let zeros = 0;
11334
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
11335
+ if (zeros >= 2 && byte <= 3) {
11336
+ nal.push(3);
11337
+ zeros = 0;
11338
+ }
11339
+ nal.push(byte);
11340
+ zeros = byte === 0 ? zeros + 1 : 0;
11341
+ }
11342
+ return Uint8Array.from(nal);
11343
+ };
11344
+ const x264Slices = [
11345
+ ["64x48 P", hex2("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
11346
+ ["64x48 B", hex2("419e414212fffeeade283707cb70f7"), 6, false],
11347
+ ["64x48 non-IDR I", hex2(
11348
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
11349
+ ), 7, true],
11350
+ ["1280x720 B, escape at byte 10", hex2(
11351
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
11352
+ ), 6, false],
11353
+ ["1280x720 P, escape at byte 15", hex2(
11354
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
11355
+ ), 5, false],
11356
+ ["1280x720 B, escape at byte 22", hex2("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
11357
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex2(
11358
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
11359
+ ), null, true],
11360
+ ["7680x4320 P, first_mb_in_slice 32640", hex2(
11361
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
11362
+ ), 5, false],
11363
+ ["7680x4320 P, first_mb_in_slice 97440", hex2(
11364
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
11365
+ ), 5, false]
11366
+ ];
11367
+ const syntheticSlices = [
11368
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
11369
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
11370
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
11371
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
11372
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
11373
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
11374
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
11375
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
11376
+ ];
11377
+ test("reads the slice_type of real and synthetic slices", () => {
11378
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
11379
+ expect(readH264SliceType(nal), name).toBe(sliceType);
11380
+ }
11381
+ });
11382
+ test("matches the whole-NAL unescape at every truncation", () => {
11383
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
11384
+ for (let end = 0; end <= nal.length; end++) {
11385
+ const cut = nal.subarray(0, end);
11386
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
11387
+ }
11388
+ }
11389
+ });
11390
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
11391
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
11392
+ let seed = 1;
11393
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
11394
+ for (let i = 0; i < 5e3; i++) {
11395
+ const nal = new Uint8Array(2 + next() % 63);
11396
+ nal[0] = 65;
11397
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
11398
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
11399
+ }
11400
+ });
11401
+ test("classifies the x264 slices as keyframes or not", () => {
11402
+ for (const [name, nal, , keyframe] of x264Slices) {
11403
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
11404
+ }
11405
+ });
11406
+ });
10539
11407
  describe("avccToAnnexB", () => {
10540
11408
  test("converts with SPS/PPS on keyframe", () => {
10541
11409
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -13583,6 +14451,9 @@ function authoredGap(before, after) {
13583
14451
  function ssIdAfter(a, b) {
13584
14452
  return (a - b | 0) > 0;
13585
14453
  }
14454
+ function holdsRebuilt(stream) {
14455
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
14456
+ }
13586
14457
  var FecReleaseSequencer = class {
13587
14458
  #streams = /* @__PURE__ */ new Map();
13588
14459
  #gate;
@@ -13645,6 +14516,7 @@ var FecReleaseSequencer = class {
13645
14516
  stream.lastSbn = void 0;
13646
14517
  stream.discontinuity = false;
13647
14518
  stream.rapSsId = void 0;
14519
+ stream.sourced = false;
13648
14520
  }
13649
14521
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
13650
14522
  this.#recordStat("droppedStale");
@@ -13671,6 +14543,7 @@ var FecReleaseSequencer = class {
13671
14543
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
13672
14544
  else hi = mid;
13673
14545
  }
14546
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
13674
14547
  stream.buf.splice(lo, 0, frame);
13675
14548
  this.#drainUnlessDeferred(stream);
13676
14549
  }
@@ -13706,6 +14579,41 @@ var FecReleaseSequencer = class {
13706
14579
  }
13707
14580
  return false;
13708
14581
  }
14582
+ /**
14583
+ * These streams' sink is being replaced by one that has seen no source
14584
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
14585
+ * release to the sink being replaced the frames the unanchored path had
14586
+ * already released to it (#cursorPassed): there they waited in its queue,
14587
+ * which its replacement flushes. A stream that holds none is not drained:
14588
+ * it holds nothing the anchor kept back, and a drain would still force out
14589
+ * a frame held past the hold limit, which before the anchor waited for the
14590
+ * next push. Then treat the streams as unsourced until a source frame is
14591
+ * released.
14592
+ */
14593
+ unsource(packetId, catalogTrackName) {
14594
+ for (const stream of this.#streams.values()) {
14595
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
14596
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
14597
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
14598
+ else this.#drain(stream, true);
14599
+ }
14600
+ stream.sourced = false;
14601
+ }
14602
+ }
14603
+ }
14604
+ /**
14605
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
14606
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
14607
+ * packetId.
14608
+ */
14609
+ holdsRebuilt(packetId, catalogTrackName) {
14610
+ for (const stream of this.#streams.values()) {
14611
+ if (stream.packetId !== packetId) continue;
14612
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
14613
+ if (holdsRebuilt(stream)) return true;
14614
+ }
14615
+ return false;
14616
+ }
13709
14617
  /** Re-evaluate held gaps after FEC state changed. */
13710
14618
  poke(streamKey) {
13711
14619
  if (streamKey !== void 0) {
@@ -13797,16 +14705,32 @@ var FecReleaseSequencer = class {
13797
14705
  last: null,
13798
14706
  lastSbn: void 0,
13799
14707
  discontinuity: false,
13800
- rapSsId: void 0
14708
+ rapSsId: void 0,
14709
+ sourced: false,
14710
+ draining: 0
13801
14711
  };
13802
14712
  this.#streams.set(streamKey, stream);
13803
14713
  }
13804
14714
  return stream;
13805
14715
  }
13806
- #drain(stream) {
14716
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
14717
+ #drain(stream, asUnanchored = false) {
14718
+ stream.draining++;
14719
+ try {
14720
+ this.#drainLoop(stream, asUnanchored);
14721
+ } finally {
14722
+ stream.draining--;
14723
+ }
14724
+ }
14725
+ #drainLoop(stream, asUnanchored) {
13807
14726
  while (stream.buf.length > 0 && stream.last !== null) {
13808
14727
  const head = stream.buf[0];
13809
14728
  const last = stream.last;
14729
+ if (compareFrameOrder(head, last) <= 0) {
14730
+ stream.buf.shift();
14731
+ this.#release(stream, head, void 0);
14732
+ continue;
14733
+ }
13810
14734
  if (stream.discontinuity) {
13811
14735
  stream.discontinuity = false;
13812
14736
  stream.buf.shift();
@@ -13820,9 +14744,10 @@ var FecReleaseSequencer = class {
13820
14744
  }
13821
14745
  const headSbn = head.meta.fecSbn;
13822
14746
  const from = stream.lastSbn ?? headSbn;
13823
- const to = headSbn ?? stream.lastSbn;
14747
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
13824
14748
  let lost = [];
13825
14749
  const unanchored = from === void 0 && to === void 0;
14750
+ let unresolved = false;
13826
14751
  if (from !== void 0 && to !== void 0) {
13827
14752
  const resolved = this.#gate.resolvedLoss(
13828
14753
  stream.packetId,
@@ -13831,7 +14756,8 @@ var FecReleaseSequencer = class {
13831
14756
  Math.max(from, to),
13832
14757
  from
13833
14758
  );
13834
- if (resolved === null) {
14759
+ unresolved = resolved === null;
14760
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
13835
14761
  const heldMs = performance.now() - head.arrivedAtMs;
13836
14762
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
13837
14763
  this.#recordStat("forcedWindowFlushes");
@@ -13839,22 +14765,69 @@ var FecReleaseSequencer = class {
13839
14765
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
13840
14766
  continue;
13841
14767
  }
13842
- lost = resolved;
14768
+ lost = resolved ?? [];
13843
14769
  }
13844
14770
  stream.buf.shift();
13845
14771
  this.#release(
13846
14772
  stream,
13847
14773
  head,
13848
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
14774
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
13849
14775
  );
13850
14776
  }
13851
14777
  }
14778
+ /**
14779
+ * The head has waited out a gap only a late source can still fill
14780
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
14781
+ * the stream when it has (`wakeAt`), since no packet may come by then.
14782
+ */
14783
+ #unrepairableWaitOver(stream, last, head, from, to) {
14784
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
14785
+ if (waitMs === void 0) return false;
14786
+ const atMs = head.arrivedAtMs + waitMs;
14787
+ if (performance.now() >= atMs) return true;
14788
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
14789
+ return false;
14790
+ }
14791
+ /**
14792
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
14793
+ * source cursor holds it unanchored, and neither does a later frame behind
14794
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
14795
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
14796
+ * like each frame that arrived in front of it since (stale there). The head
14797
+ * then goes, decided as it would be unanchored, once a frame the base path
14798
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
14799
+ * marked one: the base path has passed that one, so a frame still missing
14800
+ * before it can only come from a repair. It also goes while no source frame
14801
+ * has been released, when the direct path shows a recovered frame at once.
14802
+ * And it goes at once while a staged switch decides on when frames arrive
14803
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
14804
+ * sink being replaced: unanchored, it had already reached the sink.
14805
+ * The scan also writes: the `passed` marks it sets stay on the frames,
14806
+ * and push marks a frame it inserts in front of a marked one from them.
14807
+ */
14808
+ #cursorPassed(stream, asUnanchored) {
14809
+ let at = -1;
14810
+ for (let i = 0; i < stream.buf.length; i++) {
14811
+ const frame = stream.buf[i];
14812
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
14813
+ frame.passed = true;
14814
+ if (at < 0) at = i;
14815
+ } else if (frame.passed !== true) break;
14816
+ }
14817
+ if (at < 0) return false;
14818
+ return asUnanchored || !stream.sourced || this.#gate.releaseUnanchored?.(stream.packetId, stream.catalogTrackName) === true || stream.buf.some(({ meta }, i) => i > at && meta.fecSbnFirst === void 0 && (meta.recovered !== true || meta.fecSbn !== void 0));
14819
+ }
13852
14820
  #release(stream, frame, decision) {
14821
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
14822
+ if (stale) this.#recordStat("droppedStale");
13853
14823
  if (decision) frame.meta.gapBefore = decision;
13854
14824
  stream.last = frame;
13855
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
14825
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
14826
+ stream.lastSbn = frame.meta.fecSbn;
14827
+ }
14828
+ if (frame.meta.recovered !== true) stream.sourced = true;
13856
14829
  this.#gate.onReleased?.(frame.data, frame.meta);
13857
- this.#emit(frame.data, frame.meta);
14830
+ if (!stale) this.#emit(frame.data, frame.meta);
13858
14831
  }
13859
14832
  };
13860
14833
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -14115,11 +15088,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
14115
15088
  /**
14116
15089
  * Typed view of the ISO-BMFF timing-sample budget.
14117
15090
  *
14118
- * This is the acceptance signal for the budget ratchet: `pending` walking
14119
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
14120
- * and it is observable here rather than only as media silently stopping.
14121
- * Per repo policy this is a producer-owned counter -- never infer budget
14122
- * state by parsing logs.
15091
+ * Each stream admits timing against its own window of `capacity` slots
15092
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
15093
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
15094
+ * timing a stream declared and never delivered shows up there. `pending`
15095
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
15096
+ * a producer-owned counter -- never infer budget state by parsing logs.
14123
15097
  */
14124
15098
  get timingBudgetStats() {
14125
15099
  return {
@@ -14179,6 +15153,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
14179
15153
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
14180
15154
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
14181
15155
  }
15156
+ /** See FecReleaseSequencer.unsource. */
15157
+ unsourceFecRelease(packetId, catalogTrackName) {
15158
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
15159
+ }
15160
+ /** See FecReleaseSequencer.holdsRebuilt. */
15161
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
15162
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
15163
+ }
14182
15164
  /** Re-evaluate held gaps after FEC block state changed. */
14183
15165
  pokeFecRelease(packetId, catalogTrackName) {
14184
15166
  if (!this.#fecSequencer) return;
@@ -14432,7 +15414,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14432
15414
  if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
14433
15415
  const pendingBefore = resolver2.pendingSampleCount;
14434
15416
  const evictedBefore = resolver2.evictedSampleCount;
14435
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
15417
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
14436
15418
  const admitted = resolver2.addMovieFragment(
14437
15419
  mpu.mpuSequenceNumber,
14438
15420
  data,
@@ -14505,7 +15487,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14505
15487
  info,
14506
15488
  resolver,
14507
15489
  options?.recovered === true,
14508
- options?.fecSbn
15490
+ options?.fecSbn,
15491
+ options?.fecSbnFirst
14509
15492
  );
14510
15493
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
14511
15494
  }
@@ -14598,7 +15581,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14598
15581
  info,
14599
15582
  resolver,
14600
15583
  options?.recovered === true,
14601
- options?.fecSbn
15584
+ options?.fecSbn,
15585
+ options?.fecSbnFirst
14602
15586
  );
14603
15587
  if (outcome.record !== void 0) return outcome.record;
14604
15588
  return this.#drop(outcome.reason);
@@ -14618,7 +15602,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14618
15602
  * attribution exists to keep readable. Leaving the choice at the call site
14619
15603
  * is what keeps both true.
14620
15604
  */
14621
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
15605
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
14622
15606
  const timing = resolver.sampleTiming(
14623
15607
  combined.mpuSequenceNumber,
14624
15608
  combined.movieFragmentSequenceNumber,
@@ -14635,6 +15619,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14635
15619
  );
14636
15620
  if (!meta) return { reason: "combined-meta-build-failed" };
14637
15621
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
15622
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
14638
15623
  if (!resolver.consumeSample(
14639
15624
  combined.mpuSequenceNumber,
14640
15625
  combined.movieFragmentSequenceNumber,
@@ -18139,7 +19124,18 @@ function keyframeOverlaySsId(header) {
18139
19124
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
18140
19125
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
18141
19126
  }
19127
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
19128
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
19129
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
19130
+ }
19131
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
19132
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
19133
+ return headerPsn + offset >>> 0;
19134
+ }
19135
+ var OVERLAY_ROUTED_LIMIT = 1024;
19136
+ var OVERLAY_PENDING_LIMIT = 256;
18142
19137
  var OVERLAY_OFFSET_MPUS = 16;
19138
+ var OVERLAY_REBUILT_LIMIT = 256;
18143
19139
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
18144
19140
  function assertStreamIdentity(role, stream) {
18145
19141
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -18250,6 +19246,7 @@ var MmtpRouter = class {
18250
19246
  #provenance = /* @__PURE__ */ new Map();
18251
19247
  #onFlowProtected = null;
18252
19248
  #unadmittedListedDrops = 0;
19249
+ #admittedSourceDatagrams = 0;
18253
19250
  #unlistedRepairSetAside = 0;
18254
19251
  #assistBlocks = /* @__PURE__ */ new Map();
18255
19252
  #assistFailures = /* @__PURE__ */ new Map();
@@ -18266,6 +19263,20 @@ var MmtpRouter = class {
18266
19263
  /** The flow whose receiver admitted a stream's source datagrams, by packetId then catalog track name: recovered packets answer to it. */
18267
19264
  #provenanceStreamFlow = /* @__PURE__ */ new Map();
18268
19265
  #unregisteredFlowDrops = 0;
19266
+ /** "mfu-datagram" leg packets of a packet id the ingress does not name (never the signaling flow). */
19267
+ #datagramLegIngressDrops = 0;
19268
+ /** "mfu-datagram" leg packets of the signaling flow (packet id 0): expected, one per group. */
19269
+ #datagramLegSignalingPackets = 0;
19270
+ /**
19271
+ * The streams a live "mfu-datagram" leg has fed, catalog track names by
19272
+ * packet id: their ledgers and release gate take the leg's bounds. A stream
19273
+ * leaves when its leg does: `endDatagramLeg`, `resetTrack`, `dispose`, or
19274
+ * the first multicast packet of its packet id (the ordered switch retires
19275
+ * the leg first). The "mfu" sibling shares the packet id, never the name.
19276
+ */
19277
+ #datagramLegStreams = /* @__PURE__ */ new Map();
19278
+ /** The leg's presentation budget (setDatagramLegPresentationBudget), or null: no presentation bound. */
19279
+ #datagramLegPresentationBudgetMs = null;
18269
19280
  #ambiguousRecoveredDrops = 0;
18270
19281
  // Temp state set by #processMMTP before calling parser.feed(),
18271
19282
  // read by the parser's onFrame callback for CMAF assembly + dedup.
@@ -18306,6 +19317,26 @@ var MmtpRouter = class {
18306
19317
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
18307
19318
  */
18308
19319
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
19320
+ /**
19321
+ * Per stream, the SS_ID offset at which a base recovery last showed the
19322
+ * sender's own packet_sequence_number: a recovered packet's header psn
19323
+ * equal to its SS_ID minus that offset. While it equals the stream's
19324
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
19325
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
19326
+ * an MPU no member of which arrived).
19327
+ */
19328
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
19329
+ /**
19330
+ * The same, shown by the overlay alone, before any base recovery did: a
19331
+ * packet it rebuilt whose base copy carries its protected psn
19332
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
19333
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
19334
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
19335
+ * make the base drop a late base copy of a keyframe the overlay never
19336
+ * finished, and lift a block's late-source cut, which nothing before
19337
+ * this offset did.
19338
+ */
19339
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18309
19340
  /**
18310
19341
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
18311
19342
  * not parsed, typically because its overlap copy was parsed first
@@ -18351,6 +19382,8 @@ var MmtpRouter = class {
18351
19382
  // end: a synchronous recovery completes its block BEFORE routing the
18352
19383
  // recovered frames, and releasing a held gap in between would strand them.
18353
19384
  #fecPokeDepth = 0;
19385
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
19386
+ #fecWakes = /* @__PURE__ */ new Map();
18354
19387
  #pendingFecPokes = /* @__PURE__ */ new Map();
18355
19388
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
18356
19389
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -18375,7 +19408,9 @@ var MmtpRouter = class {
18375
19408
  recovered: 0,
18376
19409
  restarts: 0,
18377
19410
  unsequencedDropped: 0,
18378
- protectedDropped: 0
19411
+ protectedDropped: 0,
19412
+ baseFed: 0,
19413
+ baseUndetermined: 0
18379
19414
  };
18380
19415
  /** Callback fired when a delta-track FEC block completes or fails. */
18381
19416
  #onDeltaBlockCompleteCb = null;
@@ -18581,13 +19616,18 @@ var MmtpRouter = class {
18581
19616
  this.#onDeltaBlockCompleteCb?.(packetId, false);
18582
19617
  }
18583
19618
  };
18584
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
19619
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
18585
19620
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
18586
19621
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
18587
19622
  this.#onDeltaBlockCompleteCb?.(packetId, true);
18588
19623
  }
18589
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18590
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19624
+ if (span === void 0) {
19625
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19626
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19627
+ } else {
19628
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19629
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19630
+ }
18591
19631
  };
18592
19632
  }
18593
19633
  }
@@ -18612,10 +19652,11 @@ var MmtpRouter = class {
18612
19652
  const blockLifetimeMs = fec.blockLifetimeMsForPacket(packetId);
18613
19653
  if (blockSpanMs === void 0 || blockLifetimeMs === void 0) return NO_FEC_GEOMETRY_HORIZON;
18614
19654
  if (blockSpanMs === 0) return NO_BLOCK_SPAN_HORIZON;
18615
- return {
18616
- kind: "fec-horizon",
18617
- retentionMs: duplicateRetentionMs({ blockSpanMs, blockLifetimeMs })
18618
- };
19655
+ let retentionMs = duplicateRetentionMs({ blockSpanMs, blockLifetimeMs });
19656
+ if (this.#datagramLegStreams.has(packetId)) {
19657
+ retentionMs = Math.max(retentionMs, fec.datagramLegLedgerRetentionMsForPacket?.(packetId) ?? 0);
19658
+ }
19659
+ return { kind: "fec-horizon", retentionMs };
18619
19660
  }
18620
19661
  /**
18621
19662
  * Init segments rejected since construction because their packetId had no
@@ -18632,8 +19673,9 @@ var MmtpRouter = class {
18632
19673
  }
18633
19674
  /**
18634
19675
  * FEC-recovered source symbols whose reconstructed header named a
18635
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
18636
- * a hop re-stamped the sequence after the sender protected the packet.
19676
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
19677
+ * or, rebuilt by the overlay, than their base copy carries: a hop
19678
+ * re-stamped the sequence after the sender protected the packet.
18637
19679
  */
18638
19680
  get restampedRecoveredSequenceCount() {
18639
19681
  return this.#restampedRecoveredSeqs;
@@ -18812,6 +19854,7 @@ var MmtpRouter = class {
18812
19854
  enableMseAssembler(packetId, config, catalogTrackName) {
18813
19855
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
18814
19856
  const previous = this.#mseAssemblers.get(assemblerKey);
19857
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
18815
19858
  if (previous) {
18816
19859
  previous.flush();
18817
19860
  previous.dispose();
@@ -18962,7 +20005,8 @@ var MmtpRouter = class {
18962
20005
  fec,
18963
20006
  k,
18964
20007
  offsets: /* @__PURE__ */ new Map(),
18965
- moqBlocks: /* @__PURE__ */ new Set()
20008
+ moqBlocks: /* @__PURE__ */ new Set(),
20009
+ rebuilt: /* @__PURE__ */ new Map()
18966
20010
  };
18967
20011
  this.#overlays.set(repairPacketId, inst);
18968
20012
  return () => {
@@ -18992,12 +20036,18 @@ var MmtpRouter = class {
18992
20036
  */
18993
20037
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
18994
20038
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
20039
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
20040
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
20041
+ stream.overlayToBase.routed.clear();
20042
+ stream.overlayToBase.pending.clear();
20043
+ }
18995
20044
  }
18996
20045
  #resetOverlay(inst) {
18997
20046
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
18998
20047
  inst.last = void 0;
18999
20048
  inst.offsets.clear();
19000
20049
  inst.moqBlocks.clear();
20050
+ inst.rebuilt.clear();
19001
20051
  }
19002
20052
  #overlaysForSource(sourcePacketId, catalogTrackName) {
19003
20053
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -19029,7 +20079,7 @@ var MmtpRouter = class {
19029
20079
  const blockStart = placement.block.start;
19030
20080
  if (placement.span !== void 0) this.#replayOverlaySources(inst, placement.span.block.start, placement.span.placed);
19031
20081
  this.#replayOverlaySources(inst, blockStart, placement.placed);
19032
- if (source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
20082
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
19033
20083
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
19034
20084
  const recovered = fec.feedRepairSymbol(pid, repair.ssStart, repair.ssbLength, repair.rsId, repair.symbolData, name);
19035
20085
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, blockStart, recovered);
@@ -19037,7 +20087,7 @@ var MmtpRouter = class {
19037
20087
  #replayOverlaySources(inst, blockStart, placed) {
19038
20088
  const { fec, repairPacketId: pid, streamName: name } = inst;
19039
20089
  for (const { ssId, payload } of placed) {
19040
- if (payload.source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
20090
+ if (payload.source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
19041
20091
  if (payload.oversized) continue;
19042
20092
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
19043
20093
  const recovered = fec.feedSourceSymbol(pid, ssId, payload.symbolData, name);
@@ -19048,18 +20098,33 @@ var MmtpRouter = class {
19048
20098
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
19049
20099
  * every overlay installed for its source, at that SS_ID, with the bytes the
19050
20100
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
19051
- * included (7.1, 7.4.3).
19052
- */
19053
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
20101
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
20102
+ * FEC reads it.
20103
+ *
20104
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
20105
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
20106
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
20107
+ * the stream unstamped at the SS_ID offset it states, for the release gate
20108
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
20109
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
20110
+ */
20111
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
19054
20112
  if (this.#overlays.size === 0) return;
19055
20113
  const ssId = keyframeOverlaySsId(header);
19056
20114
  if (ssId === void 0) return;
20115
+ let rebuiltPsn;
19057
20116
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
19058
20117
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
20118
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
20119
+ inst.rebuilt.delete(ssId);
19059
20120
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
19060
20121
  if (identity !== null) {
19061
20122
  inst.offsets.delete(identity.mpuSequenceNumber);
19062
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
20123
+ inst.offsets.set(identity.mpuSequenceNumber, {
20124
+ psnOffset: ssId - sequenceNumber >>> 0,
20125
+ overlaySsId: ssId,
20126
+ ...baseSsId === void 0 ? {} : { baseSsId }
20127
+ });
19063
20128
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
19064
20129
  }
19065
20130
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -19075,12 +20140,20 @@ var MmtpRouter = class {
19075
20140
  });
19076
20141
  continue;
19077
20142
  }
19078
- if (source === "moq") this.#noteOverlayMoqBlock(inst, coords.sbn);
20143
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, coords.sbn);
19079
20144
  if (oversized) continue;
19080
20145
  const alreadyCompleted = fec.isBlockCompleted(coords.sbn, pid, name);
19081
20146
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
19082
20147
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
19083
20148
  }
20149
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
20150
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
20151
+ if (rebuiltPsn !== sequenceNumber) {
20152
+ this.#restampedRecoveredSeqs++;
20153
+ } else if (baseSsId !== void 0) {
20154
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
20155
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
20156
+ }
19084
20157
  }
19085
20158
  #noteOverlayMoqBlock(inst, blockStart) {
19086
20159
  inst.moqBlocks.add(blockStart);
@@ -19114,11 +20187,16 @@ var MmtpRouter = class {
19114
20187
  }
19115
20188
  /**
19116
20189
  * Route an overlay-recovered block's packets as source media of the
19117
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
19118
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
19119
- * base re-stamp, no block advance. Each packet's wire sequence is restored
19120
- * from its keyframe's own offset; without one, a stream the base never
19121
- * re-stamped keeps the header's sequence and any other drops the packet.
20190
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
20191
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
20192
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
20193
+ * base FEC recovered does, so it waits behind base frames still in flight,
20194
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
20195
+ * longer than unanchored; one whose base SS_ID is undetermined has no
20196
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
20197
+ * advance. Each packet's wire sequence is restored from its keyframe's own
20198
+ * offset; without one, a stream the base never re-stamped keeps the
20199
+ * header's sequence and any other drops the packet.
19122
20200
  */
19123
20201
  #routeOverlayRecovered(inst, blockStart, recovered) {
19124
20202
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -19138,22 +20216,139 @@ var MmtpRouter = class {
19138
20216
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
19139
20217
  const restamped = this.#restampedStreams.has(streamKey);
19140
20218
  const restored = /* @__PURE__ */ new Set();
20219
+ const baseSsIds = /* @__PURE__ */ new Map();
20220
+ const gateOnly = /* @__PURE__ */ new Set();
19141
20221
  const symbols = result.symbols.flatMap((sym) => {
19142
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19143
- if (offset !== void 0) {
19144
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
20222
+ const overlaySsId = serial32Add(blockStart, sym.index);
20223
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
20224
+ if (anchor !== void 0) {
20225
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
19145
20226
  restored.add(packetSequenceNumber);
19146
- return [{ ...sym, packetSequenceNumber }];
20227
+ const out = { ...sym, packetSequenceNumber };
20228
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
20229
+ if (baseSsId !== void 0) {
20230
+ baseSsIds.set(sym.index, baseSsId);
20231
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
20232
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
20233
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
20234
+ }
20235
+ }
20236
+ return [out];
20237
+ }
20238
+ if (!restamped) {
20239
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
20240
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
20241
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
20242
+ if (baseSsId !== void 0) {
20243
+ baseSsIds.set(sym.index, baseSsId);
20244
+ if (fedSsId === void 0) gateOnly.add(sym.index);
20245
+ } else {
20246
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
20247
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
20248
+ }
20249
+ return [sym];
19147
20250
  }
19148
- if (!restamped) return [sym];
19149
20251
  this.#overlayStats.unsequencedDropped++;
19150
20252
  return [];
19151
20253
  });
19152
20254
  this.#overlayStats.recovered++;
20255
+ const mpuFirst = /* @__PURE__ */ new Map();
20256
+ for (const sym of symbols) {
20257
+ const ssId = baseSsIds.get(sym.index);
20258
+ const mpu = sym.fragment.mpuSequenceNumber;
20259
+ const first = mpuFirst.get(mpu);
20260
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
20261
+ }
20262
+ const firstSsIds = /* @__PURE__ */ new Map();
20263
+ for (const sym of symbols) {
20264
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
20265
+ }
19153
20266
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
19154
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
20267
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
20268
+ baseSsIds,
20269
+ firstSsIds
19155
20270
  });
19156
20271
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
20272
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
20273
+ }
20274
+ /**
20275
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
20276
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
20277
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
20278
+ * base recovery showed; `baseSsIds` holds no other),
20279
+ * so it is fed to the base decoder as a rebuilt source
20280
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
20281
+ * fewer to solve, and its repair can recover the block's other packets.
20282
+ * A base block no repair has stated yet takes it when one does
20283
+ * (#feedPendingRebuilt).
20284
+ *
20285
+ * The overlay route already handled each packet fed (delivered it, or
20286
+ * held an untimed head for its FT=1), so a base recovery routes none of
20287
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
20288
+ * held head would wait in the parser for timing its first copy consumed.
20289
+ * Only an overlay block decoded from multicast symbols alone is fed: with
20290
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
20291
+ * that crossed no multicast socket, which the provenance counted from the
20292
+ * block's own arrivals cannot show.
20293
+ */
20294
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
20295
+ const fec = this.#fecManager;
20296
+ const owner = inst.leg.sourcePacketId;
20297
+ const name = inst.leg.sourceCatalogTrackName;
20298
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
20299
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
20300
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
20301
+ const feeds = [];
20302
+ for (const sym of symbols) {
20303
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
20304
+ const ssId = baseSsIds.get(sym.index);
20305
+ if (ssId === void 0) {
20306
+ this.#overlayStats.baseUndetermined++;
20307
+ continue;
20308
+ }
20309
+ routed.delete(ssId);
20310
+ routed.add(ssId);
20311
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
20312
+ feeds.push([ssId, sym.rawSymbol]);
20313
+ }
20314
+ for (const [ssId, symbolData] of feeds) {
20315
+ if (this.#classifyPacketId(owner) === null) return;
20316
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
20317
+ }
20318
+ }
20319
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
20320
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
20321
+ const fec = this.#fecManager;
20322
+ if (!fec?.feedRebuiltSourceSymbol) return;
20323
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
20324
+ if (coords == null) {
20325
+ const pending = this.#stream(owner, name).overlayToBase.pending;
20326
+ pending.delete(ssId);
20327
+ pending.set(ssId, symbolData.slice());
20328
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
20329
+ return;
20330
+ }
20331
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
20332
+ if (!fed.taken) return;
20333
+ this.#overlayStats.baseFed++;
20334
+ if (fed.recovered === null) return;
20335
+ const sbn = coords.sbn;
20336
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
20337
+ fec.cancelBlockTimeout(sbn, owner, name);
20338
+ fec.countRecovery(owner, sbn, name);
20339
+ fec.markBlockCompleted(sbn, owner, name);
20340
+ });
20341
+ }
20342
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
20343
+ #feedPendingRebuilt(owner, name, block) {
20344
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
20345
+ if (pending === void 0 || pending.size === 0) return;
20346
+ for (const [ssId, symbolData] of [...pending]) {
20347
+ if (this.#classifyPacketId(owner) === null) return;
20348
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
20349
+ pending.delete(ssId);
20350
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
20351
+ }
19157
20352
  }
19158
20353
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
19159
20354
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -19293,6 +20488,10 @@ var MmtpRouter = class {
19293
20488
  get unadmittedListedDropCount() {
19294
20489
  return this.#unadmittedListedDrops;
19295
20490
  }
20491
+ /** 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. */
20492
+ get admittedSourceDatagramCount() {
20493
+ return this.#admittedSourceDatagrams;
20494
+ }
19296
20495
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
19297
20496
  get unlistedRepairSetAsideCount() {
19298
20497
  return this.#unlistedRepairSetAside;
@@ -19530,6 +20729,46 @@ var MmtpRouter = class {
19530
20729
  get unregisteredFlowDropCount() {
19531
20730
  return this.#unregisteredFlowDrops;
19532
20731
  }
20732
+ /** "mfu-datagram" leg packets dropped because the leg's ingress does not name their packet id (packet id 0 apart). */
20733
+ get datagramLegIngressDropCount() {
20734
+ return this.#datagramLegIngressDrops;
20735
+ }
20736
+ /** "mfu-datagram" leg packets of the MMTP signaling flow (packet id 0), which no track owns. */
20737
+ get datagramLegSignalingPacketCount() {
20738
+ return this.#datagramLegSignalingPackets;
20739
+ }
20740
+ /**
20741
+ * The "mfu-datagram" leg's presentation bound (mmt-02 6.1 step 6): how
20742
+ * long after a frame arrives it must leave the release gate when the gap
20743
+ * before it holds no RAP, FT=0 or FT=1 data (the player's presentation
20744
+ * delay less its decode lead). The gap is then decided at the earlier of
20745
+ * the FEC block deadline and this bound; a gap that may hold a RAP keeps
20746
+ * the block deadline. Null, or a value that is not finite and positive:
20747
+ * the block deadline alone, as on multicast.
20748
+ */
20749
+ setDatagramLegPresentationBudget(budgetMs) {
20750
+ this.#datagramLegPresentationBudgetMs = budgetMs;
20751
+ }
20752
+ /**
20753
+ * The "mfu-datagram" leg is over (unsubscribed, or switched to another
20754
+ * path): no stream keeps its presentation bound or its ledger retention.
20755
+ * Parser, FEC and ledger state stay, so the packet ids continue on the
20756
+ * next path without an epoch. A later leg datagram starts a leg again.
20757
+ */
20758
+ endDatagramLeg() {
20759
+ this.#datagramLegStreams.clear();
20760
+ this.#datagramLegPresentationBudgetMs = null;
20761
+ }
20762
+ #datagramLegPresentationWaitMs(packetId, catalogTrackName) {
20763
+ if (this.#datagramLegPresentationBudgetMs === null || this.#datagramLegStreams.get(packetId)?.has(catalogTrackName) !== true) return void 0;
20764
+ let budgetMs;
20765
+ try {
20766
+ budgetMs = this.#datagramLegPresentationBudgetMs(packetId, catalogTrackName);
20767
+ } catch {
20768
+ return void 0;
20769
+ }
20770
+ return Number.isFinite(budgetMs) && budgetMs > 0 ? budgetMs : void 0;
20771
+ }
19533
20772
  /** Recovered packets dropped because more than one protected flow could own their stream. */
19534
20773
  get ambiguousRecoveredDropCount() {
19535
20774
  return this.#ambiguousRecoveredDrops;
@@ -19547,6 +20786,10 @@ var MmtpRouter = class {
19547
20786
  * caller that forgot it silently attributed its bytes to a multicast socket
19548
20787
  * they may never have crossed — and that attribution is what the physical-
19549
20788
  * delivery evidence path is built on. Absence is not multicast; say which.
20789
+ * `"moq-datagram"` is an "mfu-datagram" subscription (MmtpIngestSource):
20790
+ * `ingress.tracks` MUST name the datagram catalog track for its packet id,
20791
+ * and a packet of a packet id it does not name is dropped and counted
20792
+ * (`datagramLegIngressDropCount`; the signaling flow, packet id 0, apart).
19550
20793
  */
19551
20794
  feedPacket(packet, source, ingress) {
19552
20795
  if (this.#disposed) return;
@@ -19596,15 +20839,18 @@ var MmtpRouter = class {
19596
20839
  }
19597
20840
  /**
19598
20841
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
19599
- * header and delegates to FECManager for FEC recovery.
20842
+ * header and delegates to FECManager for FEC recovery. `source` is
20843
+ * `"moq-datagram"` for a repair object of an "mfu-datagram" track's repair
20844
+ * track, which arrives as a datagram and so counts as an in-band symbol of
20845
+ * the leg; a FETCHed repair stays `"moq"` (RepairVia `quic`).
19600
20846
  */
19601
- feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
20847
+ feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source = "moq") {
19602
20848
  if (this.#disposed) return;
19603
20849
  this.#withDeferredFecPokes(() => {
19604
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
20850
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source);
19605
20851
  });
19606
20852
  }
19607
- #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, admitted = false) {
20853
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source, admitted = false) {
19608
20854
  let header;
19609
20855
  try {
19610
20856
  header = parseMMTPHeader(packet);
@@ -19614,7 +20860,7 @@ var MmtpRouter = class {
19614
20860
  const repairPacketId = header.packetId;
19615
20861
  const overlay = this.#overlayRepairTarget(repairPacketId, repairTrackName);
19616
20862
  if (overlay !== void 0) {
19617
- this.#routeOverlayRepair(overlay, repairPacketId, packet, header, "moq");
20863
+ this.#routeOverlayRepair(overlay, repairPacketId, packet, header, source);
19618
20864
  return;
19619
20865
  }
19620
20866
  const hintedOwner = ownerPacketIdHint != null && this.#classifyPacketId(ownerPacketIdHint) !== null ? ownerPacketIdHint : null;
@@ -19626,7 +20872,7 @@ var MmtpRouter = class {
19626
20872
  }
19627
20873
  let unlisted = false;
19628
20874
  if (ownerPacketId != null && !admitted) {
19629
- const admit = this.#admitUnicast(repairPacketId, packet, () => this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, true));
20875
+ const admit = this.#admitUnicast(repairPacketId, packet, () => this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source, true));
19630
20876
  if (admit === "held" || admit === "dropped") return;
19631
20877
  unlisted = admit === "unlisted";
19632
20878
  }
@@ -19647,7 +20893,7 @@ var MmtpRouter = class {
19647
20893
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
19648
20894
  return;
19649
20895
  }
19650
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
20896
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, source, repairTrackName);
19651
20897
  }
19652
20898
  }
19653
20899
  // ── Packet FEC geometry and block profile ───────────────────────
@@ -19779,6 +21025,8 @@ var MmtpRouter = class {
19779
21025
  )) return;
19780
21026
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
19781
21027
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
21028
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
21029
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
19782
21030
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
19783
21031
  const recovered = fec.feedRepairSymbol(
19784
21032
  ownerPacketId,
@@ -19829,7 +21077,7 @@ var MmtpRouter = class {
19829
21077
  catalogTrackName
19830
21078
  )) continue;
19831
21079
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
19832
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
21080
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
19833
21081
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
19834
21082
  }
19835
21083
  if (payload.oversized) continue;
@@ -19850,6 +21098,7 @@ var MmtpRouter = class {
19850
21098
  debugRouter(
19851
21099
  `[MmtpRouter] Dropping repair packet pid=${packetId}: physical PID is unregistered`
19852
21100
  );
21101
+ this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
19853
21102
  return null;
19854
21103
  }
19855
21104
  const registeredOwners = this.#repairOwnersByPacketId.get(packetId) ?? /* @__PURE__ */ new Set();
@@ -19858,6 +21107,7 @@ var MmtpRouter = class {
19858
21107
  debugRouter(
19859
21108
  `[MmtpRouter] Dropping repair packet pid=${packetId}: catalog owner is ${owners.length === 0 ? "absent" : "ambiguous"}`
19860
21109
  );
21110
+ this.#fecManager?.countUnresolvedRepairOwner?.(owners.length === 0 ? "ownerAbsent" : "ownerAmbiguous");
19861
21111
  return null;
19862
21112
  }
19863
21113
  /** Route a recovered FEC block through the parser + dedup pipeline.
@@ -19907,6 +21157,8 @@ var MmtpRouter = class {
19907
21157
  }
19908
21158
  this.#parser.resetTrack(packetId, catalogTrackName);
19909
21159
  this.resetKeyframeOverlays(packetId, catalogTrackName);
21160
+ const legNames = this.#datagramLegStreams.get(packetId);
21161
+ if (legNames?.delete(catalogTrackName) && legNames.size === 0) this.#datagramLegStreams.delete(packetId);
19910
21162
  this.#restampedStreams.delete(this.#mediaStreamKey(packetId, catalogTrackName));
19911
21163
  const assistPrefix = assistKey(packetId, catalogTrackName, 0).slice(0, -1);
19912
21164
  for (const key of this.#assistBlocks.keys()) if (key.startsWith(assistPrefix)) this.#assistBlocks.delete(key);
@@ -19916,6 +21168,8 @@ var MmtpRouter = class {
19916
21168
  this.#droppedPreSyncVideo.delete(streamKey);
19917
21169
  this.#latestVideoSeqByStream.delete(streamKey);
19918
21170
  this.#ssIdSeqOffsetByStream.delete(streamKey);
21171
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
21172
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
19919
21173
  this.#multicastRapTwinByStream.delete(streamKey);
19920
21174
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19921
21175
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -20042,6 +21296,12 @@ var MmtpRouter = class {
20042
21296
  * the outgoing stream stops. The hold is bounded by the incoming stream's
20043
21297
  * own RAP cadence, so no timer is involved.
20044
21298
  *
21299
+ * While the switch is staged, the FEC release gate lets a keyframe the
21300
+ * overlay rebuilt reach it, on either side, when the keyframe did before
21301
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
21302
+ * decides on what each side delivered, and the commit discards the gate's
21303
+ * frames of the outgoing stream.
21304
+ *
20045
21305
  * The commit is one synchronous transition inside the frame path: the
20046
21306
  * outgoing stream's already-admitted frames are released (its queued FEC
20047
21307
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -20092,6 +21352,9 @@ var MmtpRouter = class {
20092
21352
  droppedIncomingFrames: 0
20093
21353
  };
20094
21354
  this.#staged = state;
21355
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
21356
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
21357
+ }
20095
21358
  return {
20096
21359
  cancel: () => {
20097
21360
  if (this.#staged !== state) return false;
@@ -20174,7 +21437,17 @@ var MmtpRouter = class {
20174
21437
  */
20175
21438
  #routeParsedFrame(data, meta) {
20176
21439
  if (this.#classifyPacketId(meta.packetId) === null) return;
20177
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
21440
+ if (this.#staged !== null) {
21441
+ let consumed = false;
21442
+ this.#fecPokeDepth++;
21443
+ try {
21444
+ consumed = this.#interceptSwitchFrame(data, meta);
21445
+ } finally {
21446
+ this.#fecPokeDepth--;
21447
+ this.#flushPendingFecPokes();
21448
+ }
21449
+ if (consumed) return;
21450
+ }
20178
21451
  this.#deliverParsedFrame(data, meta);
20179
21452
  }
20180
21453
  #commitStreamSwitch(state, rap, reason) {
@@ -20223,8 +21496,11 @@ var MmtpRouter = class {
20223
21496
  this.#disposed = true;
20224
21497
  this.#staged = null;
20225
21498
  this.cancelKeyframeLostTimer();
21499
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
21500
+ this.#fecWakes.clear();
20226
21501
  this.#parser.dispose();
20227
21502
  this.#streams.clear();
21503
+ this.endDatagramLeg();
20228
21504
  this.#trackPacketCallbacks.clear();
20229
21505
  this.#latestVideoSeqByStream.clear();
20230
21506
  this.#lastDirectSourceVideoTsByStream.clear();
@@ -20326,12 +21602,16 @@ var MmtpRouter = class {
20326
21602
  this.#parser.deferFecRelease(work);
20327
21603
  } finally {
20328
21604
  this.#fecPokeDepth--;
20329
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20330
- const pokes = [...this.#pendingFecPokes.values()];
20331
- this.#pendingFecPokes.clear();
20332
- for (const poke of pokes) {
20333
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20334
- }
21605
+ this.#flushPendingFecPokes();
21606
+ }
21607
+ }
21608
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
21609
+ #flushPendingFecPokes() {
21610
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
21611
+ const pokes = [...this.#pendingFecPokes.values()];
21612
+ this.#pendingFecPokes.clear();
21613
+ for (const poke of pokes) {
21614
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20335
21615
  }
20336
21616
  }
20337
21617
  }
@@ -20400,6 +21680,38 @@ var MmtpRouter = class {
20400
21680
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
20401
21681
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
20402
21682
  },
21683
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
21684
+ // late source can), its frame waits the late-symbol allowance when the
21685
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
21686
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
21687
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
21688
+ // unless the gap holds a stated block's loss: the overlay may rebuild
21689
+ // that MPU's FT=0, and the block's group then complete it), or
21690
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
21691
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
21692
+ // overlay protects) waits for that overlay's repair too (BLO-52085
21693
+ // D4). A run no repair has delimited instead waits for its FEC
21694
+ // deadline, whatever the decision (FECManager.isoRepairlessWaitMs). The
21695
+ // FEC check comes first: most held gaps are not behind such a span, and
21696
+ // deciding one scans both frames' bitstreams.
21697
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
21698
+ const fec = this.#fecManager;
21699
+ const { packetId, catalogTrackName } = after.meta;
21700
+ const arrivedAtMs = after.arrivedAtMs;
21701
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, false, arrivedAtMs);
21702
+ const presentationMs = this.#datagramLegPresentationWaitMs(packetId, catalogTrackName);
21703
+ if (!fec || allowanceMs === void 0 && presentationMs === void 0) return void 0;
21704
+ const decision = this.#decideGap(before, after, [], false);
21705
+ const mpu = before.meta.mpuSequenceNumber;
21706
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
21707
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
21708
+ return allowanceMs === void 0 ? void 0 : fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true, false, arrivedAtMs);
21709
+ }
21710
+ const waitMs = allowanceMs === void 0 ? void 0 : decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true, arrivedAtMs) : allowanceMs;
21711
+ if (decision.reason === "delta-lost" && !((fec.interleaveDepthMsForPacket?.(packetId) ?? 0) > 0)) return waitMs;
21712
+ if (presentationMs === void 0) return waitMs;
21713
+ return waitMs === void 0 ? presentationMs : Math.min(waitMs, presentationMs);
21714
+ },
20403
21715
  decide: (before, after, lostBlocks, discontinuity) => {
20404
21716
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
20405
21717
  this.#onFrameGap?.(decision);
@@ -20409,6 +21721,28 @@ var MmtpRouter = class {
20409
21721
  onRap: (packetId, catalogTrackName, ssId) => {
20410
21722
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
20411
21723
  },
21724
+ // One timer per stream, at the earliest wake asked: its drain re-arms
21725
+ // for the next frame still waiting.
21726
+ wakeAt: (packetId, catalogTrackName, atMs) => {
21727
+ if (this.#disposed) return;
21728
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
21729
+ const armed = this.#fecWakes.get(key);
21730
+ if (armed !== void 0 && armed.atMs <= atMs) return;
21731
+ if (armed !== void 0) clearTimeout(armed.timer);
21732
+ const timer = setTimeout(() => {
21733
+ this.#fecWakes.delete(key);
21734
+ this.#requestFecPoke(packetId, catalogTrackName);
21735
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
21736
+ this.#fecWakes.set(key, { atMs, timer });
21737
+ },
21738
+ // A staged switch commits on when each side's frames reach it
21739
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
21740
+ // they did unanchored.
21741
+ releaseUnanchored: (packetId, catalogTrackName) => {
21742
+ const staged = this.#staged;
21743
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
21744
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
21745
+ },
20412
21746
  onReleased: (data, meta) => {
20413
21747
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
20414
21748
  const timing = meta.authoredTiming;
@@ -20418,7 +21752,8 @@ var MmtpRouter = class {
20418
21752
  meta.catalogTrackName,
20419
21753
  meta.mpuSequenceNumber,
20420
21754
  timing.presentationTime,
20421
- timing.mediaTimescale
21755
+ timing.mediaTimescale,
21756
+ timing.decodeTime
20422
21757
  );
20423
21758
  }
20424
21759
  };
@@ -20436,8 +21771,20 @@ var MmtpRouter = class {
20436
21771
  #decideGap(before, after, lostBlocks, discontinuity) {
20437
21772
  const { packetId, catalogTrackName } = after.meta;
20438
21773
  const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
20439
- const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying";
20440
- const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
21774
+ const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying" && before.meta.movieFragmentSequenceNumber === after.meta.movieFragmentSequenceNumber;
21775
+ const mpu = before.meta.mpuSequenceNumber;
21776
+ const sameMpu = trackKind === "video" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu;
21777
+ const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(
21778
+ packetId,
21779
+ catalogTrackName,
21780
+ sameMpu ? {
21781
+ mpu,
21782
+ from: before.meta.authoredTiming,
21783
+ to: after.meta.authoredTiming,
21784
+ fromSsId: before.meta.fecSbn,
21785
+ toSsId: after.meta.fecSbnFirst ?? after.meta.fecSbn
21786
+ } : void 0
21787
+ ) === true;
20441
21788
  const evidence = (frame) => {
20442
21789
  const timing = frame.meta.authoredTiming;
20443
21790
  const sampleNumber = frame.meta.sampleNumber;
@@ -20550,20 +21897,37 @@ var MmtpRouter = class {
20550
21897
  const parsed = this.#parser.parsePacket(packet);
20551
21898
  if (!parsed) return;
20552
21899
  const info = parsed.info;
21900
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
20553
21901
  if (source === "multicast" && !manifestAdmitted) {
20554
21902
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
21903
+ } else if (source === "moq-datagram" && !manifestAdmitted) {
21904
+ this.#fecManager?.noteArrival?.("moq-datagram", info.packetId, info.sequenceNumber);
20555
21905
  }
20556
- if (source === "multicast" && !ingressHasPacketId(ingress, info.packetId)) {
21906
+ if (source !== "moq" && !ingressHasPacketId(ingress, info.packetId)) {
21907
+ if (source === "moq-datagram") {
21908
+ if (info.packetId === MMTP_SIGNALING_PACKET_ID) this.#datagramLegSignalingPackets++;
21909
+ else this.#datagramLegIngressDrops++;
21910
+ }
20557
21911
  debugRouter(
20558
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: absent from ingress tracks`
21912
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: absent from ingress tracks`
20559
21913
  );
20560
21914
  return;
20561
21915
  }
21916
+ if (source === "moq-datagram") {
21917
+ if (!info.isRepair) {
21918
+ let names = this.#datagramLegStreams.get(info.packetId);
21919
+ if (!names) this.#datagramLegStreams.set(info.packetId, names = /* @__PURE__ */ new Set());
21920
+ names.add(catalogTrackNameForPacket(ingress, info.packetId));
21921
+ }
21922
+ } else if (source === "multicast") {
21923
+ this.#datagramLegStreams.delete(info.packetId);
21924
+ }
20562
21925
  const packetRole = this.#packetIdRoles.get(info.packetId);
20563
- if (source === "multicast" && this.#classifyPacketId(info.packetId) === null && (!info.isRepair || packetRole !== "repair")) {
21926
+ if (source !== "moq" && this.#classifyPacketId(info.packetId) === null && (!info.isRepair || packetRole !== "repair")) {
20564
21927
  debugRouter(
20565
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: physical PID is unregistered`
21928
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: physical PID is unregistered`
20566
21929
  );
21930
+ if (info.isRepair) this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
20567
21931
  return;
20568
21932
  }
20569
21933
  if (!info.isRepair && hasAmbiguousCatalogTrackName(ingress, info.packetId)) {
@@ -20599,7 +21963,7 @@ var MmtpRouter = class {
20599
21963
  }
20600
21964
  return;
20601
21965
  }
20602
- if (source === "moq" && !manifestAdmitted) {
21966
+ if (source !== "multicast" && !manifestAdmitted) {
20603
21967
  const admit = this.#admitUnicast(info.packetId, packet, () => this.#processMMTP(packet, source, true, ingress, overlapCopy, true), overlapCopy);
20604
21968
  if (admit !== "unlisted") {
20605
21969
  if (admit === "admitted") this.#processMMTP(packet, source, true, ingress, overlapCopy);
@@ -20628,7 +21992,7 @@ var MmtpRouter = class {
20628
21992
  );
20629
21993
  if (!repair) return;
20630
21994
  if (ownerPacketId != null && this.#fecManager) {
20631
- if ((flowless && this.#userAgentGoverns(ownerPacketId) || source === "moq" && !manifestAdmitted) && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)) return;
21995
+ if ((flowless && this.#userAgentGoverns(ownerPacketId) || source !== "multicast" && !manifestAdmitted) && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)) return;
20632
21996
  this.#repairPidCounts[info.packetId] = (this.#repairPidCounts[info.packetId] || 0) + 1;
20633
21997
  const count = this.#repairPidCounts[info.packetId];
20634
21998
  if (count <= 2 || count % 500 === 0) {
@@ -20667,7 +22031,7 @@ var MmtpRouter = class {
20667
22031
  const fecSource = this.#fecManager !== null && fecPayloadId != null;
20668
22032
  const coords = fecSource && fecPayloadId ? this.#locateFecSource(info.packetId, catalogTrackName, fecPayloadId.ssId) ?? void 0 : void 0;
20669
22033
  duplicates.advance(coords?.sbn);
20670
- if (source === "multicast" && !overlapCopy && !releasedFromQuarantine && catalogTrackName !== void 0 && duplicates.predatesHorizon(info.sequenceNumber, fecPayloadId?.ssId)) {
22034
+ if (source !== "moq" && !overlapCopy && !releasedFromQuarantine && catalogTrackName !== void 0 && duplicates.predatesHorizon(info.sequenceNumber, fecPayloadId?.ssId)) {
20671
22035
  this.#publisherRestarts++;
20672
22036
  console.warn(
20673
22037
  `[MmtpRouter] publisher restart on pid=${info.packetId} track=${catalogTrackName}: packet_sequence_number=${info.sequenceNumber} predates the stream's FEC horizon; starting a new epoch`
@@ -20728,6 +22092,7 @@ var MmtpRouter = class {
20728
22092
  evidence: sourceSymbolEvidence(packet, parsed.header, info.rapFlag, info.sequenceNumber),
20729
22093
  oversized: !(this.#fecManager.isoSourceFits?.(info.packetId, rawSymbol.length) ?? false)
20730
22094
  }) ?? false;
22095
+ if (held) this.#requestFecPoke(info.packetId, catalogTrackName);
20731
22096
  parseSourceSymbol = held && !duplicates.parsedSymbols.has(ssId);
20732
22097
  }
20733
22098
  } else if (fecUnreadable && info.fecPayloadId) {
@@ -20831,7 +22196,8 @@ var MmtpRouter = class {
20831
22196
  parsed.header,
20832
22197
  info.sequenceNumber,
20833
22198
  info.rapFlag,
20834
- source
22199
+ source,
22200
+ fecPayloadId?.ssId
20835
22201
  );
20836
22202
  }
20837
22203
  }
@@ -20854,10 +22220,13 @@ var MmtpRouter = class {
20854
22220
  const feedOptions = {
20855
22221
  skipFecPayloadId: parserOptions?.skipFecPayloadId,
20856
22222
  recovered: parserOptions?.recovered,
20857
- source: parserOptions?.source,
22223
+ // Frame attribution is the transport path: an "mfu-datagram" object
22224
+ // crossed QUIC, so its frames are 'moq' (provenance 'mixed').
22225
+ source: parserOptions?.source === "moq-datagram" ? "moq" : parserOptions?.source,
20858
22226
  deliveryProvenance: parserOptions?.deliveryProvenance,
20859
22227
  catalogTrackName: parserOptions?.catalogTrackName,
20860
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
22228
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
22229
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
20861
22230
  };
20862
22231
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
20863
22232
  else this.#parser.feed(packet, feedOptions);
@@ -20981,7 +22350,8 @@ var MmtpRouter = class {
20981
22350
  if (stream === void 0) {
20982
22351
  stream = {
20983
22352
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
20984
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
22353
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
22354
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
20985
22355
  };
20986
22356
  byName.set(catalogTrackName, stream);
20987
22357
  }
@@ -21259,6 +22629,13 @@ var MmtpRouter = class {
21259
22629
  * frames by epoch only if pre-protection input ever matters.
21260
22630
  */
21261
22631
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
22632
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
22633
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
22634
+ result = {
22635
+ ...result,
22636
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
22637
+ };
22638
+ }
21262
22639
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
21263
22640
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
21264
22641
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -21315,7 +22692,12 @@ var MmtpRouter = class {
21315
22692
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
21316
22693
  if (ownerPacketId == null) return;
21317
22694
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21318
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22695
+ const fecSbnOf = (index) => {
22696
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22697
+ const fecSbn = overlay.baseSsIds.get(index);
22698
+ const fecSbnFirst = overlay.firstSsIds.get(index);
22699
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
22700
+ };
21319
22701
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21320
22702
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
21321
22703
  if (ssIdSeqOffset !== void 0) {
@@ -21323,7 +22705,10 @@ var MmtpRouter = class {
21323
22705
  ...result,
21324
22706
  symbols: result.symbols.map((sym) => {
21325
22707
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
21326
- if (wire === sym.packetSequenceNumber) return sym;
22708
+ if (wire === sym.packetSequenceNumber) {
22709
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
22710
+ return sym;
22711
+ }
21327
22712
  this.#restampedRecoveredSeqs++;
21328
22713
  this.#restampedStreams.add(streamKey);
21329
22714
  return { ...sym, packetSequenceNumber: wire };
@@ -22752,6 +24137,7 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
22752
24137
  stalls: 0,
22753
24138
  concealedBlocks: 0,
22754
24139
  concealedGaps: 0,
24140
+ undelimitedRunGaps: 0,
22755
24141
  concealedFrames: 0,
22756
24142
  concealedAudioMs: 0,
22757
24143
  vanishedBlocks: 0
@@ -22858,6 +24244,12 @@ function isNonNegativeSafeInteger(value) {
22858
24244
  function isSymbolCounts(value) {
22859
24245
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
22860
24246
  }
24247
+ function isSpanFailure(value) {
24248
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
24249
+ const length = value["length"];
24250
+ const sources = value["sources"];
24251
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
24252
+ }
22861
24253
  function isNullableNonNegative(value) {
22862
24254
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
22863
24255
  }
@@ -22877,7 +24269,10 @@ function isRepairLifecycleEvent(value) {
22877
24269
  case "recovered":
22878
24270
  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"]);
22879
24271
  case "failed":
22880
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
24272
+ return hasExactKeys(
24273
+ value,
24274
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
24275
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
22881
24276
  case "repair-preempted":
22882
24277
  case "repair-deferred":
22883
24278
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -23086,6 +24481,8 @@ var MulticastManager = class {
23086
24481
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
23087
24482
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
23088
24483
  #repairReleases = /* @__PURE__ */ new Map();
24484
+ /** Protected repair flows owned by each live repair-endpoint release. */
24485
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
23089
24486
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
23090
24487
  #overlayBindings = /* @__PURE__ */ new Map();
23091
24488
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -23143,7 +24540,7 @@ var MulticastManager = class {
23143
24540
  onPublisherRestart: (packetId, catalogTrackName) => {
23144
24541
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
23145
24542
  },
23146
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
24543
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
23147
24544
  const pathCount = this.#fec.blockPathCount(
23148
24545
  sbn,
23149
24546
  packetId,
@@ -23161,7 +24558,8 @@ var MulticastManager = class {
23161
24558
  symbols: {
23162
24559
  multicast: pathCount?.multicastSymbols ?? 0,
23163
24560
  moq: pathCount?.moqSymbols ?? 0
23164
- }
24561
+ },
24562
+ ...span === void 0 ? {} : { span }
23165
24563
  });
23166
24564
  },
23167
24565
  onFrameGap: (decision) => {
@@ -23246,9 +24644,17 @@ var MulticastManager = class {
23246
24644
  reason
23247
24645
  });
23248
24646
  };
24647
+ this.#fec.onUndelimitedRunGap = (packetId, catalogTrackName) => {
24648
+ this.#statsFor(packetId, catalogTrackName).undelimitedRunGaps++;
24649
+ };
23249
24650
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
23250
24651
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
23251
24652
  };
24653
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
24654
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
24655
+ if (binding === void 0) return void 0;
24656
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
24657
+ };
23252
24658
  this.#fec.onDecoderUnavailable = (event) => {
23253
24659
  this.#emitRepairLifecycle({
23254
24660
  version: 2,
@@ -23545,6 +24951,7 @@ var MulticastManager = class {
23545
24951
  assertPositiveGeometry("timescale", config.timescale);
23546
24952
  assertPositiveGeometry("keyframeIntervalTicks", config.keyframeIntervalTicks);
23547
24953
  assertPositiveGeometry("keyframeIntervalMs", config.keyframeIntervalMs);
24954
+ assertPositiveGeometry("groupDurationMs", config.groupDurationMs);
23548
24955
  assertNonNegativeGeometry("fecRepairSymbols", config.fecRepairSymbols);
23549
24956
  assertNonNegativeGeometry(
23550
24957
  "fecReorderToleranceMs",
@@ -23577,7 +24984,8 @@ var MulticastManager = class {
23577
24984
  timeoutMs: deliveryWindowMs,
23578
24985
  ...trackKind === void 0 ? {} : { trackKind },
23579
24986
  ...config.codec === void 0 ? {} : { codec: config.codec },
23580
- ...geometry2 === void 0 ? {} : { geometry: geometry2 }
24987
+ ...geometry2 === void 0 ? {} : { geometry: geometry2 },
24988
+ ...config.groupDurationMs === void 0 ? {} : { groupDurationMs: config.groupDurationMs }
23581
24989
  };
23582
24990
  this.#fec.configureTrack(packetId, fecConfig, catalogTrackName);
23583
24991
  this.#configureTrackMapper(packetId, fecConfig);
@@ -23751,6 +25159,9 @@ var MulticastManager = class {
23751
25159
  this.#transport.onFailback((reason) => {
23752
25160
  const joined = this.#provenanceJoin;
23753
25161
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
25162
+ for (const flows of this.#repairProvenanceFlows.values()) {
25163
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
25164
+ }
23754
25165
  this.#onFailback?.(reason);
23755
25166
  });
23756
25167
  }
@@ -23785,6 +25196,12 @@ var MulticastManager = class {
23785
25196
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
23786
25197
  );
23787
25198
  }
25199
+ if (provenanceFlow !== void 0) {
25200
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
25201
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
25202
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
25203
+ }
25204
+ }
23788
25205
  const staged = this.#renditionSwitch;
23789
25206
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
23790
25207
  this.configureFec(config);
@@ -23792,8 +25209,8 @@ var MulticastManager = class {
23792
25209
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
23793
25210
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
23794
25211
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
23795
- this.#releaseProvenanceJoin();
23796
25212
  const provenance = config.provenance;
25213
+ this.#releaseProvenanceJoin();
23797
25214
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
23798
25215
  const ingress = protectedTracks === void 0 ? void 0 : {
23799
25216
  tracks: Object.freeze(
@@ -23846,8 +25263,13 @@ var MulticastManager = class {
23846
25263
  * feeds the flow's receiver; media datagrams are held until one admits them.
23847
25264
  */
23848
25265
  #joinProvenance(provenance, ingress) {
25266
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
25267
+ this.#hookFailback();
25268
+ this.#provenanceJoin = { flow: ingress.flow };
25269
+ }
25270
+ #provenanceReceiver(provenance) {
23849
25271
  const { flow, auth } = provenance;
23850
- const receiver = new BcProvenanceV2Receiver({
25272
+ return new BcProvenanceV2Receiver({
23851
25273
  ...provenance.receiver,
23852
25274
  // The caller's ctx when it passes one, else the catalog's: an explicit
23853
25275
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -23864,9 +25286,6 @@ var MulticastManager = class {
23864
25286
  maxAuthDelayMs: flow.maxAuthDelayMs,
23865
25287
  manifestTimerMs: flow.manifestTimerMs
23866
25288
  });
23867
- this.#router.registerProvenanceFlow(ingress, receiver);
23868
- this.#hookFailback();
23869
- this.#provenanceJoin = { flow: ingress.flow };
23870
25289
  }
23871
25290
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
23872
25291
  #releaseProvenanceJoin() {
@@ -23897,8 +25316,25 @@ var MulticastManager = class {
23897
25316
  * callback delivers must come from a subscription opened on
23898
25317
  * `options.gateway`. A callback that also merges another source (a MoQ or
23899
25318
  * WebSocket repair feed) must not name a native provider here.
25319
+ *
25320
+ * An endpoint's `provenance` makes its group a protected flow of its own
25321
+ * (multicast-02 7.2.7), registered here and released with the group; its
25322
+ * records ride in band on the group's port. On the user-agent path a
25323
+ * flow-less repair group of a protected track is set aside, never read, so
25324
+ * a player joining a protected catalog's repair groups passes it.
23900
25325
  */
23901
25326
  joinRepairEndpoints(endpoints, provider, options) {
25327
+ for (const { provenance, flow, source, group, port } of endpoints) {
25328
+ if (provenance === void 0) continue;
25329
+ if (flow !== void 0) {
25330
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
25331
+ }
25332
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port !== provenance.flow.port) {
25333
+ throw new RangeError(
25334
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
25335
+ );
25336
+ }
25337
+ }
23902
25338
  const releases = [];
23903
25339
  let released = false;
23904
25340
  const safely = (each) => {
@@ -23908,17 +25344,36 @@ var MulticastManager = class {
23908
25344
  console.warn("[MulticastManager] repair group release failed", error);
23909
25345
  }
23910
25346
  };
25347
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
25348
+ const preparedProvenance = endpoints.map((endpoint) => {
25349
+ if (endpoint.provenance === void 0) return void 0;
25350
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
25351
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
25352
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
25353
+ }
25354
+ usedFlows.add(flow);
25355
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
25356
+ });
25357
+ const provenanceFlows = [];
23911
25358
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
23912
25359
  ...owner,
23913
25360
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
23914
25361
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
23915
25362
  }));
23916
25363
  this.#applyRepairOwners(repairOwners);
23917
- for (const endpoint of endpoints) {
25364
+ for (const [index, endpoint] of endpoints.entries()) {
25365
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
23918
25366
  const ingress = {
23919
25367
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
23920
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
25368
+ ...flow === void 0 ? {} : { flow }
23921
25369
  };
25370
+ if (endpoint.provenance !== void 0) {
25371
+ const prepared = preparedProvenance[index];
25372
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
25373
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
25374
+ provenanceFlows.push(prepared.flow);
25375
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
25376
+ }
23922
25377
  let sender;
23923
25378
  const feed = (packet, sourceAddress, ingressToFeed) => {
23924
25379
  if (released) return;
@@ -23948,7 +25403,7 @@ var MulticastManager = class {
23948
25403
  packetIds: endpoint.packetIds,
23949
25404
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
23950
25405
  // A protected repair group's records ride in band on its port (7.2.3).
23951
- ...endpoint.flow === void 0 ? {} : { protected: true }
25406
+ ...flow === void 0 ? {} : { protected: true }
23952
25407
  }, ingress).then((joined) => {
23953
25408
  if (!joined && !released) fail(transport.lastJoinOutcome);
23954
25409
  });
@@ -23957,9 +25412,12 @@ var MulticastManager = class {
23957
25412
  if (released) return;
23958
25413
  released = true;
23959
25414
  this.#repairReleases.delete(release);
25415
+ this.#repairProvenanceFlows.delete(release);
23960
25416
  for (const each of releases.splice(0)) safely(each);
23961
25417
  };
23962
25418
  this.#repairReleases.set(release, repairOwners);
25419
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
25420
+ if (provenanceFlows.length) this.#hookFailback();
23963
25421
  return release;
23964
25422
  }
23965
25423
  #applyRepairOwners(owners) {
@@ -24228,6 +25686,70 @@ var MulticastManager = class {
24228
25686
  feedPacket(data, ingress, sourceAddress) {
24229
25687
  this.#transport.feedPacket(data, ingress, sourceAddress);
24230
25688
  }
25689
+ /**
25690
+ * Start an "mfu-datagram" leg (draft-ramadan-moq-mmt-02 4.3.1): a
25691
+ * subscription whose objects arrive as datagrams, a lossy unicast path.
25692
+ * Arms the join-boundary rules exactly as a multicast join does (the leg
25693
+ * starts at an arbitrary datagram), keeping configured tracks, decoders
25694
+ * and diagnostics. No MulticastTransport is involved: no takeover, no
25695
+ * failback watchdog, no bridge. While the leg is up the player publishes
25696
+ * `datagramLegDiagnostics(...)` in its FEC stats (`DatagramLegDiagnostics`:
25697
+ * `datagramLegJoined`, `datagramLegIngressDrops`,
25698
+ * `datagramLegRepairBeforePacketId`, `datagramUnknownAlias`,
25699
+ * `transport.maxDatagramSize`), the same keys in every player.
25700
+ */
25701
+ startDatagramLeg(options = {}) {
25702
+ this.#router.setDatagramLegPresentationBudget(options.presentationBudgetMs ?? null);
25703
+ this.#fec.beginLegJoin();
25704
+ }
25705
+ /**
25706
+ * Feed one object of an "mfu-datagram" subscription (one MMTP packet) in
25707
+ * arrival order. `ingress.tracks` names the datagram catalog track for the
25708
+ * packet id; the router restores serial order, holds FEC sources until a
25709
+ * repair states their block, and declares loss at the block deadline
25710
+ * (mmt-02 5.3.3). Bypasses MulticastTransport, unlike `feedPacket`.
25711
+ */
25712
+ feedDatagramLegPacket(packet, ingress) {
25713
+ this.#router.feedPacket(packet, "moq-datagram", ingress);
25714
+ }
25715
+ /**
25716
+ * Feed one repair object of an "mfu-datagram" track's repair track (sent
25717
+ * as datagrams, mmt-02 4.3.1): the repair track's own packet id names no
25718
+ * owner, so the subscription supplies it, as `router.feedRepairPacket`
25719
+ * does for a MoQ repair; the symbol counts as in-band (`RepairVia`
25720
+ * `inband`), unlike a FETCHed repair.
25721
+ */
25722
+ feedDatagramLegRepair(packet, ownerPacketId, catalogTrackName, repairTrackName) {
25723
+ this.#router.feedRepairPacket(packet, ownerPacketId, catalogTrackName, repairTrackName, "moq-datagram");
25724
+ }
25725
+ /**
25726
+ * End the "mfu-datagram" leg: call it when the subscription is dropped and
25727
+ * before the first packet of the path that replaces it (the ordered switch
25728
+ * to multicast, a fallback to the "mfu" track). The leg's presentation
25729
+ * bound and ledger retention stop applying; tracks, decoders, FEC state
25730
+ * and diagnostics stay, so the next path continues without a new epoch.
25731
+ */
25732
+ stopDatagramLeg() {
25733
+ this.#router.endDatagramLeg();
25734
+ }
25735
+ /** "mfu-datagram" leg packets dropped because their packet id is not the leg's (`MmtpRouter.datagramLegIngressDropCount`). */
25736
+ get datagramLegIngressDropCount() {
25737
+ return this.#router.datagramLegIngressDropCount;
25738
+ }
25739
+ /**
25740
+ * The leg's diagnostics as one object with the shared names
25741
+ * (`DatagramLegDiagnostics`): the player supplies what it alone counts and
25742
+ * spreads the result into its published FEC stats while a leg is up.
25743
+ */
25744
+ datagramLegDiagnostics(player) {
25745
+ return {
25746
+ datagramLegJoined: player.joined,
25747
+ datagramLegIngressDrops: this.#router.datagramLegIngressDropCount,
25748
+ datagramLegRepairBeforePacketId: player.repairBeforePacketId,
25749
+ datagramUnknownAlias: player.unknownAlias,
25750
+ transport: { maxDatagramSize: player.maxDatagramSize ?? null }
25751
+ };
25752
+ }
24231
25753
  /**
24232
25754
  * Declare how packets given to feedPacket() reach this manager. A consumer
24233
25755
  * that owns the multicast socket itself declares its own leg; join()
@@ -24445,7 +25967,8 @@ var MulticastManager = class {
24445
25967
  blockProfile: parseFecBlockProfile(
24446
25968
  geometry2.blockProfile,
24447
25969
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
24448
- )
25970
+ ),
25971
+ geometry: geometry2
24449
25972
  });
24450
25973
  }
24451
25974
  }
@@ -24484,7 +26007,7 @@ var MulticastManager = class {
24484
26007
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
24485
26008
  const before = this.#overlayBindings.get(sourcePacketId);
24486
26009
  const after = overlayBindings.get(sourcePacketId);
24487
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
26010
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
24488
26011
  if (!same) install.dispose();
24489
26012
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
24490
26013
  else install.reattach();
@@ -24541,10 +26064,12 @@ var MulticastManager = class {
24541
26064
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
24542
26065
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
24543
26066
  * pending hole and reported here, and `closeIsoHoles` must be called for it
24544
- * once its range FETCH ends (or none is sent).
26067
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
26068
+ * pending hole the stream runs past the locator's horizon: returning true,
26069
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
24545
26070
  */
24546
- onUndelimitedLoss(cb) {
24547
- this.#fec.setUndelimitedLossHandler(cb);
26071
+ onUndelimitedLoss(cb, onExpired) {
26072
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
24548
26073
  }
24549
26074
  /**
24550
26075
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -24780,7 +26305,8 @@ var MulticastManager = class {
24780
26305
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
24781
26306
  ...event,
24782
26307
  block: Object.freeze({ ...event.block }),
24783
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
26308
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
26309
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
24784
26310
  }
24785
26311
  );
24786
26312
  if (this.#logRepairLifecycle) {